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

import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.model.InspectionTask;
import com.foreverwin.mesnac.common.model.InspectionTaskDetail;
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.quality.dto.InspectionTaskManageRequest;
import com.foreverwin.mesnac.quality.mapper.InspectionTaskManageMapper;
import com.foreverwin.mesnac.quality.model.InspectionTaskManageDetail;
import com.foreverwin.mesnac.quality.model.InspectionTaskManage;
import com.foreverwin.mesnac.quality.service.InspectionTaskManageService;
import com.foreverwin.modular.core.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Transactional(rollbackFor = Exception.class)
public class InspectionTaskManageServiceImpl implements InspectionTaskManageService {

    @Autowired
    private InspectionTaskService inspectionTaskService;
    @Autowired
    private InspectionTaskManageMapper inspectionTaskManageMapper;
    @Autowired
    private InspectionTaskDetailService inspectionTaskDetailService;

    @Override
    public List<InspectionTaskManage> findInspectionTask(InspectionTaskManageRequest inspectionTaskManageRequest) {
        return inspectionTaskManageMapper.findInspectionTask(inspectionTaskManageRequest);
    }

    @Override
    public InspectionTaskManage findInspectionTaskAndDetail(InspectionTaskManageRequest inspectionTaskManageRequest) {
        List<InspectionTaskManage> manageList = this.findInspectionTask(inspectionTaskManageRequest);
        if (manageList == null || manageList.size() <= 0) {
            throw BusinessException.build("产品条码没有可执行的检验任务！");
        }
        String site = inspectionTaskManageRequest.getSite();
        InspectionTaskManage inspectionTaskManage = manageList.get(0);
        String taskBo = inspectionTaskManage.getHandle();
        String inspectionItemBo = inspectionTaskManage.getInspectionItemBo();

        //查询检验项目
        List<InspectionTaskManageDetail> inspectionItemDetailList = this.getInspectionTaskDetail(taskBo);
        if (!Constants.INSPECTION_TASK_STATUS_NEW.equals(inspectionTaskManage.getStatus())) {
            inspectionTaskManage.setInspectionTaskDetailList(inspectionItemDetailList);
            return inspectionTaskManage;
        }

        if (inspectionItemDetailList == null || inspectionItemDetailList.size() <= 0) {
            inspectionItemDetailList = this.getInspectionItemDetail(inspectionItemBo);
            if (inspectionItemDetailList == null || inspectionItemDetailList.size() <= 0) {
                return inspectionTaskManage;
            }

            List<InspectionTaskDetail> taskDetailList = new ArrayList<>();
            for (InspectionTaskManageDetail itemDetail : inspectionItemDetailList) {
                InspectionTaskDetail inspectionTaskDetail = new InspectionTaskDetail();
                inspectionTaskDetail.setHandle(UUID.randomUUID().toString());
                inspectionTaskDetail.setSite(site);
                inspectionTaskDetail.setTaskBo(taskBo);
                inspectionTaskDetail.setInspectionItemDetailBo(itemDetail.getHandle());
                taskDetailList.add(inspectionTaskDetail);

                BigDecimal checkNum = itemDetail.getCheckNum();
                if (checkNum.compareTo(BigDecimal.ONE) == 1) {
                    for (int i = 0; i < checkNum.intValue()-1; i++) {
                        InspectionTaskDetail taskDetail = new InspectionTaskDetail();
                        BeanUtils.copyProperties(inspectionTaskDetail, taskDetail);
                        taskDetail.setHandle(UUID.randomUUID().toString());
                        taskDetailList.add(taskDetail);
                    }
                }
            }

            if (taskDetailList != null && taskDetailList.size() > 0) {
                inspectionTaskDetailService.saveBatch(taskDetailList);
            }
            inspectionItemDetailList = this.getInspectionTaskDetail(taskBo);
        }

        inspectionTaskManage.setInspectionTaskDetailList(inspectionItemDetailList);
        return inspectionTaskManage;
    }

    @Override
    public List<InspectionTaskManageDetail> getInspectionItemDetail(String inspectionItemBo) {
        return inspectionTaskManageMapper.selectInspectionItemDetail(inspectionItemBo);
    }

    @Override
    public List<InspectionTaskManageDetail> getInspectionTaskDetail(String inspectionTaskBo) {
        return inspectionTaskManageMapper.selectInspectionTaskDetail(inspectionTaskBo);
    }

