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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IPartExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IProcedureOnSiteService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesOnSiteOrder;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesOnSiteOrderDetail;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProcedureProject;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProjectSort;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOnSiteOrderDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOnSiteOrderRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesProcedureProjectRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesProjectSortRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
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.MesPart;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkOrder;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkOrderRepository;
import cn.estsh.i3plus.pojo.mes.sqlpack.MesPcnHqlPack;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
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.stream.Collectors;

/**
 * @Author: jessica.chen
 * @CreateDate: 2021/01/18 16:00
 * @Description:
 **/
@Service
public class ProcedureOnSiteService implements IProcedureOnSiteService {

    @Autowired
    private MesWorkOrderRepository mesWorkOrderRDao;

    @Autowired
    private MesOnSiteOrderRepository mesOnSiteOrderRDao;

    @Autowired
    private MesOnSiteOrderDetailRepository mesOnSiteOrderDetailRDao;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private MesProcedureProjectRepository mesProcedureProjectRDao;

    @Autowired
    private MesProjectSortRepository projectSortRepository;

    @Autowired
    private IPartExtService partExtService;

    @Autowired
    private MesProjectSortRepository mesProjectSortRDao;

    @Override
    public List<MesWorkOrder> findMesWorkOrderByWoStatus(String workCenterCode, String organizeCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", packBean);
        DdlPreparedPack.getNumEqualPack(MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue(), "workOrderStatus", packBean);
        return mesWorkOrderRDao.findByHqlWhere(packBean);
    }

    @Override
    public List<MesOnSiteOrder> findMesOnSiteOrderByWorkOrderNo(String workOrderNo, String organizeCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        List<Integer> statusList = new ArrayList<>();
        statusList.add(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CREATE.getValue());
        statusList.add(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECKING.getValue());
        DdlPreparedPack.getStringEqualPack(workOrderNo, "workOrderNo", packBean);
        DdlPreparedPack.getInPackList(statusList, "orderStatus", packBean);
        return mesOnSiteOrderRDao.findByHqlWhere(packBean);
    }

    @Override
    public void insertMesOnSiteOrderAndDetail(MesWorkOrder mesWorkOrder, String userName, List<Long> ids) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(mesWorkOrder.getOrganizeCode());
        DdlPreparedPack.getInPackList(ids, "id", packBean);
        List<MesProjectSort> projectSorts = projectSortRepository.findByHqlWhere(packBean);
        if (CollectionUtils.isEmpty(projectSorts)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("过程项目信息不存在数据，请检查")
                    .build();
        }
        List<String> projectSortNos = projectSorts.stream().map(MesProjectSort::getProjectSortNo).collect(Collectors.toList());
        DdlPackBean conditionMesProcedureProject = DdlPackBean.getDdlPackBean(mesWorkOrder.getOrganizeCode());
        DdlPreparedPack.getInPackList(projectSortNos, "projectSortNo", conditionMesProcedureProject);
        List<MesProcedureProject> mesProcedureProjects = mesProcedureProjectRDao.findByHqlWhere(conditionMesProcedureProject);
        MesPart partExt = partExtService.getPartExt(mesWorkOrder.getOrganizeCode(), mesWorkOrder.getPartNo());

        // 调用公共方法生成单号的方法
        List<String> orderNoList = getOrderNoByRuleCode(1,
                MesPcnExtConstWords.ON_SITE_ORDER_NO, new GenSerialNoModel(), userName, mesWorkOrder.getOrganizeCode());

