package cn.estsh.i3plus.ext.mes.apiservice.schedulejob;

import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWorkOrderExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.ConvertBeanExt;
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.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.MesEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.impp.framework.base.schedule.BaseImppScheduleJob;
import cn.estsh.impp.framework.boot.init.ApplicationProperties;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 *
 * 下达到产线的工单如果排在顺序第一时默认启动。
 * @author yumingxing
 * @version 1.0
 * @date 2021/1/27 15:16
 **/
@DisallowConcurrentExecution
@ApiOperation("生产工单默认启动")
public class WorkOrderAutoOpen extends BaseImppScheduleJob {

    @Autowired
    private MesWorkOrderExtRepository workOrderExtRepository;

    public WorkOrderAutoOpen() {
        super(WorkOrderAutoOpen.class, "生产工单默认启动job");
    }


    @Override
    public void executeImppJob(JobExecutionContext context, ApplicationProperties applicationProperties) {
        String jobParam = this.getJobParam();
        if (StringUtils.isEmpty(jobParam)) {
            LOGGER.error("Mes业务数据同步定时任务,无法获取组织代码和方法代码");
            return;
        }

        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(jobParam);
        } catch (JSONException e) {
            LOGGER.error("Mes业务数据同步定时任务,参数异常，参数不是json格式");
            return;
        }

        Object organizeCode = jsonObject.get("organizationCode");
        int openValue = MesEnumUtil.WORK_ORDER_STATUS.OPEN.getValue();

        int landedValue = MesEnumUtil.WORK_ORDER_STATUS.LANDED.getValue();

        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode.toString());
        DdlPreparedPack.getNumEqualPack(landedValue,"workOrderStatus",ddlPackBean);
        List<MesWorkOrderExt> mesWorkOrders = workOrderExtRepository.findByHqlWhere(ddlPackBean);

        if (!CollectionUtils.isEmpty(mesWorkOrders)) {
            mesWorkOrders.sort(Comparator.comparing(MesWorkOrderExt::getSeq));
            Map<String, List<MesWorkOrderExt>> map = mesWorkOrders.stream().collect(Collectors.groupingBy(MesWorkOrderExt::getWorkCenterCode));
            Set<Map.Entry<String, List<MesWorkOrderExt>>> entries = map.entrySet();
            for (Map.Entry<String, List<MesWorkOrderExt>> entry : entries) {
                List<MesWorkOrderExt> mesWorkOrderExts = entry.getValue();
                String workCenterCode = entry.getKey();
                //判断该产线下是否有启动的工单 没有则启动顺序第一的工单
                DdlPackBean ddlPackBean1 = DdlPackBean.getDdlPackBean(organizeCode.toString());
                DdlPreparedPack.getNumEqualPack(openValue,"workOrderStatus",ddlPackBean1);
                DdlPreparedPack.getStringEqualPack(workCenterCode,"workCenterCode",ddlPackBean1);
                List<MesWorkOrderExt> openWorkOrders = workOrderExtRepository.findByHqlWhere(ddlPackBean1);
                if (CollectionUtils.isEmpty(openWorkOrders) && mesWorkOrderExts.size()>0) {
                    MesWorkOrderExt mesWorkOrderExt = mesWorkOrderExts.get(0);
                    mesWorkOrderExt.setWorkOrderStatus(openValue);
                    ConvertBean.serviceModelUpdate(mesWorkOrderExt, MesExtConstWords.JOB);
                    mesWorkOrderExt.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    new ConvertBeanExt(mesWorkOrderExt).convertBean(mesWorkOrderExt);
                    workOrderExtRepository.save(mesWorkOrderExt);
                    return;
                }
            }
        }

    }
}
