package com.foreverwin.mesnac.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.mapper.InspectionTaskMapper;
import com.foreverwin.mesnac.common.model.InspectionItemDetail;
import com.foreverwin.mesnac.common.model.InspectionTask;
import com.foreverwin.mesnac.common.model.InspectionTaskDetail;
import com.foreverwin.mesnac.common.service.InspectionItemDetailService;
import com.foreverwin.mesnac.common.service.InspectionItemService;
import com.foreverwin.mesnac.common.service.InspectionTaskDetailService;
import com.foreverwin.mesnac.common.service.InspectionTaskService;
import com.foreverwin.mesnac.common.util.DateUtil;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.meapi.model.Sfc;
import com.foreverwin.mesnac.meapi.service.SfcService;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 检验任务表 服务实现类
 * </p>
 *
 * @author Philip
 * @since 2021-07-05
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class InspectionTaskServiceImpl extends ServiceImpl<InspectionTaskMapper, InspectionTask> implements InspectionTaskService {
    @Autowired
    private SfcService sfcService;
    @Autowired
    private InspectionTaskMapper inspectionTaskMapper;
    @Autowired
    private InspectionItemService inspectionItemService;
    @Autowired
    private InspectionItemDetailService inspectionItemDetailService;
    @Autowired
    private InspectionTaskDetailService inspectionTaskDetailService;


    @Override
    public IPage<InspectionTask> selectPage(FrontPage<InspectionTask> frontPage, InspectionTask inspectionTask) {
        QueryWrapper<InspectionTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(inspectionTask);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<InspectionTask> selectList(InspectionTask inspectionTask) {
        QueryWrapper<InspectionTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(inspectionTask);
        return super.list(queryWrapper);
    }

    @Override
    public InspectionTask getInspectionTaskByTaskNo(String site, String taskNo) {
        return inspectionTaskMapper.selectInspectionTaskByTaskNo(site, taskNo);
    }

    @Override
    public void saveTask(Map<String, Object> paramMap) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        //类型(首检|S/巡检|X/专检|Y/FQC|F/尾检|W/自检|Z/互检|H)
        String category = (String) paramMap.get("CATEGORY");
        //获取检验项目
        List<Map<String, Object>> taskList = (List<Map<String, Object>>) paramMap.get("taskList");
        //更新任务表
        InspectionTask task = new InspectionTask();
        String taskHandle = (String) paramMap.get("TASK_HANDLE");
        if(StringUtil.isEmpty(taskHandle)){
            throw new BaseException("保存失败,请先进行检索数据!");
        }
        InspectionTask byId = getById(taskHandle);
        if (byId==null){
            throw new BaseException("未找到检验任务");
        }
        String  result= byId.getResult();
        if(StringUtil.notBlank(result)&&result.equals(Constants.RSESULT_OK)){
            throw new BaseException("检验任务已经保存合格!");
        }
        task.setComments((String) paramMap.get("COMMENTS"));
        task.setStatus(Constants.INSPECTION_TASK_STATUS_COMPLETE);
        task.setModifyUser(user);
        task.setModifiedDateTime(LocalDateTime.now());
        task.setResult((String) paramMap.get("result"));
        UpdateWrapper<InspectionTask> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq(InspectionTask.HANDLE,taskHandle);
        update(task,updateWrapper);
        //新增任务从表
        if (taskList != null && taskList.size() != 0) {
            List<InspectionTaskDetail> detailList = new ArrayList<>();
            for (int i = 0; i < taskList.size(); i++) {
                String taskListHandle = HandleEnum.INSPECTION_TASK_DETAIL.getHandle(site, UUID.randomUUID().toString());
                InspectionTaskDetail inspectionTaskDetail = new InspectionTaskDetail();
                inspectionTaskDetail.setHandle(taskListHandle);
                inspectionTaskDetail.setSite(site);
                inspectionTaskDetail.setTaskBo(taskHandle);
                inspectionTaskDetail.setInspectionItemDetailBo((String) taskList.get(i).get("handle"));
                inspectionTaskDetail.setCheckUser(user);
                String paramType = (String) taskList.get(i).get("paramType");
                String checkValue = "";
                if (paramType.equals("布尔")) {
                    checkValue = (String) taskList.get(i).get("CHECK_VALUE1");
                } else {
                    checkValue = (String) taskList.get(i).get("CHECK_VALUE2");
                }
                inspectionTaskDetail.setCheckValues(checkValue);
                inspectionTaskDetail.setResult((String) taskList.get(i).get("result"));

                String remark = (String) taskList.get(i).get("remark");
                if (StringUtil.isBlank(remark)) {
                    inspectionTaskDetail.setRemark("");
                } else {
                    inspectionTaskDetail.setRemark(remark);
                }

                String pictureNo = (String) taskList.get(i).get("pictureNo");
                if (StringUtil.isBlank(pictureNo)) {
                    inspectionTaskDetail.setPictureNo("");
                } else {
                    inspectionTaskDetail.setPictureNo(pictureNo);
                }

                String pictureQty = (String) taskList.get(i).get("pictureQty");
                if ("".equals(pictureQty) || null == pictureQty || "NULL".equals(pictureQty)) {
                    inspectionTaskDetail.setPictureQty("0");
                } else {
                    inspectionTaskDetail.setPictureQty(pictureQty);
                }
                detailList.add(inspectionTaskDetail);
            }
            inspectionTaskDetailService.saveBatch(detailList);
        }

    }

    @Override
    public Map<String, Object> createTask(Map<String, Object> paramMap) {
        Map<String,Object>map=new HashMap<>();

        //站点
        String site = CommonMethods.getSite();
        //类型(自检|Z;互检|H;FQC|F;尾检|W)
        String category = (String) paramMap.get("CATEGORY");
        //产品批次
        String sfc = (String) paramMap.get("SFC");
        Sfc sfcServiceById = sfcService.getById(HandleEnum.SFC.getHandle(site, sfc));
        String shopOrder = StringUtil.trimHandle(sfcServiceById.getShopOrderBo());
        //工序
        String operation = (String) paramMap.get("OPERATION");
        //工序标识
        String stepId = (String) paramMap.get("STEP_ID");
        List<InspectionItemDetail> inspectionItemDetails = inspectionItemService.selectQualityInspection(sfc, operation, stepId, category);
        if (inspectionItemDetails.size() == 0||inspectionItemDetails.get(0)==null) {
            throw new BaseException("创建任务失败,未维护数据收集组!");
        }
        //自检/互检/包装 校验是否在当前工序+工序标识 做过检验任务
        InspectionTask createTask = isCreateTask(site, category, sfc, operation, stepId);
        if (createTask!=null&&createTask.getStatus().equals(Constants.INSPECTION_TASK_STATUS_COMPLETE)) {
            throw new BaseException("当前产品批次[" + sfc + "]已做完检验任务");
        }
        String inspectionItemBo = inspectionItemDetails.get(0).getInspectionItemBo();

        if (createTask!=null){
            map.put("taskHandle",createTask.getHandle());
        }else {
            String timeString = DateUtil.getTimeString();
            String taskNo = "";
            String itemNumber = (String) paramMap.get("ITEM_NUMBER");
            String description = "";
            if (category.equals(Constants.INSPECTION_TYPE_Z)) {
                if (StringUtil.isBlank(itemNumber) ) {
                    taskNo = "Z_" + timeString;
                } else{
                    taskNo = "Z_" + itemNumber + "_" + timeString;
                }
                description = "自检检验任务";
            } else if (category.equals(Constants.INSPECTION_TYPE_H)) {
                if (StringUtil.isBlank(itemNumber)) {
                    taskNo = "H_" + timeString;
                } else {
                    taskNo = "H_" + itemNumber + "_" + timeString;
                }
                description = "互检检验任务";
            } else if (category.equals(Constants.INSPECTION_TYPE_S)) {
                if (StringUtil.isBlank(itemNumber)) {
                    taskNo = "S_" + timeString;
                } else {
                    taskNo = "S_" + itemNumber + "_" + timeString;
                }
                description = "首件检验任务";
            }  else if (category.equals(Constants.INSPECTION_TYPE_P)) {
                if (StringUtil.isBlank(itemNumber)) {
                    taskNo = "P_" + timeString;
                } else {
                    taskNo = "P_" + itemNumber + "_" + timeString;
                }
                description = "专检检验任务";
            } else {
                throw new BaseException("生成任务号失败,请传入检验类型!");
            }
            String handle = "InspectionBO:" + site + "," + taskNo;

            InspectionTask task = new InspectionTask();
            task.setHandle(handle);
            task.setSite(site);
            task.setCategory(category);
            task.setTaskNo(taskNo);
            task.setStatus(Constants.INSPECTION_TASK_STATUS_NEW);
            task.setDescription(description);
            task.setInspectionItemBo( inspectionItemBo);
            task.setShopOrder(shopOrder);
            task.setWorkCenter((String) paramMap.get("WORK_CENTER"));
            task.setSfc(sfc);
            task.setOperation(operation);
            task.setStepId(stepId);
            task.setResrce((String) paramMap.get("RESRCE"));
            task.setCreateUser(CommonMethods.getUser());
            task.setCreatedDateTime(LocalDateTime.now());
            task.setModifyUser(CommonMethods.getUser());
            task.setModifiedDateTime(LocalDateTime.now());
            task.setSfcDispatchBo((String) paramMap.get("SFC_DISPATCH_DETAIL_BO"));
            task.setSfc(sfc);
            save(task);
            map.put("taskHandle",handle);
        }
        QueryWrapper<InspectionItemDetail> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(InspectionItemDetail.INSPECTION_ITEM_BO,inspectionItemBo);
        queryWrapper.orderByAsc(InspectionItemDetail.SEQ);
        List<InspectionItemDetail> list = inspectionItemDetailService.list(queryWrapper);
        map.put("inspectionItemList",list);
        map.put("inspectItemNo",StringUtil.trimHandle(inspectionItemBo));
        return map;
    }
    @Override
    public InspectionTask isCreateTask(String site,String category,String sfc,String operation ,String stepId)  {
        //自检/互检 校验是否在当前工序+工序标识 做过检验任务
        QueryWrapper<InspectionTask> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(InspectionTask.SITE,site);
        queryWrapper.eq(InspectionTask.SFC,sfc);
        queryWrapper.eq(InspectionTask.CATEGORY,category);
        queryWrapper.eq(InspectionTask.OPERATION,operation);
        queryWrapper.eq(InspectionTask.STEP_ID,stepId);
        queryWrapper.orderByDesc(InspectionTask.CREATED_DATE_TIME);
        List<InspectionTask> list = list(queryWrapper);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void createNewTask(Map<String, Object> paramMap) {
        String site = CommonMethods.getSite();
        String category = (String) paramMap.get("CATEGORY");
        String sfc = (String) paramMap.get("SFC");
        String shopOrder = (String) paramMap.get("SHOP_ORDER");
        String operation = (String) paramMap.get("OPERATION");
        String stepId = (String) paramMap.get("STEP_ID");
        String itemNumber = (String) paramMap.get("ITEM_NUMBER");

        String taskNo = "";
        String timeString = DateUtil.getTimeString();
        if (StringUtil.isBlank(itemNumber)) {
            taskNo = "P_" + timeString;
        } else {
            taskNo = "P_" + itemNumber + "_" + timeString;
        }
        String handle = "InspectionBO:" + site + "," + taskNo;
        InspectionTask task = new InspectionTask();
        task.setHandle(handle);
        task.setSite(site);
        task.setCategory(category);
        task.setTaskNo(taskNo);
        task.setStatus(Constants.INSPECTION_TASK_STATUS_NEW);
        task.setResult(null);
        task.setDescription("专检检验任务");
        task.setInspectionItemBo( null);
        task.setShopOrder(shopOrder);
        task.setWorkCenter((String) paramMap.get("WORK_CENTER"));
        task.setSfc(sfc);
        task.setOperation(operation);
        task.setStepId(stepId);
        task.setResrce((String) paramMap.get("RESRCE"));
        task.setCreateUser(CommonMethods.getUser());
        task.setCreatedDateTime(LocalDateTime.now());
        task.setModifyUser(CommonMethods.getUser());
        task.setModifiedDateTime(LocalDateTime.now());
        task.setSfcDispatchBo((String) paramMap.get("SFC_DISPATCH_DETAIL_BO"));
        task.setSfc(sfc);
        save(task);
    }


}