package com.sw.mes.yb.scheduled;


import cn.hutool.core.convert.Convert;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.sap.entity.ReportErpInputRecord;
import com.sw.mes.sap.entity.ReportErpInputRecordDetail;
import com.sw.mes.sap.service.ReportErpInputRecordDetailService;
import com.sw.mes.sap.service.ReportErpInputRecordService;
import com.sw.mes.yb.production.service.BlastFurnaceDetailService;
import com.sw.mes.yb.production.service.InputFurnaceDetailService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * 定时组装erp数据
 * @author xushu
 */
@Slf4j
@Component
public class PackageErpDataScheduling {



    @Autowired
    private BlastFurnaceDetailService blastFurnaceDetailService;

    @Autowired
    private InputFurnaceDetailService inputFurnaceDetailService;

    @Autowired
    private ReportErpInputRecordService reportErpInputRecordService;

    @Autowired
    private ReportErpInputRecordDetailService reportErpInputRecordDetailService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private DictionaryItemService dictionaryItemService;





    /**
     * 组装单晶投入实体定时任务（灌料配料）
     */
    @XxlJob("packageCrystalInputData")
    public void packageCrystalInputData() {
        try {
            List<Map<String,Object>> listMapAll = new ArrayList<>();
            //拉取该时间段未上报的配料信息数据
            List<Map<String,Object>> listMap1 = blastFurnaceDetailService.pullMaterialData();
            List<Long> idList1 = listMap1.stream().map(map->Long.valueOf(map.get("id").toString())).collect(Collectors.toList());
            listMapAll.addAll(listMap1);
            //拉取该时间段未上报的灌料信息数据
            List<Map<String,Object>> listMap2 = inputFurnaceDetailService.pullMaterialData();
            List<Long> idList2 = listMap2.stream().map(map->Long.valueOf(map.get("id").toString())).collect(Collectors.toList());
            listMapAll.addAll(listMap2);
            //将两个list根据工单号合并
            Map<String,List<Map>>  map1 = listMapAll.stream().collect(Collectors.groupingBy(map->map.get("erpOrderNo").toString()));
            Set set = map1.keySet();
            Iterator iterator = set.iterator();
            //合并后插入新建的主表
            //组装批次号
            //插入新建的子表
            while (iterator.hasNext()) {
                String key = iterator.next().toString();
                List<Map> maps =  map1.get(key);
                Map temp = maps.get(0);
                ReportErpInputRecord reportErpInputRecord = new ReportErpInputRecord();
                //
//                String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//                String number = getNumber(date);
                String workShop = temp.get("workShop") == null? "":temp.get("workShop").toString();
                String deptCode = temp.get("deptCode") == null? "":temp.get("deptCode").toString();
                String warehouseCode  = dictionaryItemService.findValueByThemeValueAndItemName("WarehouseCode","材料出库"+workShop);
                reportErpInputRecord.setWarehouseCode(warehouseCode);
//                reportErpInputRecord.setCode("RL"+date+number);
                reportErpInputRecord.setOrderNo(temp.get("erpOrderNo").toString());
                String receiveCode  = dictionaryItemService.findValueByThemeValueAndItemName("receiveCode","生产领用");
                reportErpInputRecord.setReceiveCode(receiveCode);
                reportErpInputRecord.setDepartmentCode(deptCode);
//            reportErpInputRecord.setInventoryCode();
//            reportErpInputRecord.setNumber();
//            reportErpInputRecord.setSerial();
                reportErpInputRecord.setCost(BigDecimal.ZERO);
                reportErpInputRecord.setCreateTime(new Date());
                reportErpInputRecord.setPushed(0);
                reportErpInputRecord.setType(0);

                BigDecimal weight =  BigDecimal.ZERO;
                reportErpInputRecordService.saveOrUpdate(reportErpInputRecord);
                List<ReportErpInputRecordDetail> reportErpInputRecordDetails = new ArrayList<>();
                for(Map map : maps){
                    ReportErpInputRecordDetail reportErpInputRecordDetail = new ReportErpInputRecordDetail();
                    reportErpInputRecordDetail.setRid(reportErpInputRecord.getId());
                    reportErpInputRecordDetail.setBid(Long.valueOf(map.get("id").toString()));
                    reportErpInputRecordDetail.setBatchNo(map.get("batchNo") == null? "":map.get("batchNo").toString());
                    reportErpInputRecordDetail.setMaterialName(map.get("materialName") == null ? "" :map.get("materialName").toString());
                    reportErpInputRecordDetail.setPushed(0);
                    reportErpInputRecordDetail.setType(Integer.valueOf(map.get("type").toString()));
                    reportErpInputRecordDetail.setLotNo(map.get("lotNo") == null ? "" :map.get("lotNo").toString());
                    reportErpInputRecordDetail.setMaterialCode(map.get("materialCode") == null ? "" :map.get("materialCode").toString());
                    reportErpInputRecordDetail.setErpBatchNo(map.get("erpBatchNo") == null ? "" :map.get("erpBatchNo").toString());
                    reportErpInputRecordDetail.setErpWarehouseCode(map.get("erpWarehouseCode") == null ? "" :map.get("erpWarehouseCode").toString());
                    BigDecimal weight1 = map.get("weight") == null ? BigDecimal.ZERO:new BigDecimal(map.get("weight").toString());
                    reportErpInputRecordDetail.setWeight(weight1);
                    weight = weight.add(weight1);
                    reportErpInputRecordDetails.add(reportErpInputRecordDetail);
                }
                reportErpInputRecordDetailService.saveAll(reportErpInputRecordDetails);
                reportErpInputRecord.setQuantity(weight);
                reportErpInputRecordService.saveOrUpdate(reportErpInputRecord);
            }

            //更改原来库里是否拉取的字段
            blastFurnaceDetailService.updatePulledState(idList1);
            inputFurnaceDetailService.updatePulledState(idList2);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private String getNumber(String date) {
        String key = "order_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, 3, "0");
        return strSequence;
    }


}
