package com.zt.plat.module.qms.resource.material.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zt.plat.framework.common.exception.ServiceException;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigWarehouseLocationDO;
import com.zt.plat.module.qms.business.config.service.ConfigWarehouseLocationService;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialInventoryCheckDetailPageReqVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialInventoryCheckDetailRespVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialInventoryCheckDetailSaveReqVO;
import com.zt.plat.module.qms.resource.material.dal.dataobject.MaterialInfomationDO;
import com.zt.plat.module.qms.resource.material.dal.dataobject.MaterialInventoryCheckDetailDO;
import com.zt.plat.module.qms.resource.material.dal.dataobject.MaterialInventoryCheckItemDO;
import com.zt.plat.module.qms.resource.material.dal.dataobject.MaterialLifecycleDO;
import com.zt.plat.module.qms.resource.material.dal.mapper.MaterialInventoryCheckDetailMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.*;

/**
 * 库存盘点明细 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class MaterialInventoryCheckDetailServiceImpl implements MaterialInventoryCheckDetailService {

    @Resource
    private MaterialInventoryCheckDetailMapper materialInventoryCheckDetailMapper;
    @Autowired
    private MaterialInfomationService materialInfomationService;
    @Autowired
    private MaterialLifecycleService materialLifecycleService;
    @Autowired
    private MaterialInventoryCheckItemService materialInventoryCheckItemService;
    @Autowired
    private ConfigWarehouseLocationService configWarehouseLocationService;

    @Transactional
    @Override
    public MaterialInventoryCheckDetailRespVO createMaterialInventoryCheckDetail(MaterialInventoryCheckDetailSaveReqVO createReqVO) {
        MaterialInventoryCheckDetailDO checkDetailDO = BeanUtils.toBean(createReqVO, MaterialInventoryCheckDetailDO.class);
        // 插入
        materialInventoryCheckDetailMapper.insert(checkDetailDO);
        // 返回
        return BeanUtils.toBean(checkDetailDO, MaterialInventoryCheckDetailRespVO.class);
    }

    @Override
    public void updateMaterialInventoryCheckDetail(MaterialInventoryCheckDetailSaveReqVO updateReqVO) {
        // 校验存在
        validateMaterialInventoryCheckDetailExists(updateReqVO.getId());
        // 更新
        MaterialInventoryCheckDetailDO updateObj = BeanUtils.toBean(updateReqVO, MaterialInventoryCheckDetailDO.class);
        materialInventoryCheckDetailMapper.updateById(updateObj);
    }

    @Override
    public void deleteMaterialInventoryCheckDetail(Long id) {
        // 校验存在
        validateMaterialInventoryCheckDetailExists(id);
        // 删除
        materialInventoryCheckDetailMapper.deleteById(id);
    }

    @Override
        public void deleteMaterialInventoryCheckDetailListByIds(List<Long> ids) {
        // 校验存在
        validateMaterialInventoryCheckDetailExists(ids);
        // 删除
        materialInventoryCheckDetailMapper.deleteByIds(ids);
        }

    private void validateMaterialInventoryCheckDetailExists(List<Long> ids) {
        List<MaterialInventoryCheckDetailDO> list = materialInventoryCheckDetailMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(MATERIAL_INVENTORY_CHECK_DETAIL_NOT_EXISTS);
        }
    }

    private void validateMaterialInventoryCheckDetailExists(Long id) {
        if (materialInventoryCheckDetailMapper.selectById(id) == null) {
            throw exception(MATERIAL_INVENTORY_CHECK_DETAIL_NOT_EXISTS);
        }
    }

    @Override
    public MaterialInventoryCheckDetailDO getMaterialInventoryCheckDetail(Long id) {
        return materialInventoryCheckDetailMapper.selectById(id);
    }

    @Override
    public PageResult<MaterialInventoryCheckDetailDO> getMaterialInventoryCheckDetailPage(MaterialInventoryCheckDetailPageReqVO pageReqVO) {
        return materialInventoryCheckDetailMapper.selectPage(pageReqVO);
    }

    @Override
    public List<MaterialInventoryCheckDetailDO> getListByItemId(Long itemId) {
        return materialInventoryCheckDetailMapper.selectList(Wrappers.lambdaQuery(MaterialInventoryCheckDetailDO.class)
                .eq(MaterialInventoryCheckDetailDO::getItemId, itemId));
    }

    @Override
    public void addBatch(List<MaterialInventoryCheckDetailDO> checkDetailDOS) {
        if (CollUtil.isEmpty(checkDetailDOS)) return;
        materialInventoryCheckDetailMapper.insertBatch(checkDetailDOS);
    }

    @Override
    public MaterialInventoryCheckDetailRespVO inventoryCheckInfomation(MaterialInventoryCheckDetailSaveReqVO inventoryReqVO) {
        Long infomationId = inventoryReqVO.getInfomationId();
        MaterialInfomationDO infomationDO = materialInfomationService.getMaterialInfomation(infomationId);
        if (infomationDO == null) throw exception(MATERIAL_INFOMATION_NOT_EXISTS);
        Long checkId = inventoryReqVO.getCheckId();
        MaterialLifecycleDO lifecycleDO = materialLifecycleService.getMaterialLifecycle(checkId);
        if (lifecycleDO == null) throw exception(MATERIAL_LIFECYCLE_NOT_EXISTS);
        if (lifecycleDO.getSubmitStatus() != 1) throw new ServiceException(1_032_160_000, "盘点单未提交");

        LocalDateTime checkTime = lifecycleDO.getApplyTime();
        if (infomationDO.getCreateTime().isAfter(checkTime)) throw new ServiceException(1_032_160_000, "此物料在发起盘点后入库，不可盘点");

        // 检查是否已经盘点过
        MaterialInventoryCheckDetailDO checkDetailDO = materialInventoryCheckDetailMapper.selectOne(Wrappers.lambdaQuery(MaterialInventoryCheckDetailDO.class)
                .eq(MaterialInventoryCheckDetailDO::getCheckId, checkId)
                .eq(MaterialInventoryCheckDetailDO::getInfomationId, infomationId));
        MaterialInventoryCheckItemDO item = materialInventoryCheckItemService.getItemByCheckIdAndPdtId(checkId, infomationDO.getProductId());
        if (checkDetailDO != null) {
            if (checkDetailDO.getPresent() == 1) throw new ServiceException(1_032_160_000, "此物料已盘点过");
        } else {
            // 检查是否未领用了没拿走的情况
            if (infomationDO.getUsageStatus() != 1) throw new ServiceException(1_032_160_000, "此盘点单不可盘点该物料");
            // 根据仓库和盘点项匹配物料
            // 1. 匹配上 新建盘点明细（领用了没拿走）
            // 2. 匹配不上 新建盘点项和盘点明细（领用了没拿走且大类不在盘点项中）
            JSONObject cstCfgObj = JSONUtil.parseObj(lifecycleDO.getCustomConfig());
            JSONArray jsonWarehouseIds = cstCfgObj.getJSONArray("warehouseIds");
            List<Long> warehouseIds = CollUtil.isEmpty(jsonWarehouseIds) ? List.of() : jsonWarehouseIds.toList(Long.class);
            if (CollUtil.isEmpty(warehouseIds)) throw new ServiceException(1_032_160_000, "此盘点单没有配置盘点仓库");
            ConfigWarehouseLocationDO location = configWarehouseLocationService.getConfigWarehouseLocation(infomationDO.getLocationId());
            if (location == null) throw exception(CONFIG_WAREHOUSE_LOCATION_NOT_EXISTS);
            // 仓库匹配不成功，
            if (!warehouseIds.contains(location.getParentId())) throw new ServiceException(1_032_160_000, "该物料所在的仓库不在此盘点单中");
            if (item == null) {
                // 盘点项匹配不成功，新建盘点项
                item = new MaterialInventoryCheckItemDO()
                        .setParentId(checkId).setProductId(infomationDO.getProductId())
                        .setExpected(BigDecimal.valueOf(0))
                        .setRemark("盘点过程中新增的盘点项");
                materialInventoryCheckItemService.save(item);
            }
            checkDetailDO = new MaterialInventoryCheckDetailDO()
                    .setCheckId(checkId).setItemId(item.getId()).setInfomationId(infomationId)
                    .setCurrentQuantity(inventoryReqVO.getCurrentQuantity())
                    .setRemark(StrUtil.isEmpty(inventoryReqVO.getRemark()) ? "已领用未拿走" : inventoryReqVO.getRemark());
        }
        checkDetailDO.setPresent(1);
        materialInventoryCheckDetailMapper.updateById(checkDetailDO);
        item.setActual(item.getActual().add(BigDecimal.valueOf(1)));
        materialInventoryCheckItemService.updateById(item);
        return BeanUtils.toBean(checkDetailDO, MaterialInventoryCheckDetailRespVO.class);
    }

    @Override
    public PageResult<MaterialInventoryCheckDetailRespVO> getPageWithInf(MaterialInventoryCheckDetailPageReqVO pageReqVO) {
        return materialInventoryCheckDetailMapper.selectPageWithInf(pageReqVO);
    }

}