package com.zt.plat.module.contractorder.service.purchaseorder;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.plat.framework.common.exception.ErrorCode;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.spring.SpringUtils;
import com.zt.plat.module.base.api.materialclasses.MaterialClassesApi;
import com.zt.plat.module.base.api.materialinfomation.MaterialInfomationApi;
import com.zt.plat.module.base.api.materialinfomation.dto.MaterialInfomationPageReqDTO;
import com.zt.plat.module.base.api.materialinfomation.dto.MaterialInfomationRespDTO;
import com.zt.plat.module.base.dal.dataobject.base.ElementDO;
import com.zt.plat.module.base.service.base.ElementService;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.PrchOrdDtlPageReqVO;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.PrchOrdDtlRespVO;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.PrchOrdDtlSaveReqVO;
import com.zt.plat.module.contractorder.dal.dataobject.purchaseorder.PrchOrdDtlDO;
import com.zt.plat.module.contractorder.dal.dataobject.purchaseorder.PurchaseOrderDO;
import com.zt.plat.module.contractorder.dal.mysql.purchaseorder.PrchOrdDtlMapper;
import com.zt.plat.module.contractorder.dal.mysql.purchaseorder.PurchaseOrderMapper;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpOrderUpdateReqVO;
import com.zt.plat.module.erp.service.erp.ErpOrderService;
import com.zt.plat.module.receivedeliver.api.bill.BillMainApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.util.object.BeanUtils;


import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.diffList;
import static com.zt.plat.module.contractorder.enums.purchaseorder.ErrorCodeConstants.*;
import static com.zt.plat.module.contractorder.enums.purchaseorder.ErrorCodeConstants.MTRL_CODE_NOT_EXISTS;
import static com.zt.plat.module.receivedeliver.enums.ErrorCodeConstants.PURCHASE_ORDER_DETAIL_NOT_EXISTS;


/**
 * 采购订单明细 Service 实现类
 *
 * @author 后台管理-1
 */
@Service
@Validated
@Slf4j
public class PrchOrdDtlServiceImpl implements PrchOrdDtlService {

    @Resource
    private PrchOrdDtlMapper prchOrdDtlMapper;
    @Resource
    private BillMainApi billMainApi;
    @Resource
    private ElementService elementService;


    @Override
    public PrchOrdDtlRespVO createPrchOrdDtl(PrchOrdDtlSaveReqVO createReqVO) {
        // 插入
        PrchOrdDtlDO prchOrdDtl = BeanUtils.toBean(createReqVO, PrchOrdDtlDO.class);
        //填充金属元素相关的信息
        setElemInfo(prchOrdDtl);
        log.info("创建采购订单明细,创建数据【{}】", prchOrdDtl);
        prchOrdDtl.setTrfQty(BigDecimal.ZERO);
        prchOrdDtlMapper.insert(prchOrdDtl);
        // 返回
        return BeanUtils.toBean(prchOrdDtl, PrchOrdDtlRespVO.class);
    }

    private void setElemInfo(PrchOrdDtlDO prchOrdDtl) {
        if (prchOrdDtl.getElemAbbr() == null) {
            return;
        }
        ElementDO elementBySymbol = elementService.getElementBySymbol(prchOrdDtl.getElemAbbr());
        if (elementBySymbol != null) {
            prchOrdDtl.setElemName(elementBySymbol.getName());
            prchOrdDtl.setElemCdg(elementBySymbol.getCoding());
        } else {
            log.warn("元素【{}】不存在,订单ID【{}】", prchOrdDtl.getElemAbbr(), prchOrdDtl.getOrdId());
        }

    }

    @Override
    public void updatePrchOrdDtl(PrchOrdDtlSaveReqVO updateReqVO) {
        // 校验存在
        validatePrchOrdDtlExists(updateReqVO.getId());
        // 更新
        PrchOrdDtlDO updateObj = BeanUtils.toBean(updateReqVO, PrchOrdDtlDO.class);
        setElemInfo(updateObj);
        prchOrdDtlMapper.updateById(updateObj);
    }

