package com.sw.mes.sap.service.impl;


import cn.hutool.core.convert.Convert;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.erp.ErpAddResultDto;
import com.sw.mes.core.dto.erp.ErpRequestDto;
import com.sw.mes.core.entity.MesToErpCcpEntity;
import com.sw.mes.core.enums.ErpEnum;
import com.sw.mes.core.enums.ErpPypeEnum;
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.core.utils.DateUtil;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.sap.dao.ReportErpOutputRecordDao;
import com.sw.mes.sap.entity.ReportErpOutputRecord;
import com.sw.mes.sap.entity.ReportErpOutputRecordDetail;
import com.sw.mes.sap.service.ReportErpOutputRecordDetailService;
import com.sw.mes.sap.service.ReportErpOutputRecordService;
import com.sw.mes.third.utils.ErpRequestUtil;
import com.sw.mes.yb.plan.entity.ProductionOrder;
import com.sw.mes.yb.plan.service.ProductionOrderService;
import com.sw.mes.yb.production.entity.LongCrystal;
import com.sw.mes.yb.production.service.LongCrystalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@Service
@Transactional
public class ReportErpOutputRecordServiceImpl extends BaseServiceImpl<ReportErpOutputRecord> implements ReportErpOutputRecordService {

    @Autowired
    private ReportErpOutputRecordService reportErpOutputRecordService;

    @Autowired
    private ReportErpOutputRecordDetailService reportErpOutputRecordDetailService;

    @Autowired
    private ErpRequestUtil erpRequestUtil;

    @Autowired
    private LongCrystalService longCrystalService;

    @Autowired
    private ProductionOrderService productionOrderService;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${spring.erpServiceUrl}")
    private String erpServiceUrl;

    ReportErpOutputRecordDao dao;
	@Autowired
    public void setDao(ReportErpOutputRecordDao dao) {
        super.setBaseDao(dao);
        this.dao=dao;
    }

    @Override
    public Result reportForWork(ReportErpOutputRecord reportErpOutputRecord)  {

        ErpRequestDto erpRequestDto = packageData(reportErpOutputRecord);

        ErpAddResultDto erpAddResultDto = erpRequestUtil.postToErp(erpRequestDto);
        if (null != erpAddResultDto) {
            if (null != erpAddResultDto.getErrcode() && erpAddResultDto.getErrcode().equals(String.valueOf(ResultCode.SUCCESS.getCode()))) {
                reportErpOutputRecord.setPushed(1);
                reportErpOutputRecord.setSerial(erpAddResultDto.getCcode());
                reportErpOutputRecord.setPushSerial(erpRequestDto.getMesToErpCcpEntity().getCbatch());
                reportErpOutputRecord.setPushUser(BaseContextHandler.getUsername());
                reportErpOutputRecord.setPushTime(new Date());
                reportErpOutputRecord.setDepartmentCode(erpRequestDto.getMesToErpCcpEntity().getCdepname());
                reportErpOutputRecordService.saveOrUpdate(reportErpOutputRecord);

                List<ReportErpOutputRecordDetail> byRid = reportErpOutputRecordDetailService.findByRid(reportErpOutputRecord.getId());
                for (ReportErpOutputRecordDetail reportErpOutputRecordDetail : byRid) {
                    reportErpOutputRecordDetail.setReportWorkState(1);
                    reportErpOutputRecordDetail.setReportWorkTime(new Date());
                    reportErpOutputRecordDetail.setBatchNo(erpAddResultDto.getCcode());
                    reportErpOutputRecordDetail.setPushBatchNo(erpRequestDto.getMesToErpCcpEntity().getCbatch());
                    reportErpOutputRecordDetailService.saveOrUpdate(reportErpOutputRecordDetail);

                    LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(reportErpOutputRecordDetail.getCrystalNo());
                    byCrystalNo.setPushed(1);
                    longCrystalService.saveOrUpdate(byCrystalNo);
                }
                return ResultGenerator.success("上报成功");
            }
//                throw new RuntimeException(erpAddResultDto.getErrmsg());
        }
        return ResultGenerator.fail(erpAddResultDto.getErrmsg());

//        throw new RuntimeException(erpAddResultDto.getErrmsg());
    }

