package com.bonus.sgzb.material.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.bonus.sgzb.common.core.constant.TaskTypeConstants;
import com.bonus.sgzb.common.core.enums.TaskStatusEnum;
import com.bonus.sgzb.common.core.enums.TaskTypeEnum;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.common.core.utils.StringHelper;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.material.domain.*;
import com.bonus.sgzb.material.mapper.*;
import com.bonus.sgzb.material.service.IRepairAuditDetailsService;
import com.bonus.sgzb.material.vo.GlobalContants;
import com.bonus.sgzb.material.vo.RepairAuditDetailsVO;
import com.bonus.sgzb.material.vo.ScrapApplyDetailsVO;
import com.bonus.sgzb.material.vo.ScrapAudit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 修试审核详细repair_apply_detailsService业务层处理
 *
 * @author bonus
 * @date 2023-12-16
 */
@Service
public class RepairAuditDetailsServiceImpl implements IRepairAuditDetailsService {
    @Autowired
    private RepairAuditDetailsMapper repairAuditDetailsMapper;

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private TmTaskAgreementMapper agreementMapper;

    @Resource
    private ScrapApplyDetailsMapper scrapApplyDetailsMapper;

    @Resource
    private RepairTestInputMapper repairTestInputMapper;


    /**
     * 查询修试审核详细repair_apply_details
     *
     * @param id 修试审核详细repair_apply_details主键
     * @return 修试审核详细repair_apply_details
     */
    @Override
    public RepairAuditDetails selectRepairAuditDetailsById(Long id) {
        return repairAuditDetailsMapper.selectRepairAuditDetailsById(id);
    }

    /**
     * 查询修试审核详细repair_apply_details列表
     *
     * @param repairAuditDetails 修试审核详细repair_apply_details
     * @return 修试审核详细repair_apply_details
     */
    @Override
    public List<RepairAuditDetails> selectRepairAuditDetailsList(RepairAuditDetails repairAuditDetails) {
        return repairAuditDetailsMapper.selectRepairAuditDetailsList(repairAuditDetails);
    }

    /**
     * 新增修试审核详细repair_apply_details
     *
     * @param repairAuditDetails 修试审核详细repair_apply_details
     * @return 结果
     */
    @Override
    public int insertRepairAuditDetails(RepairAuditDetails repairAuditDetails) {
        repairAuditDetails.setCreateTime(DateUtils.getNowDate());
        return repairAuditDetailsMapper.insertRepairAuditDetails(repairAuditDetails);
    }

    /**
     * 修改修试审核详细repair_apply_details
     *
     * @param repairAuditDetails 修试审核详细repair_apply_details
     * @return 结果
     */
    @Override
    public int updateRepairAuditDetails(RepairAuditDetails repairAuditDetails) {
        repairAuditDetails.setUpdateTime(DateUtils.getNowDate());
        return repairAuditDetailsMapper.updateRepairAuditDetails(repairAuditDetails);
    }

    /**
     * 批量删除修试审核详细repair_apply_details
     *
     * @param ids 需要删除的修试审核详细repair_apply_details主键
     * @return 结果
     */
    @Override
    public int deleteRepairAuditDetailsByIds(Long[] ids) {
        return repairAuditDetailsMapper.deleteRepairAuditDetailsByIds(ids);
    }

    /**
     * 删除修试审核详细repair_apply_details信息
     *
     * @param id 修试审核详细repair_apply_details主键
     * @return 结果
     */
    @Override
    public int deleteRepairAuditDetailsById(Long id) {
        return repairAuditDetailsMapper.deleteRepairAuditDetailsById(id);
    }

    /**
     * 查询试验审核列表
     *
     * @param repairAuditDetails
     * @return
     */
    @Override
    public List<ScrapApplyDetailsVO> selectRepairQuestList(RepairAuditDetails repairAuditDetails) {
        List<ScrapApplyDetailsVO> repairQuestList = repairAuditDetailsMapper.selectRepairQuestList(repairAuditDetails);
        for (ScrapApplyDetailsVO scrapApplyDetailsVO : repairQuestList) {
            Long taskId = scrapApplyDetailsVO.getTaskId();
            String typeName = repairAuditDetailsMapper.selectTypeNameByTaskId(taskId);
            scrapApplyDetailsVO.setItemType(typeName);
        }
        return repairQuestList;
    }

