package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.base;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IPersonCheckDetailService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesOrderJob;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesPersonCheckDetail;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.PersonCheckModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOrderJobRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesPersonCheckDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCellRepository;
import cn.estsh.i3plus.pojo.mes.sqlpack.MesHqlPack;
import cn.estsh.i3plus.pojo.mes.sqlpack.MesPcnHqlPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * @Author: xiangming.liao
 * @CreateDate: 2021/02/05 13:52
 * @Description:
 **/
@Service
public class PersonCheckDetailService implements IPersonCheckDetailService {
    @Autowired
    private MesPersonCheckDetailRepository personCheckDetailRDao;
    @Autowired
    private MesOrderJobRepository mesOrderJobRDao;
    @Autowired
    private MesWorkCellRepository mesWorkCellRDao;

    @Override
    @Transactional(readOnly = false)
    public PersonCheckModel queryPersonCheckDetail(MesPersonCheckDetail personCheckDetail) {
        DdlPackBean packBean = MesPcnHqlPack.getAllBaseData(personCheckDetail.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(personCheckDetail.getOrderNo(), MesPcnExtConstWords.ORDER_NO, packBean);
        DdlPreparedPack.getStringEqualPack(personCheckDetail.getWorkCellCode(), MesPcnExtConstWords.WORK_CELL_CODE, packBean);
        packBean.setOrderByStr(personCheckDetail.orderBy());

        List<MesPersonCheckDetail> personCheckDetailList = personCheckDetailRDao.findByHqlWhere(packBean);
        PersonCheckModel personCheckModel=new PersonCheckModel();
        personCheckModel.setCheckDetailList(personCheckDetailList);

        //根据工位代码分组,设置工位点检状态，组装工位数据
        Map<String, List<MesPersonCheckDetail>> CellMap = personCheckDetailList.stream().collect(Collectors.groupingBy(MesPersonCheckDetail::getWorkCellCode));
        List<MesPersonCheckDetail> cellList=new ArrayList<>();
        Set<Map.Entry<String, List<MesPersonCheckDetail>>> entries = CellMap.entrySet();
        for (Map.Entry<String, List<MesPersonCheckDetail>> entry : entries) {
            List<MesPersonCheckDetail> personCheckDetails = entry.getValue();
            MesPersonCheckDetail dataModel=new MesPersonCheckDetail();
            List<MesPersonCheckDetail> noComplate = personCheckDetails.stream().filter(p -> p.getOrderStatus() != 30).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(noComplate)){
                dataModel.setIsCellAllComplate(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
            }else{
                dataModel.setIsCellAllComplate(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
            }
            dataModel.setWorkCellCode(entry.getKey());
            dataModel.setOrderNo(personCheckDetails.get(0).getOrderNo());
            dataModel.setProcessCode(personCheckDetails.get(0).getProcessCode());
            dataModel.setProcessName(personCheckDetails.get(0).getProcessName());
            dataModel.setTaskUser(personCheckDetails.get(0).getTaskUser());
            dataModel.setOrderStatus(personCheckDetails.get(0).getOrderStatus());
            dataModel.setId(personCheckDetails.get(0).getId());
            cellList.add(dataModel);
        }
        personCheckModel.setCellList(cellList);
       /* if(!CollectionUtils.isEmpty(personCheckDetailList)){
            personCheckDetailList.forEach(p->{
                personCheckDetailRDao.updateByProperties(new String[]{MesPcnExtConstWords.ID}, new Object[]{p.getId()},
                        new String[]{MesPcnExtConstWords.ORDER_STATUS, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME},
                        new Object[]{MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECKING.getValue(), p.getModifyUser(), TimeTool.getNowTime(true)});
            });
        }*/
        return personCheckModel;
    }

    @Override
    public void updatePersonCheckDetail(MesPersonCheckDetail personCheckDetail) {
        MesPersonCheckDetail detailById = personCheckDetailRDao.getById(personCheckDetail.getId());
        if (null == detailById) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("该条数据不存在")
                    .build();
        }

        personCheckDetail.setCheckTime(TimeTool.getNowTime(true));
        personCheckDetail.setCheckUser(personCheckDetail.getModifyUser());
        personCheckDetail.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECK_COMPLETE.getValue());
        ConvertBean.serviceModelUpdate(personCheckDetail, personCheckDetail.getModifyUser());
        personCheckDetailRDao.save(personCheckDetail);

        //单据主表状态改为点检中
        updateOrderJobStatus(personCheckDetail);
        /*if (updateOrderJobStatus(personCheckDetail)) return true;
        return false;*/
    }

