package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.busi.bu;

import cn.estsh.i3plus.ext.mes.api.base.IProdOrgExtService;
import cn.estsh.i3plus.ext.mes.api.base.bu.IBuWorkTimeDetailService;
import cn.estsh.i3plus.ext.mes.api.base.bu.IBusiConfigService;
import cn.estsh.i3plus.ext.mes.api.base.bu3.ISxPartCategoryPlanRateService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesShiftProdCenterRecord;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkCenterExt;
import cn.estsh.i3plus.ext.mes.pojo.model.bu.BuWorkTimeDetailModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesShiftProdCenterRecordRepository;
import cn.estsh.i3plus.ext.mes.pojo.sqlpack.MesExtHqlPack;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCenter;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xinwang.yi
 * @CreateDate: 2021/01/19 15:15 下午
 * @Description:
 **/
@Service
public class MesShiftProdCenterRecordService implements IBuWorkTimeDetailService {

    @Autowired
    private MesShiftProdCenterRecordRepository shiftProdCenterRecordRepository;

    @Autowired
    private IProdOrgExtService prodOrgExtService;

    @Autowired
    private IBusiConfigService busiConfigService;

    @Autowired
    private ISxPartCategoryPlanRateService partCategoryPlanRateService;

    @Override
    public MesShiftProdCenterRecord insertWorkTimeDetail(MesShiftProdCenterRecord mesShiftProdCenterRecord) {
        updateCategoryAndCareer(mesShiftProdCenterRecord);
        ConvertBean.saveOrUpdate(mesShiftProdCenterRecord, AuthUtil.getSessionUser().getUserName());
        return shiftProdCenterRecordRepository.insert(mesShiftProdCenterRecord);
    }

    private void updateCategoryAndCareer(MesShiftProdCenterRecord shiftProdCenterRecord) {
        MesWorkCenterExt workCenterDb = prodOrgExtService.getWorkCenterExt(shiftProdCenterRecord.getOrganizeCode(), shiftProdCenterRecord.getWorkCenterCode());
        shiftProdCenterRecord.setCategoryCode(workCenterDb.getCategoryCode());
        shiftProdCenterRecord.setCareerCode(workCenterDb.getCareerCode());
    }

    @Override
    public ListPager<BuWorkTimeDetailModel> queryWorkTimeDetailByPager(BuWorkTimeDetailModel model, Pager pager) {
        List<BuWorkTimeDetailModel> recordModelList = new ArrayList<>();
        DdlPackBean hqlPack = MesExtHqlPack.getWorkTimeDetail(model);
        pager = PagerHelper.getPager(pager, shiftProdCenterRecordRepository.findByHqlWhereCount(hqlPack));
        hqlPack.setOrderByStr(" order by workTime, workCenterCode, shiftCode, prodType, prodCode ");
        List<MesShiftProdCenterRecord> shiftProdCenterRecordList = shiftProdCenterRecordRepository.findByHqlWherePage(hqlPack, pager);
        if (!CollectionUtils.isEmpty(shiftProdCenterRecordList)) {

            List<MesWorkCenterExt> workCenterExtList = prodOrgExtService.queryWorkCenterExtList(model.getOrganizeCode());
            Map<String, List<MesWorkCenterExt>> workCenterCodeMap = CollectionUtils.isEmpty(workCenterExtList) ? null :
                    workCenterExtList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesWorkCenter::getWorkCenterCode));

            Map<String, String> careerMap = busiConfigService.getConfigMap(model.getOrganizeCode(), MesExtConstWords.SX_CAREER_CFG);
            Map<String, String> categoryMap = partCategoryPlanRateService.getCategoryMap(model.getOrganizeCode());