    private ErpRequestDto packageData(ReportErpOutputRecord reportErpOutputRecord) {
        ErpRequestDto erpRequestDto = new ErpRequestDto();
        erpRequestDto.setUrl(erpServiceUrl);

        MesToErpCcpEntity mesToErpCcpEntity = new MesToErpCcpEntity();
        String orderNo = reportErpOutputRecord.getOrderNo();
        ProductionOrder byeErpOrderNo = productionOrderService.findByeErpOrderNo(orderNo);
        if(null != byeErpOrderNo){
            String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//            String date1 = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
            String date1 = DateUtil.packageDocDate(reportErpOutputRecord.getCreateTime());

            String number = getNumber(date);
            String batchNo = null;
            if(byeErpOrderNo.getAuart().equals("研发")){
                batchNo = byeErpOrderNo.getRdonlylogo() + "-" + date1;
            } else if(byeErpOrderNo.getWorkShop().equals("一车间")){
                batchNo = date1 + "1201" + number + "-" + byeErpOrderNo.getProductType() + byeErpOrderNo.getSideLengthRange();
            } else if (byeErpOrderNo.getWorkShop().equals("二车间")){
                batchNo = date1 + "1206" + number + "-" + byeErpOrderNo.getProductType() + byeErpOrderNo.getSideLengthRange();
            }

            mesToErpCcpEntity.setCbatch(batchNo);
            mesToErpCcpEntity.setCwhname(String.valueOf(ErpEnum.WarehouseName.单晶半成品库.getKey()));
            mesToErpCcpEntity.setCinvcode(byeErpOrderNo.getMatnr());
            //此处可优化
            MaterialModel byCode = materialModelService.findByCode(byeErpOrderNo.getMatnr());
            mesToErpCcpEntity.setCinvname(byCode.getName());
            mesToErpCcpEntity.setCinsted(byCode.getSpecification());
            if(null != byCode.getMaterialType()){
                mesToErpCcpEntity.setCinvccode(byCode.getMaterialType().getCode());
            }
            mesToErpCcpEntity.setCinvm_unit(byCode.getUnit().getCode());
            mesToErpCcpEntity.setIquantity(String.valueOf(byeErpOrderNo.getMenge()));
//            mesToErpCcpEntity.setImpoids();
//            mesToErpCcpEntity.setBrelated();
            mesToErpCcpEntity.setCmocode(byeErpOrderNo.getAufnr());
            mesToErpCcpEntity.setImoseq("1");
            mesToErpCcpEntity.setIrowno("1");

            mesToErpCcpEntity.setIproorderid(byeErpOrderNo.getTid());
            if(byeErpOrderNo.getAuart().equals("研发")){
                mesToErpCcpEntity.setCdepcode("18");
            } else if(byeErpOrderNo.getWorkShop().equals("一车间")){
                mesToErpCcpEntity.setCdepcode("1201");
            } else if (byeErpOrderNo.getWorkShop().equals("二车间")){
                mesToErpCcpEntity.setCdepcode("1206");
            }
//            mesToErpCcpEntity.setCdepcode(byeErpOrderNo.getDeptCode());
            mesToErpCcpEntity.setCdepname(byeErpOrderNo.getWorkShop());
        }

        mesToErpCcpEntity.setCmpocode(orderNo);
        mesToErpCcpEntity.setErpType(ErpPypeEnum.长晶棒产出.getKey());
        mesToErpCcpEntity.setCrdcode(reportErpOutputRecord.getReceiveCode());
        mesToErpCcpEntity.setCwhcode(reportErpOutputRecord.getWarehouseCode());
        mesToErpCcpEntity.setIquantity(reportErpOutputRecord.getQuantity().toString());
        mesToErpCcpEntity.setDocTime(reportErpOutputRecord.getCreateTime());
        erpRequestDto.setMesToErpCcpEntity(mesToErpCcpEntity);
        return erpRequestDto;
    }

    private String getNumber(String date) {
        String key = "crystal_seq:" + date;
        String serialNumber =  redisTemplate.opsForValue().get(key);
        if(StringUtils.isBlank(serialNumber)){
            serialNumber="1";
            redisTemplate.opsForValue().set(key, serialNumber, 2L, TimeUnit.DAYS);

        }else{
            Long increment = redisTemplate.opsForValue().increment(key);
            redisTemplate.expire(key, 2L, TimeUnit.DAYS);
            serialNumber = Convert.toStr(increment);
        }
        int sequence = Convert.toInt(serialNumber);
        String strSequence = Convert.toStr(sequence);
        strSequence = StringUtils.leftPad(strSequence, 2, "0");
        return strSequence;
    }
}