    @Override
    public void deletePrchOrdDtl(Long id) {
        // 校验存在
        validatePrchOrdDtlExists(id);
        // 删除
        prchOrdDtlMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePrchOrdDtlListByIds(List<Long> ids) {
        //校验是否可以删除
        validateBillMainCanDelete(ids);
        //提交erp062
        submitErp062ByDelete(ids);
        // 校验存在
        validatePrchOrdDtlExists(ids);
        // 删除
        prchOrdDtlMapper.deleteByIds(ids);
    }

    private void validateBillMainCanDelete(List<Long> ids) {
        ids.forEach(id -> {
            CommonResult<Boolean> booleanCommonResult = billMainApi.notOffsetIsExistOrderDetailId(id);
            if (booleanCommonResult.isSuccess() && booleanCommonResult.getData()) {
                PrchOrdDtlDO prchOrdDtlDO = prchOrdDtlMapper.selectById(id);
                throw exception(new ErrorCode(1_008_00_600, "订单明细【" + prchOrdDtlDO.getLineNum() + "】已生成收发货单，不能删除"));
            }
        });
    }

    private void validatePrchOrdDtlExists(List<Long> ids) {
        List<PrchOrdDtlDO> list = prchOrdDtlMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(PRCH_ORD_DTL_NOT_EXISTS);
        }
    }

    private void validatePrchOrdDtlExists(Long id) {
        if (prchOrdDtlMapper.selectById(id) == null) {
            throw exception(PRCH_ORD_DTL_NOT_EXISTS);
        }
    }

    @Override
    public PrchOrdDtlDO getPrchOrdDtl(Long id) {
        return prchOrdDtlMapper.selectById(id);
    }

    @Override
    public PageResult<PrchOrdDtlDO> getPrchOrdDtlPage(PrchOrdDtlPageReqVO pageReqVO) {
        return prchOrdDtlMapper.selectPage(pageReqVO);
    }

    @Override
    public List<PrchOrdDtlRespVO> batchCreatePrchOrdDtl(List<PrchOrdDtlSaveReqVO> createReqVOS) {
        List<PrchOrdDtlDO> prchOrdDtlDOS = BeanUtils.toBean(createReqVOS, PrchOrdDtlDO.class);
        prchOrdDtlDOS.forEach(this::setElemInfo);
        prchOrdDtlMapper.insertBatch(prchOrdDtlDOS);
        log.info("批量创建采购订单明细成功,工插入【{}】条数据", prchOrdDtlDOS.size());
        return BeanUtils.toBean(prchOrdDtlDOS, PrchOrdDtlRespVO.class);
    }

    @Override
    public List<PrchOrdDtlRespVO> batchUpdatePrchOrdDtl(List<PrchOrdDtlSaveReqVO> createReqVOS) {
        List<PrchOrdDtlDO> prchOrdDtlDOS = BeanUtils.toBean(createReqVOS, PrchOrdDtlDO.class);
        //判断行项目号是否已存在
        prchOrdDtlDOS.forEach(p -> {
            if (p.getLineNum() == null) {
                exitsLineNumber(p);
            }
            setElemInfo(p);
        });
        prchOrdDtlMapper.insertOrUpdate(prchOrdDtlDOS);
        log.info("批量更新采购订单明细成功,更新【{}】条数据", prchOrdDtlDOS.size());
        return BeanUtils.toBean(prchOrdDtlDOS, PrchOrdDtlRespVO.class);
    }

    private void exitsLineNumber(PrchOrdDtlDO prchOrdDtlDO) {
        PrchOrdDtlDO prchOrd = prchOrdDtlMapper.selectByLineNumAndOrdId(prchOrdDtlDO.getLineNum(), prchOrdDtlDO.getOrdId());
        if (prchOrd != null) {
            throw exception(new ErrorCode(1_008_00_666, "该行项目号【" + prchOrdDtlDO.getLineNum() + "】已存在"));
        }
    }

    ;

    @Override
    public void deletePrchOrdDtlListByOrdIds(List<Long> ordIds) {
        //通过订单组件查询订单明细
        List<PrchOrdDtlDO> prchOrdDtlDOS = prchOrdDtlMapper.selectList(new LambdaQueryWrapper<>(PrchOrdDtlDO.class).in(PrchOrdDtlDO::getOrdId, ordIds));
        //删除订单明细
        deletePrchOrdDtlListByIds(convertList(prchOrdDtlDOS, PrchOrdDtlDO::getId));
    }

    @Override
    public List<PrchOrdDtlDO> getDetailsByOrderId(Long ordId) {

        return prchOrdDtlMapper.selectList(new LambdaQueryWrapper<>(PrchOrdDtlDO.class).eq(PrchOrdDtlDO::getOrdId, ordId));
    }