    @Override
    public void updatePersonCheckClose(MesPersonCheckDetail personCheckDetail) {
        personCheckDetailRDao.updateByProperties(new String[]{MesPcnExtConstWords.ORDER_NO, MesPcnExtConstWords.WORK_CELL_CODE}, new Object[]{personCheckDetail.getOrderNo(), personCheckDetail.getWorkCellCode()},
                new String[]{MesPcnExtConstWords.ORDER_STATUS, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME},
                new Object[]{MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CLOSE.getValue(), personCheckDetail.getModifyUser(), TimeTool.getNowTime(true)});

        //单据主表状态改为点检中
        updateOrderJobStatus(personCheckDetail);
        /*if (updateOrderJobStatus(personCheckDetail)) return true;

        return false;*/
    }

    private void updateOrderJobStatus(MesPersonCheckDetail personCheckDetail) {
        //单据主表状态改为点检中
        MesOrderJob mesOrderJob = mesOrderJobRDao.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.ORDER_NO},
                new Object[]{personCheckDetail.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),
                        MesPcnExtEnumUtil.IS_VAILD.VAILD.getValue(), personCheckDetail.getOrderNo()});
        if (mesOrderJob.getOrderStatus() == MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CREATE.getValue()) {
            mesOrderJob.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECKING.getValue());
            mesOrderJob.setComplateTime(TimeTool.getNowTime(true));
            ConvertBean.serviceModelUpdate(mesOrderJob, personCheckDetail.getModifyUser());
            mesOrderJobRDao.save(mesOrderJob);
        }

        /*//查询单据下点检单是否全部完成
        DdlPackBean packBean = MesPcnHqlPack.getAllBaseData(personCheckDetail.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(personCheckDetail.getOrderNo(), MesPcnExtConstWords.ORDER_NO, packBean);
        DdlPreparedPack.getInPackArray(new Object[]{MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CREATE.getValue(), MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECKING.getValue()},
                MesPcnExtConstWords.ORDER_STATUS, packBean);
        List<MesPersonCheckDetail> checkDetails = personCheckDetailRDao.findByHqlWhere(packBean);
        if (CollectionUtils.isEmpty(checkDetails)) {
            mesOrderJob.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECK_COMPLETE.getValue());
            mesOrderJob.setComplateTime(TimeTool.getNowTime(true));
            ConvertBean.serviceModelUpdate(mesOrderJob, personCheckDetail.getModifyUser());
            mesOrderJobRDao.save(mesOrderJob);
            return true;
        }
        return false;*/
    }

    @Override
    public void updateTaskUserByCell(MesPersonCheckDetail personCheckDetail) {
        personCheckDetailRDao.updateByProperties(new String[]{MesPcnExtConstWords.ORDER_NO, MesPcnExtConstWords.WORK_CELL_CODE}, new Object[]{personCheckDetail.getOrderNo(), personCheckDetail.getWorkCellCode()},
                new String[]{MesPcnExtConstWords.TASK_USER, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME},
                new Object[]{personCheckDetail.getTaskUser(), personCheckDetail.getModifyUser(), TimeTool.getNowTime(true)});
    }

    @Override
    public List<MesWorkCell> queryCellByOrderNo(String orderNo, String organizeCode) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(organizeCode);
        DdlPreparedPack.getStringEqualPack(orderNo, MesPcnExtConstWords.ORDER_NO, packBean);
        List<MesPersonCheckDetail> checkDetailList = personCheckDetailRDao.findByHqlWhere(packBean);
        List<String> centerList = checkDetailList.stream().map(MesPersonCheckDetail::getWorkCenterCode).collect(Collectors.toList());
        List<String> cellList = checkDetailList.stream().map(MesPersonCheckDetail::getWorkCellCode).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(cellList)) {
            return null;
        }
        DdlPackBean cellPackBean = MesHqlPack.getMesAllData(organizeCode);
        DdlPreparedPack.getInPackList(cellList, MesPcnExtConstWords.WORK_CELL_CODE, cellPackBean);
        DdlPreparedPack.getInPackList(centerList, MesPcnExtConstWords.WORK_CENTER_CODE, cellPackBean);
        return mesWorkCellRDao.findByHqlWhere(cellPackBean);
    }
}
