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

import com.sw.mes.agv.dao.MobileRechargeDAO;
import com.sw.mes.agv.entity.MobileRecharge;
import com.sw.mes.agv.service.MonitorEquipmentRechargeService;
import com.sw.mes.agv.service.RechargeArtBagItemService;
import com.sw.mes.agv.service.MobileRechargeService;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.factory.utils.PageUtils;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.third.service.SapGiService;
import com.sw.mes.yb.plan.service.ProductionScheduleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class MobileRechargeServiceImpl extends BaseServiceImpl<MobileRecharge> implements MobileRechargeService {

    MobileRechargeDAO mobileRechargeDAO;

    @Autowired
    public void setDao(MobileRechargeDAO mobileRechargeDAO) {
        this.mobileRechargeDAO = mobileRechargeDAO;
        super.setBaseDao(mobileRechargeDAO);
    }

    @Autowired
    private MonitorEquipmentRechargeService equipmentRechargeService;

//    @Autowired
//    private RechargeNumService rechargeNumService;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private RechargeArtBagItemService rechargeArtBagItemService;

    @Autowired
    private ProductionScheduleService sapProductionScheduleService;

    @Autowired
    private SapGiService sapGiService;

    @Override
    public List<MobileRecharge> findAll(RequestPage page) {
        org.springframework.data.domain.Page<MobileRecharge> springDataPage = mobileRechargeDAO.findAll(PageUtils.createPageable(page));
        page.setTotal(springDataPage.getTotalElements());
        return springDataPage.getContent();
    }

    @Override
    public List<MobileRecharge> findAll(Specification<MobileRecharge> specification) {
        return mobileRechargeDAO.findAll(specification);
    }

    @Override
    public List<MobileRecharge> findByExample(
            Specification<MobileRecharge> specification, RequestPage page) {
        org.springframework.data.domain.Page<MobileRecharge> springDataPage = mobileRechargeDAO.findAll(specification, PageUtils.createPageable(page));
        page.setTotal(springDataPage.getTotalElements());
        return springDataPage.getContent();
    }

    @Override
    public List<MobileRecharge> findBySlingCode(String slingCode) {
        return mobileRechargeDAO.findBySlingCode(slingCode);
    }

    @Override
    public MobileRecharge findLastBySlingCode(String code) {
        List<MobileRecharge> list = mobileRechargeDAO.findBySlingCode(code);
        if (list != null && list.size() > 0) {
            return list.get(list.size() - 1);
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> rechargeDetail(
            String startTime, String endTime,
            Long start, Integer rows
    ) {
        return mobileRechargeDAO.rechargeDetail(startTime, endTime, start, rows);
    }

    @Override
    public List<Map<String, Object>> rechargeDetailCount(
            String startTime, String endTime
    ) {
        return mobileRechargeDAO.rechargeDetailCount(startTime, endTime);
    }

    public String generateCodeByDeviceNo(String deviceNo) {
        Long time = System.currentTimeMillis();
        return deviceNo + time;
    }

    @Override
    public void create(MobileRecharge recharge) throws RuntimeException {

//        String deviceNo = recharge.getDeviceNo();
//        if (StringUtils.isBlank(deviceNo)) {
//            throw new RuntimeException("炉台编号不能为空！");
//        }
//
//        recharge.setRechargeCode(generateCodeByDeviceNo(deviceNo));
//
//        List<MobileChargeItem> list = recharge.getList();
//        if (list != null && list.size() > 0) {
//            for (MobileChargeItem item : list) {
//                if (StringUtils.isNotBlank(item.getMaterialCode())) {
//                    item.setRecharge(recharge);
//                }
//            }
//        } else {
//            list = new ArrayList<>();
//        }
//        //灌料总重量
//        Double currentCount = recharge.getCurrentCount();
//
//        recharge.setRechargeFinishTime(new Date());
////        recharge.setCurrentCount(currentCount);
//
//        MonitorEquipmentRecharge monitorEquipmentRecharge = equipmentRechargeService.getByName(deviceNo);
//        if (monitorEquipmentRecharge != null) {
//            // 判断是否已发送AGV请求
//            // 取消判断 2021-09-10
////            if (monitorEquipmentRecharge.getPadSend() == null || monitorEquipmentRecharge.getPadSend().equals(0)) {
//            monitorEquipmentRecharge.setLeftNum(0d);
//            monitorEquipmentRecharge.setRightNum(0d);
//            monitorEquipmentRecharge.setRechargeStartTime(recharge.getPreRechargeTime());
//            monitorEquipmentRecharge.setRechargeEndTime(recharge.getRechargeFinishTime());
//            if (monitorEquipmentRecharge.getPareNum() == null) {
//                monitorEquipmentRecharge.setPareNum(1);
//                monitorEquipmentRecharge.setPareWeight(currentCount);
//            } else {
//                monitorEquipmentRecharge.setPareNum(monitorEquipmentRecharge.getPareNum() + 1);
//                monitorEquipmentRecharge.setPareWeight(monitorEquipmentRecharge.getPareWeight() + currentCount);
//            }
//            // TODO 复投修改 0117
//            //如果灌料是第二桶 且剩余重量大于等于70，呼叫时间增加30分钟
////            if (monitorEquipmentRecharge.getPareNum() == 2 &&
////                    (monitorEquipmentRecharge.getRechargeWeight() - monitorEquipmentRecharge.getPareWeight() >= 70)) {
////                Calendar calendar = Calendar.getInstance();
////                calendar.setTime(monitorEquipmentRecharge.getPreSlingTime());
////                calendar.add(Calendar.MINUTE, 30);
////                monitorEquipmentRecharge.setPreSlingTime(calendar.getTime());
////            }
//            monitorEquipmentRecharge.setPadSend(1);
//            equipmentRechargeService.saveOrUpdate(monitorEquipmentRecharge);
////            } else {
////                throw new RuntimeException("炉台[" + deviceNo + "]已灌料！");
////            }
//
//            recharge.setRechargeType(monitorEquipmentRecharge.getRechargeType());
//        }
//
//        String lotNo = batchInfoService.getCurrentLotNo(deviceNo);
//        recharge.setLotNo(lotNo);
//        for(MobileChargeItem item:recharge.getList()){
//            item.setIsGi(0);
//        }
//        saveOrUpdate(recharge);
//
////        monitorEquipmentRechargeService.updateRechargeEndTime(recharge.getRechargeFinishTime(), recharge.getDeviceNo());
//
//        List<RechargeNum> rechargeNums = rechargeNumService.getMaxNumListByLotNo(lotNo);
//        Map<String, RechargeNum> rechargeNumMap = new HashMap<>();
//        Integer tempRechargeNum = 1;
//        if (rechargeNums != null && rechargeNums.size() > 0) {
//            Date tempDate = rechargeNums.get(0).getCreateDate();
//            tempRechargeNum = rechargeNums.get(0).getRechargeNum();
//            Double hour = DateUtil.secondsBetween(tempDate, new Date());
//            //10个小时以内统一算作同一次复投
//            if (hour < 36000) {
//                for (RechargeNum num : rechargeNums) {
//                    rechargeNumMap.put(num.getMaterialCode(), num);
//                }
//            } else {
//                tempRechargeNum++;
//            }
//        }
//
//        List<RechargeArtBagItem> artBagItems = rechargeArtBagItemService.findByDeviceNo(deviceNo);
//        Map<String, RechargeArtBagItem> artBagItemMap = new HashMap<>();
//        if (artBagItems != null && artBagItems.size() > 0) {
//            for (RechargeArtBagItem item : artBagItems) {
//                if (item.getMaterialModel() != null) {
//                    artBagItemMap.put(item.getMaterialModel().getCode(), item);
//                }
//            }
//        }
//
//        for (MobileChargeItem item : list) {
//
//            if (StringUtils.isBlank(item.getMaterialCode())) {
//                continue;
//            }
//
//            RechargeNum tempNum;
//            if (rechargeNumMap.containsKey(item.getMaterialCode())) {
//                tempNum = rechargeNumMap.get(item.getMaterialCode());
//                tempNum.setRechargeCount(tempNum.getRechargeCount() + 1);
//                tempNum.setRechargeWeight(tempNum.getRechargeWeight() + item.getCount());
//                tempNum.setEachInfo(tempNum.getEachInfo() + ";" + item.getMaterialName() + "[" + item.getCount() + "]" + item.getUnit());
//            } else {
//                tempNum = new RechargeNum();
//                tempNum.setMaterialCode(item.getMaterialCode());
//                tempNum.setLotNo(lotNo);
//                tempNum.setRechargeNum(1);
//                tempNum.setRechargeWeight(item.getCount());
//                tempNum.setEachInfo(item.getMaterialName() + "[" + item.getCount() + "]" + item.getUnit());
//                tempNum.setCreateDate(new Date());
//                tempNum.setRechargeNum(tempRechargeNum);
//                tempNum.setRechargeCount(1);
//                if (item.getMaterialId() != null) {
//                    MaterialModel materialModel = materialModelService.get(item.getMaterialId());
//                    if (materialModel != null) {
//                        tempNum.setModel(materialModel);
//                    }
//                }
//                rechargeNumMap.put(item.getMaterialCode(), tempNum);
//            }
//
//            if (artBagItemMap.containsKey(item.getMaterialCode())) {
//                RechargeArtBagItem artBagItem = artBagItemMap.get(item.getMaterialCode());
//                if (artBagItem != null) {
//                    artBagItem.setCount(artBagItem.getCount().add(BigDecimal.valueOf(item.getCount())));
//                    rechargeArtBagItemService.saveOrUpdate(artBagItem);
//                }
//            }
//
//        }
//
//        if (rechargeNumMap.size() > 0) {
//            rechargeNumService.saveOrUpdateInBatch(new ArrayList<>(rechargeNumMap.values()));
//        }

        //region 向SAP发送装料数据 GI 主材消耗
//        try {
//            List<SapGi> sapGiList = new ArrayList();
//            Date nowTime = new Date();
//            for (MobileChargeItem item : list) {
//                List<MaterialModel> materialModelList = materialModelService.findMaterialModelByCode(item.getMaterialCode());
//                if (materialModelList != null && materialModelList.size() > 0) {
//                    MaterialModel materialModel = materialModelList.get(0);
//                    if (materialModel.getSpecification().startsWith("A01") || materialModel.getSpecification().startsWith("A03")) {
//                        ProductionSchedule sapProductionSchedule = sapProductionScheduleService.getByDeviceNoAndStatusDesc(recharge.getDeviceNo(), ProductionStateEnums.ProductionStateType.进行中.getValue());
//                        if (sapProductionSchedule == null) {
//                            //查询该设备最近一次的工单
//                            sapProductionSchedule = sapProductionScheduleService.getByDeviceNo(recharge.getDeviceNo());
//                        }
//                        if (sapProductionSchedule != null && StringUtils.isNotBlank(sapProductionSchedule.getProductNo())) {
//                            String sapDate = SapUtil.getDateNowForSap(540);
//                            ProductionSchedule sapProductionSchedule1 = sapProductionScheduleService.getByDeviceNoAndDate(lotNo.substring(4, 7), sapDate);
//                            if (sapProductionSchedule1 != null && StringUtils.isNotBlank(sapProductionSchedule1.getOrderNo())) {
//                                SapGi sapGi = new SapGi();
//                                sapGi.setZmesid(UUID.randomUUID().toString());
//                                sapGi.setWerks("1011");
//                                sapGi.setAufnr(sapProductionSchedule1.getOrderNo());
//                                sapGi.setBty("1");//新增
//                                sapGi.setCharg(SapStaticEnum.SapStaticValue.GI固定批次号.getValue());//批次号 虚拟
//                                sapGi.setLgort(SapStaticEnum.SapStaticValue.GI固定库存地点.getValue());//固定库存地点 虚拟
//                                sapGi.setIssuedate(WbServiceUtils.getSapDate(nowTime));//日期 yyyymmdd
//                                sapGi.setIssuetime(WbServiceUtils.getSapTime(nowTime));//时间 HHmmss
//                                sapGi.setMatnr(sapProductionSchedule.getProductNo());//新物料号
//                                sapGi.setMatnrmat(item.getMaterialCode());//旧物料号
//                                sapGi.setMeins("KG");//单位
//                                sapGi.setMenge(new BigDecimal(item.getCount()));//数量
//                                sapGi.setSource("");
//                                sapGiList.add(sapGi);
//                            }
//                        }
//                    }
//                }
//            }
//            if (sapGiList != null && sapGiList.size() > 0) {
//                sapGiService.saveBatch(sapGiList);
//            }
//        } catch (Exception e) {
//            throw new RuntimeException("向SAP发送灌料GI消耗异常:" + e.getMessage());
//        }
        //endregion
    }

    @Override
    public void backoff(Long techId, BigDecimal backoffWeight, String backoffReason) {
        MobileRecharge recharge = findByTechIdLimit(techId);
        if (recharge != null) {
            if (recharge.getBackoffWeight() == null || recharge.getBackoffWeight().compareTo(BigDecimal.ZERO) <= 0) {
                recharge.setBackoffWeight(backoffWeight);
            } else {
                recharge.setBackoffWeight(recharge.getBackoffWeight().add(backoffWeight));
            }
            if (StringUtils.isBlank(recharge.getBackoffReason())) {
                recharge.setBackoffReason(backoffReason);
            } else {
                recharge.setBackoffReason(recharge.getBackoffReason() + "," + backoffReason);
            }

            saveOrUpdate(recharge);
        }
    }

    private MobileRecharge findByTechIdLimit(Long techId) {
        return mobileRechargeDAO.findByTechIdLimit(techId);
    }

}