    @Override
    public List<RepairAuditDetailsVO> exportRepairQuestList(RepairAuditDetails bean) {
        return repairAuditDetailsMapper.exportRepairQuestList(bean);
    }

    @Override
    public List<RepairRecord> getRepairRecord(RepairAuditDetails repairAuditDetails) {
        RepairAuditDetails bean = repairAuditDetailsMapper.getRepairId(repairAuditDetails);
        List<RepairRecord> list = repairAuditDetailsMapper.getRepairRecord(bean);
        return list;
    }

    @Override
    public List<RepairPart> getPartRecord(RepairAuditDetails repairAuditDetails) {
        RepairAuditDetails bean = repairAuditDetailsMapper.getRepairId(repairAuditDetails);
        List<RepairPart> list = repairAuditDetailsMapper.getPartRecord(bean);
        return list;
    }

    /**
     * @param repairAuditDetails
     * @return
     */
    @Override
    public List<RepairAuditDetails> getRepairAuditList(RepairAuditDetails repairAuditDetails) {
        List<RepairAuditDetails> repairAuditDetailsList = repairAuditDetailsMapper.selectRepairAuditDetailsList(repairAuditDetails);
        return repairAuditDetailsList;
    }

    /**
     * 修饰审核任务审核
     *
     * @param scrapAudit 审核信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditRepair(ScrapAudit scrapAudit) throws Exception {
        String checkResult = scrapAudit.getCheckResult();
        List<RepairAuditDetails> auditDetailList = scrapAudit.getAuditDetailList();
        List<Long> taskIdList = scrapAudit.getTaskIdList();
        Integer b = 0;
        for (Long taskId : taskIdList) {
            String status = "0";
            TmTask task1 = taskMapper.selectTmTaskByTaskId(taskId);
            if (task1.getTaskStatus() == 47) {
                throw new Exception("任务已审核已通过");
            }

            List<RepairAuditDetails> auditAllList = repairAuditDetailsMapper.selectRepairAuditDetailsByTaskId(taskId);
            List<RepairAuditDetails> notAuditList = repairAuditDetailsMapper.selectnotAuditByTaskId(taskId);
            // 查询协议表
            TmTaskAgreement tmTaskAgreement = agreementMapper.selectTmTaskAgreementByTaskId(taskId);
            String taskCode = "";
            int taskStatus = 0;
            int taskType = 0;
            int companyId = 0;
            if ("通过".equals(checkResult)) {
                status = "1";
                List<RepairAuditDetails> repairInputList = new ArrayList<>();
                List<RepairAuditDetails> scrapNumList = new ArrayList<>();
                if (auditDetailList != null && auditDetailList.size() > 0) {
                    for (RepairAuditDetails bean : auditDetailList) {
                        if (bean.getRepairedNum().compareTo(b) > 0) {
                            repairInputList.add(bean);
                        }
                        if (bean.getScrapNum().compareTo(b) > 0) {
                            scrapNumList.add(bean);
                        }
                    }
                } else {
                    repairInputList = repairAuditDetailsMapper.selectRepairInputByTaskId(taskId);
                    //获取维修报废列表
                    scrapNumList = repairAuditDetailsMapper.selectScrapNumByTaskId(taskId);
                }

                if (repairInputList != null && repairInputList.size() > 0) {
                    if (repairInputList.get(0).getCompanyId() != null) {
                        companyId = repairInputList.get(0).getCompanyId();
                    }

                    taskCode = purchaseCodeRule("R", 50);
                    taskStatus = 53;
                    taskType = 50;
                    long inputTaskId = genTask(taskCode, taskType, taskStatus, tmTaskAgreement, companyId);
                    for (RepairAuditDetails inputDetails : repairInputList) {
                        Long typeId = inputDetails.getTypeId();
                        Long maId = inputDetails.getMaId();
                        Integer repairNum = inputDetails.getRepairedNum();
                        // 创建修饰后入库任务
                        if (repairNum.compareTo(b) > 0) {
                            // 添加修试后入库任务
                            RepairInputDetails repairInputDetails = new RepairInputDetails();
                            repairInputDetails.setTaskId(inputTaskId);
                            repairInputDetails.setAuditId(inputDetails.getId());
                            repairInputDetails.setRepairId(inputDetails.getRepairId());
                            repairInputDetails.setRepairNum(inputDetails.getRepairedNum());
                            repairInputDetails.setTypeId(inputDetails.getTypeId());
                            repairInputDetails.setMaId(inputDetails.getMaId());
                            repairInputDetails.setStatus("0");
                            repairInputDetails.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                            repairInputDetails.setCreateTime(new Date());
                            repairInputDetails.setCompanyId((long) companyId);
                            repairTestInputMapper.insertRepairInputDetails(repairInputDetails);
                        }
                        repairAuditDetailsMapper.updateRepairCost(inputDetails,status);
                        // 根据repairId找到taskId和 typeId 、maid
                        List<String> repairApplyRecordId = repairAuditDetailsMapper.getRepairApplyRecordId(inputDetails.getRepairId());
                        // 再去repair_apply_record 中查，并给一个标识表示审核完成
                        for (String id : repairApplyRecordId) {
                            repairAuditDetailsMapper.updateRecodeStatus(id);
                        }
                    }
                }
                if (scrapNumList != null && scrapNumList.size() > 0) {
                    if (scrapNumList.get(0).getCompanyId() != null) {
                        companyId = scrapNumList.get(0).getCompanyId();
                    }
                    taskCode = purchaseCodeRule(TaskTypeConstants.BF, TaskTypeEnum.SCRAP_TASK.getCode());
                    /*taskStatus = 58;
                    taskType = 57;*/
                    //创建报废任务
                    long scrapTaskId = genTask(taskCode, TaskTypeEnum.SCRAP_TASK.getCode(), Integer.parseInt(TaskStatusEnum.SCRAP_UNDER_REVIEW.getCode()), tmTaskAgreement, companyId);
                    for (RepairAuditDetails scrapDetails : scrapNumList) {
                        RepairAuditDetails byRepairId = scrapApplyDetailsMapper.getByRepairId(String.valueOf(scrapDetails.getRepairId()));
                        List<RepairRecord> repairRecord = scrapApplyDetailsMapper.getGyoupRepairRecord(byRepairId);
                        Long typeId = scrapDetails.getTypeId();
                        Long maId = scrapDetails.getMaId();
                        // 创建报废任务
                        Integer scrapNum = scrapDetails.getScrapNum();
                        if (scrapNum.compareTo(b) > 0) {
                            for (RepairRecord bean : repairRecord){
                                ScrapApplyDetails scrapApplyDetails = new ScrapApplyDetails();
                                scrapApplyDetails.setTaskId(scrapTaskId);
                                scrapApplyDetails.setTypeId(typeId);
                                scrapApplyDetails.setMaId(maId);
                                scrapApplyDetails.setScrapNum(bean.getScrapNum());
                                scrapApplyDetails.setScrapType(bean.getScrapType());
                                scrapApplyDetails.setScrapSource("2");
                                scrapApplyDetails.setStatus("0");
                                scrapApplyDetails.setParentId(scrapDetails.getId());
                                scrapApplyDetails.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                                scrapApplyDetails.setCreateTime(new Date());
                                scrapApplyDetails.setCompanyId((long) companyId);
                                scrapApplyDetailsMapper.insertScrapApplyDetails(scrapApplyDetails);
                            }
                        }
                    }

                }
                // 修饰审核通过时改修任务为已通过审核
                if (auditDetailList != null) {
                    if (auditDetailList.size() == notAuditList.size()) {
                        task1.setTaskStatus(47);
                    }
                } else if (auditAllList != null) {
                    if (auditAllList.size() == notAuditList.size()) {
                        task1.setTaskStatus(47);
                    }
                }
                task1.setUpdateTime(new Date());
                task1.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                taskMapper.updateTmTask(task1);
            } else {
                status = "2";
                List<RepairAuditDetails> repairDetailList = new ArrayList<>();
                if (auditDetailList != null && auditDetailList.size() > 0) {
                    repairDetailList.addAll(auditDetailList);
                } else {
                    repairDetailList.addAll(auditAllList);
                }
                if (repairDetailList.size() > 0) {
                    if (repairDetailList.get(0).getCompanyId() != null) {
                        companyId = repairDetailList.get(0).getCompanyId();
                    }
                    taskCode = purchaseCodeRule("WX", 41);
                    taskStatus = 43;
                    taskType = 41;
                    long inputTaskId = genTask(taskCode, taskType, taskStatus, tmTaskAgreement, companyId);
                    for (RepairAuditDetails inputDetails : repairDetailList) {
                        Long backId = repairAuditDetailsMapper.getBackId(inputDetails.getRepairId());
                       /* 添加驳回后维修详细表数据*/
                        RepairTaskDetails repairTaskDetails = new RepairTaskDetails();
                        repairTaskDetails.setTaskId(String.valueOf(inputTaskId));
                        repairTaskDetails.setMaId(inputDetails.getMaId());
                        repairTaskDetails.setTypeId(inputDetails.getTypeId());
                        Integer repairNum = inputDetails.getRepairNum();
                        repairTaskDetails.setRepairNum(repairNum);
                        repairTaskDetails.setStatus("0");
                        repairTaskDetails.setCreateBy(SecurityUtils.getLoginUser().getUserid());
                        repairTaskDetails.setCompanyId((long) companyId);
                        repairTaskDetails.setBackId(backId);
                        repairAuditDetailsMapper.insertRepairDetails(repairTaskDetails);

                        repairAuditDetailsMapper.updateRepairCost(inputDetails,status);
                    }
                }
                // 修饰审核任务不通过时
                TmTask tmTask = new TmTask();
                tmTask.setTaskId(taskId);
                tmTask.setRemark(scrapAudit.getRemark());
                if (repairDetailList.size() == notAuditList.size()) {
                    tmTask.setTaskStatus(48);
                }
                tmTask.setUpdateTime(new Date());
                tmTask.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                taskMapper.updateTmTask(tmTask);
            }
            if (scrapAudit.getAuditDetailList() != null && scrapAudit.getAuditDetailList().size() > 0) {
                if (auditDetailList != null) {
                    for (RepairAuditDetails bean : auditDetailList) {
                        bean.setAuditBy(SecurityUtils.getLoginUser().getUserid());
                        bean.setStatus(status);
                        bean.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                        bean.setAuditRemark(scrapAudit.getRemark());
                        repairAuditDetailsMapper.updateStatus(bean);
                    }
                }
            } else {
                if (auditAllList != null) {
                    for (RepairAuditDetails bean : auditAllList) {
                        bean.setAuditBy(SecurityUtils.getLoginUser().getUserid());
                        bean.setStatus(status);
                        bean.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                        bean.setAuditRemark(scrapAudit.getRemark());
                        repairAuditDetailsMapper.updateStatus(bean);
                    }
                }
            }
        }
        return 1;
    }

    private long genTask(String taskCode, int taskType, int taskStatus, TmTaskAgreement tmTaskAgreement, int companyId) {
        TmTask task = new TmTask();
        task.setCode(taskCode);
        task.setTaskStatus(taskStatus);
        task.setTaskType(taskType);
        task.setCompanyId(companyId);
        task.setCreateTime(new Date());
        task.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
        taskMapper.insertTmTask(task);
        // 添加协议信息表
        TmTaskAgreement taskAgreement = new TmTaskAgreement();
        long taskId = task.getTaskId();
        taskAgreement.setTaskId(taskId);
        if (tmTaskAgreement.getAgreementId() == null) {
            throw new ServiceException("缺少协议数据");
        } else {
            taskAgreement.setAgreementId(tmTaskAgreement.getAgreementId());
        }
        taskAgreement.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
        agreementMapper.insertTmTaskAgreement(taskAgreement);
        return taskId;
    }


    /**采购单号编码生成规则*/
    private String purchaseCodeRule(String code, Integer taskType) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String taskNum = taskMapper.selectTaskNumByMonths(nowDate, taskType);
        if (StringHelper.isNotEmpty(taskNum)){
            // 将字符串转换为整数
            int num = Integer.parseInt(taskNum);
            // 执行加一操作
            num++;
            // 将结果转换回字符串格式，并确保结果是四位数，不足四位则在前面补0
            taskNum = String.format("%04d", num);
        }else {
            taskNum = "0001";
        }
        String codeNum = code + format + "-" + taskNum;
        return codeNum;
    }
}