    //操作步骤 1、更新erp->更新数据库
    @Override
    public void submitErp062ByDelete(List<Long> ids) {
        log.info("开始执行提交ERP 062 By Delete 操作，ID：{}", ids);
        //查询采购单信息
        //根据订单信息查询采购单详情信息
        List<PrchOrdDtlDO> purchaseOrderDetailsDOS = prchOrdDtlMapper.selectByIds(ids);
        if (purchaseOrderDetailsDOS == null || purchaseOrderDetailsDOS.isEmpty()) {
            throw exception(PURCHASE_ORDER_DETAIL_NOT_EXISTS);
        }
        PurchaseOrderDO purchaseOrderDO = SpringUtils.getBean(PurchaseOrderMapper.class).selectById(purchaseOrderDetailsDOS.get(0).getOrdId());
        if (purchaseOrderDO.getOrderSAPNumber()==null){
            log.info("该订单尚未提交erp，ID：{}", purchaseOrderDetailsDOS.get(0).getOrdId());
            return;
        }

        ErpOrderUpdateReqVO erpOrderUpdateReqVO = new ErpOrderUpdateReqVO();
        setHeadAndExte(erpOrderUpdateReqVO, purchaseOrderDO);
        setDeleteItems(erpOrderUpdateReqVO, purchaseOrderDetailsDOS);
        String str = SpringUtils.getBean(ErpOrderService.class).submitOrderToErp062(erpOrderUpdateReqVO);
        log.info("提交ERP 062 By Delete 结果：{}", str);
    }


    private void setHeadAndExte(ErpOrderUpdateReqVO erpOrderUpdateReqVO, PurchaseOrderDO purchaseOrderDO) {
        erpOrderUpdateReqVO.setPoNumber(purchaseOrderDO.getOrderSAPNumber()).setCurrency(purchaseOrderDO.getCurrencyNumber()).setExchRate(purchaseOrderDO.getExchangeRate());
        erpOrderUpdateReqVO.setZzhth(purchaseOrderDO.getPaperContractNumber()).setZxxyh(purchaseOrderDO.getAgreementNumber()).setZnote(purchaseOrderDO.getRemark()).setZlifnr(purchaseOrderDO.getAgreementNumber());
    }

    private void setDeleteItems(ErpOrderUpdateReqVO erpOrderUpdateReqVO, List<PrchOrdDtlDO> purchaseOrderDetailsDOS) {
        List<ErpOrderUpdateReqVO.item> items = new ArrayList<>();
        purchaseOrderDetailsDOS.forEach(prchOrdDtlDO -> {
            MaterialInfomationPageReqDTO infomationPageReqDTO = new MaterialInfomationPageReqDTO();
            infomationPageReqDTO.setPageSize(10000);
            infomationPageReqDTO.setCode(prchOrdDtlDO.getMtrlNum());
            CommonResult<PageResult<MaterialInfomationRespDTO>> materialInfomationPage = SpringUtils.getBean(MaterialInfomationApi.class).getMaterialInfomationPage(infomationPageReqDTO);
            if (materialInfomationPage.getData() == null || materialInfomationPage.getData().getList().isEmpty()) {
                throw exception(MTRL_CODE_NOT_EXISTS);

            }
            MaterialInfomationRespDTO materialInfomationRespDTO = materialInfomationPage.getData().getList().get(0);
            Map<String, Object> flatAttributes = materialInfomationRespDTO.getFlatAttributes();
            //获取中铜物料编码
            String mtrlZhongtongCode = flatAttributes.getOrDefault("mtrlZhongtongCode", "").toString();
            if (mtrlZhongtongCode.isEmpty()) {
                throw exception(MTRL_CODE_NOT_EXISTS);
            }
            ErpOrderUpdateReqVO.item item = new ErpOrderUpdateReqVO.item(); // item
            item.setPo_item(prchOrdDtlDO.getLineNum());//行号
            item.setMaterial(mtrlZhongtongCode);//物料号
            item.setPlant(prchOrdDtlDO.getRcvFactNum());//工厂
            item.setStge_loc(prchOrdDtlDO.getRcvWrhNum());//库位
            item.setQuantity(String.valueOf(prchOrdDtlDO.getQty()));// 数量
            item.setPo_unit(prchOrdDtlDO.getUnt());// 计量单位
            item.setNet_price(prchOrdDtlDO.getInTaxUprc());// 含税单价
            item.setTax_code(prchOrdDtlDO.getTaxNum());//税码
            item.setAcctasscat(prchOrdDtlDO.getActsCtgr());//科目分配类别
            item.setMatl_group(prchOrdDtlDO.getMtrlCpntNum());//物料组
            item.setShort_text(prchOrdDtlDO.getShrtTxt());//短文本
            item.setDelete_ind("1");//行项目删除标识
            items.add(item);
        });
        erpOrderUpdateReqVO.setItems(items);
    }

}
