package org.dromara.personnel.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.personnel.domain.OpsCaigouPlan;
import org.dromara.personnel.domain.OpsCaigouPlanChanpin;
import org.dromara.personnel.domain.bo.OpsChurukudanReq;
import org.dromara.personnel.domain.dto.OpsChurukudanCountDto;
import org.dromara.personnel.domain.dto.OpsChurukudanDayCountDto;
import org.dromara.personnel.domain.enums.OpsChurukuEnum;
import org.dromara.personnel.domain.vo.OpsChurukudanCountVo;
import org.dromara.personnel.domain.vo.OpsChurukudanDayCountVo;
import org.dromara.personnel.service.IOpsCaigouPlanChanpinService;
import org.dromara.personnel.service.IOpsCaigouPlanService;
import org.dromara.personnel.utils.CglxdIdGenerator;
import org.springframework.stereotype.Service;
import org.dromara.personnel.domain.bo.OpsChurukudanBo;
import org.dromara.personnel.domain.vo.OpsChurukudanVo;
import org.dromara.personnel.domain.OpsChurukudan;
import org.dromara.personnel.mapper.OpsChurukudanMapper;
import org.dromara.personnel.service.IOpsChurukudanService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 运维-物资-出入库单管理Service业务层处理
 *
 * @author LionLi
 * @date 2025-09-24
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OpsChurukudanServiceImpl extends ServiceImpl<OpsChurukudanMapper,OpsChurukudan> implements IOpsChurukudanService {

    private final OpsChurukudanMapper baseMapper;

    private final IOpsCaigouPlanChanpinService caigouPlanChanpinService;
    private final IOpsCaigouPlanService caigouPlanService;

    /**
     * 查询运维-物资-出入库单管理
     *
     * @param id 主键
     * @return 运维-物资-出入库单管理
     */
    @Override
    public OpsChurukudanVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询运维-物资-出入库单管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 运维-物资-出入库单管理分页列表
     */
    @Override
    public TableDataInfo<OpsChurukudanVo> queryPageList(OpsChurukudanReq bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OpsChurukudan> lqw = buildQueryWrapper(bo);
        Page<OpsChurukudanVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的运维-物资-出入库单管理列表
     *
     * @param bo 查询条件
     * @return 运维-物资-出入库单管理列表
     */
    @Override
    public List<OpsChurukudanVo> queryList(OpsChurukudanReq bo) {
        LambdaQueryWrapper<OpsChurukudan> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OpsChurukudan> buildQueryWrapper(OpsChurukudanReq bo) {
        LambdaQueryWrapper<OpsChurukudan> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(OpsChurukudan::getId);
        lqw.eq(OpsChurukudan::getProjectId, bo.getProjectId());
        lqw.eq(StringUtils.isNotBlank(bo.getDanjvNumber()), OpsChurukudan::getDanjvNumber, bo.getDanjvNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getShenheStatus()), OpsChurukudan::getShenheStatus, bo.getShenheStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDanjvType()), OpsChurukudan::getDanjvType, bo.getDanjvType());
        lqw.between(bo.getStartDate()!=null && bo.getEndDate()!=null,OpsChurukudan::getCreateTime,bo.getStartDate(),bo.getEndDate());
        return lqw;
    }

    /**
     * 新增运维-物资-出入库单管理
     *
     * @param bo 运维-物资-出入库单管理
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OpsChurukudanBo bo) {
        OpsCaigouPlanChanpin planChanpin = caigouPlanChanpinService.getBaseMapper().selectById(bo.getChanpinId());
        if (planChanpin == null) {
            throw new ServiceException("产品不存在，请重新核对后提交");
        }
        OpsChurukudan add = MapstructUtils.convert(bo, OpsChurukudan.class);
        String generated =  "";
        Long count = baseMapper.getChuRuKuZonCount(bo.getProjectId(),bo.getChanpinId(),"2");
        if (OpsChurukuEnum.RUKU.getValue().equals(bo.getDanjvType())){
            generated = CglxdIdGenerator.generateId("RUKU");
            if (count+bo.getZonNumber() > planChanpin.getGoumaiNumber()){
                throw new ServiceException("超出计划总量，请核对后再提交");
            }
        }else {
            Long chuKuZonCount = baseMapper.getChuRuKuZonCount(bo.getProjectId(), bo.getChanpinId(), "1");
            if (chuKuZonCount+bo.getZonNumber() > count){
                throw new ServiceException("出库数量超出入库总量，请核对后再提交");
            }
            generated = CglxdIdGenerator.generateId("CHUKU");
        }
        OpsCaigouPlan opsCaigouPlan = caigouPlanService.getBaseMapper().selectById(planChanpin.getCaigouPlanId());
        add.setChanpinName(opsCaigouPlan.getJihuaName()+"-"+planChanpin.getChanpinName());
        add.setDanjvNumber(generated);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改运维-物资-出入库单管理
     *
     * @param bo 运维-物资-出入库单管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OpsChurukudanBo bo) {
        OpsChurukudan update = MapstructUtils.convert(bo, OpsChurukudan.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OpsChurukudan entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除运维-物资-出入库单管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 出入库类型分布
     * @param bo
     * @return
     */
    @Override
    public OpsChurukudanCountDto getChuRuKuCount(OpsChurukudanReq bo) {
        OpsChurukudanCountDto dto = new OpsChurukudanCountDto();

        List<String> shebeiType = new ArrayList<>();
        List<Long> rukuCounnt = new ArrayList<>();
        List<Long> chukuCounnt = new ArrayList<>();
        List<OpsChurukudanCountVo> countVoList = baseMapper.getChuRuKuCount(bo);
        for (OpsChurukudanCountVo count : countVoList) {
            shebeiType.add(count.getShebeiType());
            rukuCounnt.add(count.getRukuCounnt());
            chukuCounnt.add(count.getChukuCounnt());
        }
        dto.setShebeiType(shebeiType);
        dto.setRukuCounnt(rukuCounnt);
        dto.setChukuCounnt(chukuCounnt);
        return dto;
    }

    /**
     * 查询出入库月中每天的出入库数量
     * @param bo
     * @return
     */
    @Override
    public OpsChurukudanDayCountDto getChuRuKuDayCount(OpsChurukudanReq bo) {
        OpsChurukudanDayCountDto dto = new OpsChurukudanDayCountDto();
        List<String> days = new ArrayList<>();
        List<Long> rukuCounnt = new ArrayList<>();
        List<Long> chukuCounnt = new ArrayList<>();
        List<OpsChurukudanDayCountVo> churukudanDayCountVos = baseMapper.getChuRuKuDayCount(bo);
        for (OpsChurukudanDayCountVo count : churukudanDayCountVos) {
            days.add(count.getStatDay());
            rukuCounnt.add(count.getRukuCounnt());
            chukuCounnt.add(count.getChukuCounnt());
        }
        dto.setDays(days);
        dto.setRukuCounnts(rukuCounnt);
        dto.setChukuCounnts(chukuCounnt);
        return dto;
    }
}