            for (MesShiftProdCenterRecord record : shiftProdCenterRecordList) {
                if (null == record) {
                    continue;
                }
                BuWorkTimeDetailModel detailModel = new BuWorkTimeDetailModel();
                BeanUtils.copyProperties(record, detailModel);
                detailModel.setWorkCenterName(
                        (!CollectionUtils.isEmpty(workCenterCodeMap) && workCenterCodeMap.containsKey(record.getWorkCenterCode())) ?
                                workCenterCodeMap.get(record.getWorkCenterCode()).get(0).getWorkCenterName() : record.getWorkCenterCode());
                detailModel.setProdTypeName(StringUtils.isEmpty(record.getProdType()) ?
                        null : MesExtEnumUtil.SHIFT_PROD_TYPE.valueOfDescription(record.getProdType()));
                detailModel.setDuration(getDuration(record.getStartTime(), record.getEndTime()));
                detailModel.setLossHour(MathOperation.mul(detailModel.getDuration(), record.getWorkerQty()));
                detailModel.setCareerName((!StringUtils.isEmpty(detailModel.getCareerCode()) && !CollectionUtils.isEmpty(careerMap) &&
                        careerMap.containsKey(detailModel.getCareerCode())) ? careerMap.get(detailModel.getCareerCode()) : null);
                detailModel.setCategoryName((!StringUtils.isEmpty(detailModel.getCategoryCode()) && !CollectionUtils.isEmpty(categoryMap) &&
                        categoryMap.containsKey(detailModel.getCategoryCode())) ? categoryMap.get(detailModel.getCategoryCode()) : null);
                recordModelList.add(detailModel);
            }
        }
        return new ListPager(recordModelList, pager);
    }

    private Double getDuration(String startTime, String endTime) {
        try {
            return new Double(TimeTool.getSecoundsBetweenTime(1, startTime, endTime) / 60);
        } catch (Exception e) {
            return new Double(0);
        }
    }

    @Override
    public MesShiftProdCenterRecord updateWorkTimeDetail(MesShiftProdCenterRecord mesShiftProdCenterRecord) {
        //对id做有效性校验
        MesShiftProdCenterRecord mesShiftProdCenterRecordDb = shiftProdCenterRecordRepository.getById(mesShiftProdCenterRecord.getId());
        if (mesShiftProdCenterRecordDb == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("记录不存在")
                    .build();
        }

        //唯一性校验
//        DdlPackBean packBean = MesHqlPack.getAllBaseData(mesShiftProdCenterRecord.getOrganizeCode());
//        DdlPreparedPack.getStringEqualPack(mesShiftProdCenterRecord.getWorkCellCode(), MesExtConstWords.WORK_CELL_CODE, packBean);
//        DdlPreparedPack.getStringEqualPack(mesShiftProdCenterRecord.getWorkCenterCode(), MesExtConstWords.WORK_CENTER_CODE, packBean);
//        DdlPreparedPack.getNumNOEqualPack(mesShiftProdCenterRecord.getId(), MesExtConstWords.ID, packBean);
//        List<MesShiftProdCenterRecord> MesShiftProdCenterRecordDbs = shiftProdCenterRecordRepository.findByHqlWhere(packBean);
//        if (!CollectionUtils.isEmpty(MesShiftProdCenterRecordDbs)) {
//            throw ImppExceptionBuilder.newInstance()
//                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
//                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
//                    .setErrorDetail("工位代码为【%s】，生产线代码为【%s】的记录已存在"
//                            , mesShiftProdCenterRecord.getWorkCellCode(), mesShiftProdCenterRecord.getWorkCenterCode())
//                    .build();
//        }
        mesShiftProdCenterRecordDb.setWorkerQty(mesShiftProdCenterRecord.getWorkerQty());
        mesShiftProdCenterRecordDb.setStartTime(mesShiftProdCenterRecord.getStartTime());
        mesShiftProdCenterRecordDb.setEndTime(mesShiftProdCenterRecord.getEndTime());
        mesShiftProdCenterRecordDb.setMemo(mesShiftProdCenterRecord.getMemo());
        mesShiftProdCenterRecordDb.setPartNo(mesShiftProdCenterRecord.getPartNo());
        mesShiftProdCenterRecordDb.setOrderNo(mesShiftProdCenterRecord.getOrderNo());
        mesShiftProdCenterRecordDb.setProdCode(mesShiftProdCenterRecord.getProdCode());
        mesShiftProdCenterRecordDb.setProdName(mesShiftProdCenterRecord.getProdName());

        updateCategoryAndCareer(mesShiftProdCenterRecordDb);

        ConvertBean.serviceModelUpdate(mesShiftProdCenterRecordDb, AuthUtil.getSessionUser().getUserName());
        return shiftProdCenterRecordRepository.save(mesShiftProdCenterRecordDb);
    }

    @Override
    public int deleteWorkTimeDetail(long id, String userName) {
//        List<MesShiftProdCenterRecord> cellList=shiftProdCenterRecordRepository.findByProperty(new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.ID},
//                new Object[]{AuthUtil.getOrganize().getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), MesExtEnumUtil.IS_VAILD.VAILD.getValue(), id});
//        if(StringUtils.isEmpty(cellList)){
//            throw ImppExceptionBuilder.newInstance()
//                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
//                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
//                    .setErrorDetail("该工序工位关系不存在")
//                    .build();
//        }
        return shiftProdCenterRecordRepository.deleteWeaklyById(id, userName);
    }
}
