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

import cn.hutool.core.collection.CollUtil;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.util.spring.SpringUtils;
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.entrustorder.vo.EntrustOrderDetailPageReqVO;
import com.zt.plat.module.contractorder.controller.admin.entrustorder.vo.EntrustOrderDetailRespVO;
import com.zt.plat.module.contractorder.controller.admin.entrustorder.vo.EntrustOrderDetailSaveReqVO;
import com.zt.plat.module.contractorder.dal.dataobject.entrustorder.EntrustOrderDetailDO;
import com.zt.plat.module.contractorder.dal.dataobject.entrustorder.EntrustOrderOrderDO;
import com.zt.plat.module.contractorder.dal.dataobject.purchaseorder.PrchOrdDtlDO;
import com.zt.plat.module.contractorder.dal.mysql.entrustorder.EntrustOrderDetailMapper;
import com.zt.plat.module.contractorder.dal.mysql.entrustorder.EntrustOrderOrderMapper;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpOrderUpdateReqVO;
import com.zt.plat.module.erp.service.erp.ErpOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import com.zt.plat.framework.common.pojo.PageResult;
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.module.contractorder.enums.ErpConstants.CONSTANTS_L;
import static com.zt.plat.module.contractorder.enums.entrustorder.ErrorCodeConstants.ENTRUST_ORDER_DETAIL_NOT_EXISTS;
import static com.zt.plat.module.contractorder.enums.purchaseorder.ErrorCodeConstants.MTRL_CODE_NOT_EXISTS;


/**
 * 委托加工订单明细 Service 实现类
 *
 * @author 后台管理-1
 */
@Service
@Validated
@Slf4j
public class EntrustOrderDetailServiceImpl implements EntrustOrderDetailService {

    @Resource
    private ElementService elementService;

    @Resource
    private EntrustOrderDetailMapper entrustOrderDetailMapper;

    @Override
    public EntrustOrderDetailRespVO createEntrustOrderDetail(EntrustOrderDetailSaveReqVO createReqVO) {
        // 插入
        EntrustOrderDetailDO entrustOrderDetail = BeanUtils.toBean(createReqVO, EntrustOrderDetailDO.class);
        setElemInfo(entrustOrderDetail);
        entrustOrderDetailMapper.insert(entrustOrderDetail);
        // 返回
        return BeanUtils.toBean(entrustOrderDetail, EntrustOrderDetailRespVO.class);
    }

    @Override
    public void updateEntrustOrderDetail(EntrustOrderDetailSaveReqVO updateReqVO) {
        // 校验存在
        validateEntrustOrderDetailExists(updateReqVO.getId());
        // 更新
        EntrustOrderDetailDO updateObj = BeanUtils.toBean(updateReqVO, EntrustOrderDetailDO.class);
        setElemInfo(updateObj);
        entrustOrderDetailMapper.updateById(updateObj);
    }

    @Override
    public void deleteEntrustOrderDetail(Long id) {
        // 校验存在
        validateEntrustOrderDetailExists(id);
        // 删除
        entrustOrderDetailMapper.deleteById(id);
    }

    @Override
    public void deleteEntrustOrderDetailListByIds(List<Long> ids) {
        // 校验存在
        validateEntrustOrderDetailExists(ids);
        //提交erp
        submitToErp062(ids);
        // 删除
        entrustOrderDetailMapper.deleteByIds(ids);
    }

    private void submitToErp062(List<Long> ids) {
        //查询订单明细
        List<EntrustOrderDetailDO> entrustOrderDetails = entrustOrderDetailMapper.selectByIds(ids);
        if (CollUtil.isEmpty(entrustOrderDetails)) {
            log.warn("提交订单明细到erp，订单明细为空，订单明细ID：{}", ids);
            return;
        }
        log.info("提交订单明细到erp，订单明细：{}", entrustOrderDetails);
        //查询主订单
        EntrustOrderOrderDO entrustOrderOrderDO = SpringUtils.getBean(EntrustOrderOrderMapper.class).selectById(entrustOrderDetails.get(0).getOrderId());
        if (entrustOrderOrderDO == null) {
            log.warn("提交订单明细到erp，主订单为空，订单明细ID：{}", ids);
            return;
        }
        if (entrustOrderOrderDO.getOrderSAPNumber() == null || entrustOrderOrderDO.getOrderSAPNumber().isEmpty()) {
          return;
        }
        log.info("提交订单明细到erp，主订单：{}", entrustOrderOrderDO);
        ErpOrderUpdateReqVO erpOrderUpdateReqVO = new ErpOrderUpdateReqVO();
        buildErp062Data(erpOrderUpdateReqVO, entrustOrderOrderDO, entrustOrderDetails);
        log.info("提交订单明细到erp，数据：{}", erpOrderUpdateReqVO);
        String result = SpringUtils.getBean(ErpOrderService.class).submitOrderToErp062(erpOrderUpdateReqVO);
        log.info("提交订单明细到erp，结果：{}", result);
    }
    private void buildErp062Data(ErpOrderUpdateReqVO erpOrderUpdateReqVO, EntrustOrderOrderDO order, List<EntrustOrderDetailDO> entrustOrderDetailList) {
        erpOrderUpdateReqVO
                .setPoNumber(order.getOrderSAPNumber())
                .setDeleteInd(order.getDeleted() ? "1" : null)
                .setCurrency(order.getCurrencyNumber())
                .setExchRate(order.getExchangeRate());
        //exte
        erpOrderUpdateReqVO
                .setZzhth(order.getPaperContractNumber())
                .setZxxyh(order.getAgreementNumber())
                .setZnote(order.getRemark())
                .setZlifnr(order.getAgreementNumber());
        //item
        List<ErpOrderUpdateReqVO.item> items = new ArrayList<>();
        List<ErpOrderUpdateReqVO.comp> comps = new ArrayList<>();
        AtomicReference<Integer> index= new AtomicReference<>(0);
        entrustOrderDetailList.forEach(detail -> {
            index.getAndSet(index.get() + 1);
            ErpOrderUpdateReqVO.item item = new ErpOrderUpdateReqVO.item(); // item
            item.setPo_item(Long.valueOf(detail.getLineNumber()));//行号
            item.setMaterial(getMtrlZhongtongCode(detail.getSendMaterialNumber()));//物料号
            item.setPlant(detail.getReceiveFactoryNumber());//工厂
            item.setStge_loc(detail.getReceiveWarehouseNumber());//库位
            item.setQuantity(String.valueOf(detail.getForecastQuantity()));// 数量
            item.setPo_unit(detail.getSendUnit());// 计量单位
            item.setNet_price(detail.getInTaxUnitPrice());// 含税单价
            item.setTax_code(detail.getTaxNumber());//税码
            item.setItem_cat(CONSTANTS_L);//科目分配类别
            item.setMatl_group(detail.getMaterialGroup());//物料组
            item.setShort_text(detail.getShortText());//短文本
            item.setDelete_ind(detail.getDeleted() ? "1" : null);//行项目删除标识
            items.add(item);

            ErpOrderUpdateReqVO.comp comp = new ErpOrderUpdateReqVO.comp();
            comp.setPo_item(Long.valueOf(detail.getLineNumber()));
//            comp.setSched_line(index.get()); // 计划行号 -> 计划行号（保持一致）
//            comp.setItem_no(index.get()); // 项目编号 -> 项目编号
            comp.setMaterial(detail.getSendMaterialNumber()); // 物料号 -> 物料号
            comp.setPlant(detail.getReceiveFactoryNumber()); // 收货工厂 -> 收货工厂
            comp.setEntry_quantity(detail.getForecastQuantity()); // 委托加工需求数量 -> 委托加工需求数量
            comp.setEntry_uom(detail.getSendUnit()); // 组件计量单位 -> 组件计量单位
            comps.add(comp);
        });
        erpOrderUpdateReqVO.setItems(items);
        //comp
        erpOrderUpdateReqVO.setComps(comps);

    }