        //生成巡检单主表信息
        MesOnSiteOrder mesOnSiteOrder = new MesOnSiteOrder();
        mesOnSiteOrder.setOrganizeCode(mesWorkOrder.getOrganizeCode());
        mesOnSiteOrder.setOrderNo(orderNoList.get(0));
        mesOnSiteOrder.setWorkCenterCode(mesWorkOrder.getWorkCenterCode());
        mesOnSiteOrder.setWorkOrderNo(mesWorkOrder.getOrderNo());
        mesOnSiteOrder.setPartNo(mesWorkOrder.getPartNo());
        if(partExt != null){
            mesOnSiteOrder.setPartNameRdd(partExt.getPartName());
        }
        mesOnSiteOrder.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CREATE.getValue());

        ConvertBean.serviceModelInitialize(mesOnSiteOrder, userName);
        mesOnSiteOrderRDao.insert(mesOnSiteOrder);

        //生成巡检单明细表信息
        for(MesProcedureProject procedureProject : mesProcedureProjects){
            MesOnSiteOrderDetail onSiteOrderDetail = new MesOnSiteOrderDetail();
            onSiteOrderDetail.setOrganizeCode(mesWorkOrder.getOrganizeCode());
            onSiteOrderDetail.setOrderNo(orderNoList.get(0));
            onSiteOrderDetail.setProjectSortNo(procedureProject.getProjectSortNo());
            onSiteOrderDetail.setProjectCode(procedureProject.getProjectCode());
            onSiteOrderDetail.setProjectName(procedureProject.getProjectName());
            onSiteOrderDetail.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            ConvertBean.serviceModelInitialize(onSiteOrderDetail, userName);
            mesOnSiteOrderDetailRDao.insert(onSiteOrderDetail);
        }
    }

    @Override
    public void updateMesOnSiteOrderByStatus(MesOnSiteOrder mesOnSiteOrder, String userName) {

        DdlPackBean packBean = MesPcnHqlPack.getAllBaseData(AuthUtil.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(mesOnSiteOrder.getOrderNo(), "orderNo", packBean);
        List<MesOnSiteOrderDetail> oDetailsTotal = mesOnSiteOrderDetailRDao.findByHqlWhere(packBean);

        DdlPreparedPack.getStringNotBlanklPack("checkResult", packBean);
        List<MesOnSiteOrderDetail> oDetails = mesOnSiteOrderDetailRDao.findByHqlWhere(packBean);
        mesOnSiteOrder.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECK_COMPLETE.getValue());
        if (oDetailsTotal.size() == oDetails.size()) {
            ConvertBean.serviceModelUpdate(mesOnSiteOrder, userName);
            mesOnSiteOrderRDao.save(mesOnSiteOrder);
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION.getCode())
                    .setErrorDetail("未点检完成不能提交")
                    .build();
        }


    }

    @Override
    public List<MesOnSiteOrderDetail> findMesOnSiteOrderDetail(String orderNo, String projectSortNo, String checkResult, String organizeCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        if (StringUtils.isEmpty(orderNo)) {
            return new ArrayList<>();
        }
        DdlPreparedPack.getStringEqualPack(orderNo, "orderNo", packBean);
        DdlPreparedPack.getStringLikerPack(projectSortNo, "projectSortNo", packBean);
        DdlPreparedPack.getStringEqualPack(checkResult, "checkResult", packBean);

        List<MesOnSiteOrderDetail> onSiteOrderDetails = mesOnSiteOrderDetailRDao.findByHqlWhere(packBean);
        for (MesOnSiteOrderDetail onSiteOrderDetail : onSiteOrderDetails) {
            packBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getStringEqualPack(onSiteOrderDetail.getProjectSortNo(), "projectSortNo", packBean);
            MesProjectSort projectSort = mesProjectSortRDao.getByProperty(packBean);
            if (projectSort != null) {
                onSiteOrderDetail.setProjectSortName(projectSort.getProjectSortName());
            }
        }
        return onSiteOrderDetails;
    }

    @Override
    public Boolean updateMesOnSiteOrderDetail(MesOnSiteOrderDetail mesOnSiteOrderDetail, String userName) {
        //修改巡检单明细数据
        MesOnSiteOrderDetail onSiteOrderDetail = mesOnSiteOrderDetailRDao.getById(mesOnSiteOrderDetail.getId());
        if (null == onSiteOrderDetail) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("数据不存在")
                    .build();
        }
        BeanUtils.copyProperties(mesOnSiteOrderDetail, onSiteOrderDetail);
        onSiteOrderDetail.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(onSiteOrderDetail, userName);
        mesOnSiteOrderDetailRDao.save(onSiteOrderDetail);

        //判断当前明细数据中【点检结果】字段存在数据
        DdlPackBean packBean = MesPcnHqlPack.getAllBaseData(mesOnSiteOrderDetail.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(mesOnSiteOrderDetail.getOrderNo(),"orderNo",packBean);
        List<MesOnSiteOrderDetail> oDetailsTotal = mesOnSiteOrderDetailRDao.findByHqlWhere(packBean);

        DdlPreparedPack.getStringNotBlanklPack("checkResult",packBean);
        List<MesOnSiteOrderDetail> oDetails = mesOnSiteOrderDetailRDao.findByHqlWhere(packBean);

        if(!CollectionUtils.isEmpty(oDetails)){
            MesOnSiteOrder mesOnSiteOrder = mesOnSiteOrderRDao.getByProperty(
                    new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, "orderNo"},
                    new Object[]{mesOnSiteOrderDetail.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),
                            MesPcnExtEnumUtil.IS_VAILD.VAILD.getValue(), mesOnSiteOrderDetail.getOrderNo()});
            if (oDetailsTotal.size() == oDetails.size()) {
//                mesOnSiteOrder.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECK_COMPLETE.getValue());
//                ConvertBean.serviceModelUpdate(mesOnSiteOrder, userName);
//
//                mesOnSiteOrderRDao.save(mesOnSiteOrder);

                return true;
            } else {
                mesOnSiteOrder.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECKING.getValue());
                ConvertBean.serviceModelUpdate(mesOnSiteOrder, userName);

                mesOnSiteOrderRDao.save(mesOnSiteOrder);
            }
        }

        return false;
    }

    @Override
    public List<MesProjectSort> findProjectSort(MesProjectSort procedureProject) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(procedureProject.getOrganizeCode());
        String projectSortNo = procedureProject.getProjectSortNo();
        DdlPreparedPack.getStringEqualPack(projectSortNo, "projectSortNo", packBean);
        return projectSortRepository.findByHqlWhere(packBean);
    }

    public List<String> getOrderNoByRuleCode(int number, String ruleCode, GenSerialNoModel genSerialNoModel, String userName, String org) {
        genSerialNoModel.setRuleCode(ruleCode);
        BaseResultBean<String> serialNumberBean = syncFuncService.syncSerialNo(genSerialNoModel, userName, org, Integer.valueOf(number));
        if (serialNumberBean != null && serialNumberBean.isSuccess()) {
            return serialNumberBean.getResultList();
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION.getCode())
                    .setErrorDetail("单号未生成成功")
                    .build();
        }
    }
}
