package com.sw.mes.itemclean.clean.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.dto.DictionaryItemDto;
import com.sw.mes.core.dto.erp.ErpOrderDto;
import com.sw.mes.core.dto.materialCleanDto.MaterialCleanModelDto;
import com.sw.mes.core.dto.mes.pc.yb.SapRequestLog;
import com.sw.mes.core.enums.SectionIndexRangeEnum;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.itemclean.clean.domain.MaterialPlanOrder;
import com.sw.mes.itemclean.clean.mapper.MaterialPlanOrderMapper;
import com.sw.mes.itemclean.clean.service.MaterialPlanOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by author on 2023-05-18
 */
@Service
@Slf4j
public class MaterialPlanOrderServiceImpl extends ServiceImpl<MaterialPlanOrderMapper, MaterialPlanOrder> implements MaterialPlanOrderService {

    @Autowired
    MaterialPlanOrderMapper baseDao;

    @Autowired
    YbFeignClients ybFeignClients;


    @Override
    public List<MaterialPlanOrder> getList() {
        return baseDao.getList();
    }

    @Override
    public MaterialPlanOrder getById(Integer id) {
        return baseDao.getById(id);
    }

    @Override
    public MaterialPlanOrder insert(MaterialPlanOrder materialPlanOrder) {
        baseDao.insert(materialPlanOrder);
        return materialPlanOrder;
    }

    @Override
    public void delete(Integer id) {
        baseDao.delete(id);
    }

    @Override
    public void update(MaterialPlanOrder materialPlanOrder) {
        baseDao.update(materialPlanOrder);
    }

    @Override
    public void activeUpdate(MaterialPlanOrder materialPlanOrder) {
        baseDao.activeUpdate(materialPlanOrder);
    }

    @Override
    public MaterialPlanOrder findByAufnr(String aufnr) {
        return baseDao.findByAufnr(aufnr);
    }

    @Override
    public List<MaterialPlanOrder> findByMatnr(String matnr) {
        return baseDao.findByMatnr(matnr);
    }

    @Override
    public Result handleErpOrder(List<ErpOrderDto> xlErpOrderDto) {
        StringBuilder sb = new StringBuilder();
        Result<DictionaryItemDto> result = ybFeignClients.findByThemeCodeAndItemName("departmentCode","清洗车间");
        String departmentCode = Optional.ofNullable(result).map(Result::getData).map(DictionaryItemDto::getValue).orElse("");
        for(ErpOrderDto dto:xlErpOrderDto) {
            Integer status = dto.getStatus();
            String mdeptCode = dto.getMdeptcode();
            if (mdeptCode.equals(departmentCode)) {
                MaterialPlanOrder oldOder = this.findByAufnr(dto.getMocode());
                if (3 == status) {
                    //新增
                    if (oldOder == null) {
                        StringBuilder sb1 = new StringBuilder();
                        MaterialPlanOrder order;
                        try {
                            order = packageOrder(dto, sb1);
                            if (sb1.length() == 0 && order != null) {
                                saveOrUpdate(order);
                            } else {
                                sb.append(sb1);
                                continue;
                            }
                        } catch (Exception e) {
                            sb.append("订单" + dto.getMocode() + "异常:" + e.getMessage() + "; ");
                            e.printStackTrace();
                            continue;
                        }
                    }
                } else if (4 == status) {
                    if (oldOder != null) {
                        oldOder.setStatus("CLOSE");
                        saveOrUpdate(oldOder);
                    }
                }
            }
        }
        //记录异常日志
        if(sb.length() > 0){
            SapRequestLog log = new SapRequestLog();
            log.setContent("洗料订单异常信息:"+sb.toString());
            log.setCreateTime(new Date());
            log.setType(3);
            ybFeignClients.saveSapLog(log);
        }
        return ResultGenerator.success();
    }

    private MaterialPlanOrder packageOrder(ErpOrderDto dto,StringBuilder sb) {
        MaterialPlanOrder order = new MaterialPlanOrder();
        order.setAufnr(dto.getMocode());
        String type = dto.getMocode().substring(SectionIndexRangeEnum.订单类型.getBeginIndex(),SectionIndexRangeEnum.订单类型.getEndIndex());

        if("A".equals(type)){
            order.setAuart("研发");
        }else if("B".equals(type)){
            order.setAuart("实验");
        }else if("C".equals(type)){
            order.setAuart("常规");
        }
        order.setDeptCode(dto.getMdeptcode());
        order.setMoid(dto.getMoid() == null ? null : dto.getMoid().toString());
        order.setModid(dto.getModid() == null ? null : dto.getModid().toString());
        order.setMatnr(dto.getInvcode());
        order.setPlanMenge(dto.getQty());
        order.setGltrp(dto.getDuedate());
        order.setGstrp(dto.getStartdate());
        order.setCreateDate(new Date());
        order.setStatus("REL");
        String cdepname = dto.getCdepname();
        if(StringUtils.isNotBlank(cdepname) && cdepname.length() > SectionIndexRangeEnum.生产部门.getEndIndex()) {
            String workShop = cdepname.substring(SectionIndexRangeEnum.生产部门.getBeginIndex(), SectionIndexRangeEnum.生产部门.getEndIndex());
            //生产部门
            order.setProductDepartment(workShop);
        }
        order.setProductionStatus(true);
        //产品信息
        Result<MaterialCleanModelDto> result = ybFeignClients.findMaterialCleanByFinishedCode(dto.getInvcode());
        if(result.getCode() == ResultCode.SUCCESS.getCode()){
            MaterialCleanModelDto dto1 = result.getData();
            order.setProductModelId(dto1.getId());
            order.setConductionType(dto1.getDopedTypeCode());
            order.setDopant(dto1.getDopedType());
        }else{
            sb.append("订单"+dto.getMocode()+"的"+dto.getInvcode()+"未匹配到产品模型; ");
            return null;
        }
        //如果溯源标识为 D、J，则型号为D、J；其他：则从工单中规格型号（cinvstd），截取第一位 - 转换规则：P转成T，N转成H
        String productType = null;
        String fromMark = dto.getMocode().substring(SectionIndexRangeEnum.订单溯源标识.getBeginIndex(),SectionIndexRangeEnum.订单溯源标识.getEndIndex());
        String cinvstd = dto.getCinvstd();
        if(org.apache.commons.lang3.StringUtils.isNotBlank(fromMark)) {
            if ("D".equals(fromMark) || "J".equals(fromMark)) {
                productType = fromMark + fromMark;
            } else if(org.apache.commons.lang3.StringUtils.isNotBlank(cinvstd)){
                String type1 = cinvstd.substring(SectionIndexRangeEnum.规格型号截取类型.getBeginIndex(),SectionIndexRangeEnum.规格型号截取类型.getEndIndex());
                if("P".equals(type1)){
                    type1 = "T";
                }else if("N".equals(type1)){
                    type1 = "H";
                }
                productType = fromMark + type1;
            }
        }
        order.setProductType(productType);
        //TODO 电阻如何获取
        String [] parts = cinvstd.split(",|，");
        if(parts.length>1) {
            order.setResistanceType(parts[1]);
        }
        order.setProductionStatus(false);
        return order;


    }


}