    private void validateEntrustOrderDetailExists(List<Long> ids) {
        List<EntrustOrderDetailDO> list = entrustOrderDetailMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(ENTRUST_ORDER_DETAIL_NOT_EXISTS);
        }
    }

    private void validateEntrustOrderDetailExists(Long id) {
        if (entrustOrderDetailMapper.selectById(id) == null) {
            throw exception(ENTRUST_ORDER_DETAIL_NOT_EXISTS);
        }
    }

    @Override
    public EntrustOrderDetailDO getEntrustOrderDetail(Long id) {
        return entrustOrderDetailMapper.selectById(id);
    }

    @Override
    public PageResult<EntrustOrderDetailDO> getEntrustOrderDetailPage(EntrustOrderDetailPageReqVO pageReqVO) {
        return entrustOrderDetailMapper.selectPage(pageReqVO);
    }

    @Override
    public List<EntrustOrderDetailRespVO> insertBatchSomeColumn(List<EntrustOrderDetailSaveReqVO> entrustOrderOrderDetails) {
        List<EntrustOrderDetailDO> entrustOrderDetail = BeanUtils.toBean(entrustOrderOrderDetails, EntrustOrderDetailDO.class);
        entrustOrderDetail.forEach(this::setElemInfo);
        entrustOrderDetailMapper.insertBatch(entrustOrderDetail);
        return BeanUtils.toBean(entrustOrderDetail, EntrustOrderDetailRespVO.class);
    }

    @Override
    public void updateBatchSomeColumn(List<EntrustOrderDetailSaveReqVO> entrustOrderOrderDetails) {
        List<EntrustOrderDetailDO> updateList = BeanUtils.toBean(entrustOrderOrderDetails, EntrustOrderDetailDO.class);
        updateList.forEach(this::setElemInfo);
        entrustOrderDetailMapper.insertOrUpdate(updateList);
    }

    @Override
    public List<EntrustOrderDetailRespVO> getEntrustOrderDetailListByOrderId(Long orderId) {
        return BeanUtils.toBean(entrustOrderDetailMapper.selectList(EntrustOrderDetailDO::getOrderId, orderId), EntrustOrderDetailRespVO.class);
    }

    @Override
    public void deleteEntrustOrderDetailByOrderId(List<Long> orderId) {
        entrustOrderDetailMapper.delete(EntrustOrderDetailDO::getOrderId, orderId);
    }

    public String getMtrlZhongtongCode(String materialNumber) {
        MaterialInfomationPageReqDTO infomationPageReqDTO = new MaterialInfomationPageReqDTO();
        infomationPageReqDTO.setPageSize(10000);
        infomationPageReqDTO.setCode(materialNumber);
        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);
        }
        return mtrlZhongtongCode;
    }

    private void setElemInfo(EntrustOrderDetailDO entrustOrderDetailDO) {
        if (entrustOrderDetailDO.getElementAbbreviation() == null) {
            return;
        }
        ElementDO elementBySymbol = elementService.getElementBySymbol(entrustOrderDetailDO.getElementAbbreviation());
        if (elementBySymbol != null) {
            entrustOrderDetailDO.setElementName(elementBySymbol.getName());
            entrustOrderDetailDO.setElementNumber(elementBySymbol.getCoding());
        } else {
            log.warn("元素【{}】不存在,订单ID【{}】", entrustOrderDetailDO.getElementAbbreviation(), entrustOrderDetailDO.getOrderId());
        }

    }
}