    @Override
    public void completeInspectionTask(String site, String user, List<InspectionTaskManageRequest> requestList) {
        if (requestList == null || requestList.size() <= 0) {
            return;
        }

        LocalDateTime dateTime = LocalDateTime.now();
        List<InspectionTask> inspectionTaskList = new ArrayList<>();
        for (InspectionTaskManageRequest request : requestList) {
            String status = request.getStatus();
            String taskNo = request.getTaskNo();
            if (!Constants.INSPECTION_TASK_STATUS_NEW.equals(status)) {
                throw BusinessException.build("任务【" +taskNo+ "】不是新建状态，不允许执行合格操作");
            }

            List<InspectionTaskManageDetail> inspectionItemDetailList = this.getInspectionTaskDetail(HandleEnum.INSPECTION_TASK.getHandle(taskNo));
            if (inspectionItemDetailList != null && inspectionItemDetailList.size() > 0) {
                    throw BusinessException.build("检验任务【"+taskNo+"】有检验项目，不允许执行合格操作");
            }


            //修改数据
            InspectionTask inspectionTask = new InspectionTask();
            inspectionTask.setHandle(request.getHandle());
            inspectionTask.setResult("OK");
            inspectionTask.setStatus(Constants.INSPECTION_TASK_STATUS_COMPLETE);
            inspectionTask.setModifyUser(user);
            inspectionTask.setModifiedDateTime(dateTime);
            inspectionTaskList.add(inspectionTask);
        }


        if (inspectionTaskList != null && inspectionTaskList.size() > 0) {
            inspectionTaskService.updateBatchById(inspectionTaskList);
        }
    }

    @Override
    public void saveInspectionTaskDetail(String site, String user, InspectionTaskManage inspectionTaskManage) {
        LocalDateTime dateTime = LocalDateTime.now();
        String type = inspectionTaskManage.getOperationType();

        List<InspectionTaskManageDetail> taskDetailList = inspectionTaskManage.getInspectionTaskDetailList();
        if (taskDetailList != null && taskDetailList.size() > 0) {
            List<InspectionTaskDetail> inspectionTaskDetailList = new ArrayList<>();

            //修改明细数据
            for (InspectionTaskManageDetail manageDetail : taskDetailList) {
                String isRequired = manageDetail.getIsRequired();
                String paramNo = manageDetail.getParamNo();
                String checkValues = manageDetail.getCheckValues();
                if ("Y".equals(isRequired) && StringUtil.isBlank(checkValues) && "SUBMIT".equals(type)) {
                    throw BusinessException.build("检验项目【" + paramNo + "】值必输!");
                }

                InspectionTaskDetail taskDetail = new InspectionTaskDetail();
                taskDetail.setHandle(manageDetail.getHandle());
                taskDetail.setCheckValues(checkValues);
                taskDetail.setResult(manageDetail.getResult());
                taskDetail.setRemark(manageDetail.getRemark());
                taskDetail.setCheckUser(user);
                taskDetail.setCheckDate(dateTime);
                inspectionTaskDetailList.add(taskDetail);
            }

            if (inspectionTaskDetailList != null && inspectionTaskDetailList.size() > 0) {
                inspectionTaskDetailService.updateBatchById(inspectionTaskDetailList);
            }
        }

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        String result = inspectionTaskManage.getResult();
        String taskNo = inspectionTaskManage.getTaskNo();
        //修改主表数据
        InspectionTask inspectionTaskModel = inspectionTaskService.getInspectionTaskByTaskNo(site, taskNo);
        if (inspectionTaskModel == null) {
            throw BusinessException.build("检验任务【" +taskNo+ "】不存在！");
        }
        String status = inspectionTaskModel.getStatus();
        String category = inspectionTaskModel.getCategory();
        if (!Constants.INSPECTION_TASK_STATUS_NEW.equals(status) && !Constants.INSPECTION_TASK_STATUS_DOING.equals(status)) {
            throw BusinessException.build("检验任务【" +taskNo+ "】不是【新建|检验中】，不允许操作！");
        }

        inspectionTaskModel.setStatus("SAVE".equals(type) ? Constants.INSPECTION_TASK_STATUS_DOING : Constants.INSPECTION_TASK_STATUS_COMPLETE);
        inspectionTaskModel.setResult(result);
        inspectionTaskModel.setComments(inspectionTaskManage.getComments());
        inspectionTaskModel.setModifyUser(user);
        inspectionTaskModel.setModifiedDateTime(dateTime);
        inspectionTaskService.updateById(inspectionTaskModel);

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //如果专检不合格，生产新的检验任务
        /*if (!Constants.INSPECTION_TYPE_P.equals(category) || !"NG".equals(result) || !"SUBMIT".equals(type)) {
            return;
        }

        //任务主表
        InspectionTask newInspectionTask = new InspectionTask();
        BeanUtils.copyProperties(inspectionTaskModel, newInspectionTask);
        String newTaskNo = "P_" + DateUtil.getTimeString();
        String handle = HandleEnum.INSPECTION_TASK.getHandle(site, newTaskNo);
        newInspectionTask.setHandle(handle);
        newInspectionTask.setTaskNo(newTaskNo);
        newInspectionTask.setStatus(Constants.INSPECTION_TASK_STATUS_NEW);
        newInspectionTask.setResult(null);
        newInspectionTask.setComments(null);
        newInspectionTask.setCreatedDateTime(dateTime);
        newInspectionTask.setModifiedDateTime(dateTime);
        inspectionTaskService.save(newInspectionTask);*/
    }
}
