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 java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.bonus.sgzb.app.mapper.BackReceiveMapper;
import com.bonus.sgzb.app.service.BackReceiveService;
import com.bonus.sgzb.base.api.domain.BackApplyInfo;
import com.bonus.sgzb.common.core.constant.TaskTypeConstants;
import com.bonus.sgzb.common.core.enums.ReviewStatusEnum;
import com.bonus.sgzb.common.core.enums.ScrapSourceEnum;
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.exception.ExceptionDict;
import com.bonus.sgzb.material.mapper.*;
import com.bonus.sgzb.material.service.IScrapApplyDetailsService;
import com.bonus.sgzb.material.vo.ForecastWasteExcel;
import com.bonus.sgzb.material.vo.ScrapApplyDetailsVO;
import com.bonus.sgzb.material.vo.ScrapAudit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 报废任务详细scrap_apply_detailsService业务层处理
 *
 * @author bonus
 * @date 2023-12-15
 */
@Service
@Slf4j
public class ScrapApplyDetailsServiceImpl implements IScrapApplyDetailsService {
    @Resource
    private ScrapApplyDetailsMapper scrapApplyDetailsMapper;

    @Resource
    private PurchaseCheckInfoMapper purchaseCheckInfoMapper;

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private TmTaskAgreementMapper agreementMapper;

    @Resource
    private ScrapAuditorSetMapper scrapAuditorSetMapper;

    @Resource
    BackReceiveService backReceiveService;

    /**
     * 查询报废任务详细scrap_apply_details
     *
     * @param id 报废任务详细scrap_apply_details主键
     * @return 报废任务详细scrap_apply_details
     */
    @Override
    public ScrapApplyDetails selectScrapApplyDetailsById(Long id) {
        return scrapApplyDetailsMapper.selectScrapApplyDetailsById(id);
    }

    @Override
    public List<ScrapApplyDetailsVO> exportScrapApplyDetailsList(ScrapApplyDetails bean) {
        return scrapApplyDetailsMapper.exportScrapApplyDetailsList(bean);
    }

    @Override
    public List<RepairRecord> getScrapRecord(ScrapApplyDetails scrapApplyDetails) {
        String repairId = scrapApplyDetailsMapper.getRepairId(scrapApplyDetails);
        RepairAuditDetails bean = scrapApplyDetailsMapper.getByRepairId(repairId);
        List<RepairRecord> list = scrapApplyDetailsMapper.getRepairRecord(bean);
        return list;
    }

    @Override
    public List<String> getFileUrl(String fileIds) {
        List<String> fileUrlList = new ArrayList<>();
        if (fileIds != null && !fileIds.isEmpty()) {
            for (String s : fileIds.split(",")) {
                String url = scrapApplyDetailsMapper.getFileUrl(s);
                fileUrlList.add(url);
            }
        }
        return fileUrlList;
    }

    /**
     * 查询预报废申请列表
     * @param scrapApplyDetails 包含预报废申请详情的实体对象，用于筛选申请列表的条件。
     * @return
     */
    @Override
    public List<ScrapApplyDetailsVO> getScrapApplyList(ScrapApplyDetails scrapApplyDetails) {
        List<ScrapApplyDetailsVO> scrapApplyDetailsList = scrapApplyDetailsMapper.getScrapApplyList(scrapApplyDetails);
        for (ScrapApplyDetailsVO applyDetails : scrapApplyDetailsList) {
            Long taskId = applyDetails.getTaskId();
            String typeName = scrapApplyDetailsMapper.selectTypeNameByTaskId(taskId);
            applyDetails.setItemType(typeName);
        }
        return scrapApplyDetailsList;
    }

    /**
     * 预报废任务审核
     * @param scrapAudit
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int forecastWasteAudit(ScrapAudit scrapAudit) {
        log.info("ScrapApplyDetailsServiceImpl forecastWasteAudit  begin: {}", scrapAudit);
        //获取任务id
        Long taskId = scrapAudit.getTaskId();
        if (taskId == null) {
            throw new ServiceException(ExceptionDict.TASK_ID_IS_EMPTY_MSG, ExceptionDict.TASK_ID_IS_EMPTY);
        }
        //获取审核列表
        List<ScrapApplyDetails> scrapApplyDetailList = scrapAudit.getScrapDetailList();
        if (scrapApplyDetailList == null || scrapApplyDetailList.size() == 0) {
            throw new ServiceException(String.format(ExceptionDict.PARAM_IS_NULL_ERROR_MSG,"scrapDetailList"), ExceptionDict.PARAM_IS_NULL_ERROR);
        }
        //修改装备状态
        for (ScrapApplyDetails scrapApplyDetails: scrapApplyDetailList){
            scrapApplyDetails.setAuditTime(new Date());
            scrapApplyDetails.setUpdateTime(DateUtils.getNowDate());
            scrapApplyDetailsMapper.updateScrapApplyDetails(scrapApplyDetails);
        }
        //根据任务id查看是否还有未审核的设备
        List<ScrapApplyDetails> getScrapApplyDetailList = scrapApplyDetailsMapper.selectScrapDetailsByTaskId(taskId);
        if (scrapApplyDetailList.size()==0){
            return BigDecimal.ROUND_UP;
        }
        //获取所有装备的状态
        List<String> statusList = getScrapApplyDetailList.stream().map(ScrapApplyDetails::getStatus).collect(Collectors.toList());
        TmTask task = new TmTask();
        task.setTaskId(taskId);
        //判断是否还有装备没有进行审核
        if (statusList.contains(ReviewStatusEnum.IN_PROGRESS.getCode())){
            task.setTaskStatus(Integer.valueOf(TaskStatusEnum.UNDER_REVIEW.getCode()));
            //当全部审核以后判断是否有被驳回的装备
        } else if (!statusList.contains(ReviewStatusEnum.IN_PROGRESS.getCode()) &&statusList.contains(ReviewStatusEnum.REJECTED.getCode())) {
            task.setTaskStatus(Integer.valueOf(TaskStatusEnum.REJECTED.getCode()));
            //TODO 对审核驳回的单子进行处理的业务待确认
        }else {
            task.setTaskStatus(Integer.valueOf(TaskStatusEnum.PASSED.getCode()));
            //生成报废的单子
            createScrapTask(taskId);
        }
        //修改任务状态
        taskMapper.updateTmTask(task);
        log.info("ScrapApplyDetailsServiceImpl forecastWasteAudit  end: {}", scrapAudit);
        return BigDecimal.ROUND_DOWN;
    }

    /**
     * 提交报废任务
     * @param scrapAudit 包含废弃任务审计信息的对象。
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int submitScrapTask(ScrapAudit scrapAudit) {
        log.info("ScrapApplyDetailsServiceImpl submitScrapTask  begin: {}", scrapAudit);
        //参数校验  后期可以考虑写一个校验的工具类
        List<Integer> deptIds = scrapAudit.getDeptIds();
        if (deptIds == null || deptIds.size() == 0) {
            throw new ServiceException(String.format(ExceptionDict.PARAM_IS_NULL_ERROR_MSG,"deptIds"), ExceptionDict.PARAM_IS_NULL_ERROR);
        }
        List<Long> taskIdList =scrapAudit.getTaskIdList();
        if (taskIdList == null || taskIdList.size() == 0) {
            throw new ServiceException(ExceptionDict.TASK_ID_IS_EMPTY_MSG, ExceptionDict.TASK_ID_IS_EMPTY);
        }
        for (Long taskId : taskIdList) {
            //修任务状态
            TmTask task = new TmTask();
            task.setTaskId(taskId);
            task.setTaskStatus(Integer.valueOf(TaskStatusEnum.SCRAP_UNDER_REVIEW.getCode()));
            taskMapper.updateTmTask(task);
            //创建审核详情
            ScrapAuditorSet scrapAuditorSet = new ScrapAuditorSet();
            scrapAuditorSet.setTaskId(taskId.intValue());
            for (Integer deptId : deptIds) {
                scrapAuditorSet.setDeptId(deptId);
                scrapAuditorSet.setTaskId(taskId.intValue());
                scrapAuditorSetMapper.insertScrapAuditorSet(scrapAuditorSet);
            }
        }
        log.info("ScrapApplyDetailsServiceImpl submitScrapTask  end" );
        return BigDecimal.ROUND_DOWN;
    }

    /**
     * 报废任务审核--宁夏
     * @param scrapAuditorSet
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int scrapTaskReview(ScrapAuditorSet scrapAuditorSet) {
        log.info("ScrapApplyDetailsServiceImpl scrapTaskReview  begin: {}", scrapAuditorSet);
        try {
            scrapAuditorSet.setAuditTime(new Date());
            //修改审核状态
            scrapAuditorSetMapper.updateStatus(scrapAuditorSet);
            //获取报废任务所有审核人员的审核详情
            List<ScrapAuditorSet> scrapAuditorSetList = scrapAuditorSetMapper.selectScrapAuditListByTaskId(Long.valueOf(scrapAuditorSet.getTaskId()));
            //获取所有的审核状态
            List<String> statusList = scrapAuditorSetList.stream().map(ScrapAuditorSet::getStatus).collect(Collectors.toList());
            TmTask task = new TmTask();
            task.setTaskId(Long.valueOf(scrapAuditorSet.getTaskId()));
            //判断是否还有部门没有进行审核
            if (statusList.contains(ReviewStatusEnum.IN_PROGRESS.getCode())){
                task.setTaskStatus(Integer.valueOf(TaskStatusEnum.SCRAP_UNDER_REVIEW.getCode()));
                //当全部审核以后判断是否有驳回的
            } else if (!statusList.contains(ReviewStatusEnum.IN_PROGRESS.getCode()) &&statusList.contains(ReviewStatusEnum.REJECTED.getCode())) {
                task.setTaskStatus(Integer.valueOf(TaskStatusEnum.SCRAP_REJECTED.getCode()));
            }else {
                task.setTaskStatus(Integer.valueOf(TaskStatusEnum.SCRAP_PASSED.getCode()));
                task.setDisposition(Integer.valueOf(TaskStatusEnum.NOT_DISPOSED.getCode()));
            }
            //修改任务状态
            taskMapper.updateTmTask(task);
            log.info("ScrapApplyDetailsServiceImpl scrapTaskReview  end");
        } catch (Exception e) {
            log.error("Error occurred during scrap task review: {}", e.getMessage());
            throw new ServiceException(ExceptionDict.ERROR_OCCURRED_DURING_SCRAP_TASK_REVIEW_MSG, ExceptionDict.ERROR_OCCURRED_DURING_SCRAP_TASK_REVIEW);
        }
        return BigDecimal.ROUND_DOWN;
    }

    /**
     * 报废任务审核列表
     * @param scrapApplyDetails
     * @return
     */
    @Override
    public List<ScrapApplyDetailsVO> scrapTaskReviewList(ScrapApplyDetails scrapApplyDetails) {
        log.info("ScrapApplyDetailsServiceImpl scrapTaskReviewList  begin:{}",scrapApplyDetails);
        List<ScrapApplyDetailsVO> scrapApplyDetailsList = scrapApplyDetailsMapper.scrapTaskReviewList(scrapApplyDetails);
        for (ScrapApplyDetailsVO applyDetails : scrapApplyDetailsList) {
            Long taskId = applyDetails.getTaskId();
            String typeName = scrapApplyDetailsMapper.selectTypeNameByTaskId(taskId);
            applyDetails.setItemType(typeName);
            List<ScrapAuditorSet> scrapAuditorSetList = scrapAuditorSetMapper.selectScrapAuditListByTaskId(taskId);
            applyDetails.setScrapAuditorSetList(scrapAuditorSetList);
        }
        log.info("ScrapApplyDetailsServiceImpl scrapTaskReviewList  end:{}",scrapApplyDetails);
        return scrapApplyDetailsList;
    }

    /**
     * 获取处置列表----宁夏
     * @param scrapApplyDetails
     * @return
     */
    @Override
    public List<ScrapApplyDetailsVO> obtainDisposalList(ScrapApplyDetails scrapApplyDetails) {
        List<ScrapApplyDetailsVO> tmTaskList = taskMapper.selectTmTaskListByDisposition(scrapApplyDetails);
        for (ScrapApplyDetailsVO applyDetails : tmTaskList) {
            Long taskId = applyDetails.getTaskId();
            String typeName = scrapApplyDetailsMapper.selectTypeNameByTaskId(taskId);
            applyDetails.setItemType(typeName);
            List<ScrapAuditorSet> scrapAuditorSetList = scrapAuditorSetMapper.selectScrapAuditListByTaskId(taskId);
            applyDetails.setScrapAuditorSetList(scrapAuditorSetList);
        }
        return tmTaskList;
    }

    /**
     * 处置
     * @param tmTaskList
     * @return
     */
    @Override
    public int obtainDisposal(List<TmTask> tmTaskList) {
        log.info("ScrapApplyDetailsServiceImpl scrapTaskReviewList  begin:{}",tmTaskList);
        tmTaskList.forEach(tmTask -> {
            taskMapper.updateTmTask(tmTask);
        });
        log.info("ScrapApplyDetailsServiceImpl scrapTaskReviewList  end:{}",tmTaskList);
        return BigDecimal.ROUND_DOWN;
    }

    /**
     * 导出预报废
     * @param scrapApplyDetails
     * @return
     */
    @Override
    public List<ForecastWasteExcel> exportForecastWaste(ScrapApplyDetails scrapApplyDetails) {
        List<ScrapApplyDetailsVO> scrapApplyDetailsList = this.getScrapApplyList(scrapApplyDetails);
        List<ForecastWasteExcel> ForecastWasteExcelList = new ArrayList<>();
        ForecastWasteExcel forecastWasteExcel = new ForecastWasteExcel();
        //对预报废来源进行处理
        for (ScrapApplyDetailsVO scrapApplyDetailsVO: scrapApplyDetailsList) {
            BeanUtils.copyProperties(scrapApplyDetailsVO,forecastWasteExcel);
            //获取来源单号
            forecastWasteExcel.setRepairNum(scrapApplyDetailsVO.getRepairNum()!=null?scrapApplyDetailsVO.getRepairNum(): scrapApplyDetailsVO.getRepairCode());
            //获取来源名称
            forecastWasteExcel.setScrapSourceName(ScrapSourceEnum.getInfoByCode(scrapApplyDetailsVO.getScrapSource()));
            ForecastWasteExcelList.add(forecastWasteExcel);
        }
        return ForecastWasteExcelList;
    }

    /**
     * 生成报废任务
     * @param taskId
     */
    private void createScrapTask(Long taskId) {
        TmTask task = taskMapper.selectTmTaskByTaskId(taskId);
        if (task == null) {
            throw new ServiceException(ExceptionDict.TASK_IS_EMPTY_MSG, ExceptionDict.TASK_IS_EMPTY);
        }
        // 查询协议表
        TmTaskAgreement tmTaskAgreement = agreementMapper.selectTmTaskAgreementByTaskId(taskId);
        //生成编号
        String taskCode = purchaseCodeRule(TaskTypeConstants.BF,  Integer.valueOf(TaskTypeEnum.SCRAP_TASK.getCode()));
        Integer taskStatus = Integer.valueOf(TaskStatusEnum.SCRAP_UNSUBMITTED.getCode());
        Integer taskType = Integer.valueOf(TaskTypeEnum.SCRAP_TASK.getCode());
        //获取该任务下通过预报废审核的装备信息
        ScrapApplyDetails scrapApplyDetails = new ScrapApplyDetails();
        scrapApplyDetails.setTaskId(taskId);
        scrapApplyDetails.setStatus(ReviewStatusEnum.PASSED.getCode());
        List<ScrapApplyDetails> scrapApplyDetailsList = scrapApplyDetailsMapper.selectScrapAuditList(scrapApplyDetails);
        if (scrapApplyDetailsList.size() == 0){
            throw new ServiceException(ExceptionDict.TASK_DETAILS_IS_EMPTY_MSG, ExceptionDict.TASK_DETAILS_IS_EMPTY);
        }
        //获取生成的任务id
        int companyId = task.getCompanyId() == null ? 0 : task.getCompanyId();
        long backTaskId = genTask(taskCode, taskType, taskStatus, tmTaskAgreement, companyId);
        //保存装备详情
        processScrapApplyDetails( scrapApplyDetailsList,  backTaskId);

    }

    /**
     * 保存报废任务详细scrap_apply_details
     *
     * @param scrapApplyDetailsList 报废任务详细scrap_apply_details
     * @param backTaskId            报废任务id
     */
    public void processScrapApplyDetails(List<ScrapApplyDetails> scrapApplyDetailsList, Long backTaskId) {
        ScrapApplyDetails scrapApplyDetails = new ScrapApplyDetails();
        for (ScrapApplyDetails scrapApplyDetail:scrapApplyDetailsList) {
            BeanUtil.copyProperties(scrapApplyDetail, scrapApplyDetails);
            scrapApplyDetails.setStatus(ReviewStatusEnum.IN_PROGRESS.getCode());
            scrapApplyDetails.setId(null);
            scrapApplyDetails.setAuditBy(null);
            scrapApplyDetails.setAuditTime(null);
            scrapApplyDetails.setAuditRemark(null);
            scrapApplyDetails.setTaskId(backTaskId);
            scrapApplyDetails.setParentId(scrapApplyDetail.getId());
            scrapApplyDetailsMapper.insertScrapApplyDetails(scrapApplyDetails);
        }
    }

    /**
     * 查询报废任务详细scrap_apply_details列表
     *
     * @param scrapApplyDetails 报废任务详细scrap_apply_details
     * @return 报废任务详细scrap_apply_details
     */
    @Override
    public List<ScrapApplyDetailsVO> selectScrapApplyDetailsList(ScrapApplyDetails scrapApplyDetails) {
        List<ScrapApplyDetailsVO> scrapApplyDetailsList = scrapApplyDetailsMapper.selectScrapApplyDetailsList(scrapApplyDetails);
        for (ScrapApplyDetailsVO applyDetails : scrapApplyDetailsList) {
            Long taskId = applyDetails.getTaskId();
            String typeName = scrapApplyDetailsMapper.selectTypeNameByTaskId(taskId);
            applyDetails.setItemType(typeName);
            List<ScrapAuditorSet> scrapAuditorSetList = scrapAuditorSetMapper.selectScrapAuditListByTaskId(taskId);
            applyDetails.setScrapAuditorSetList(scrapAuditorSetList);
        }
        return scrapApplyDetailsList;
    }

    /**
     * 新增报废任务详细scrap_apply_details
     *
     * @param scrapApplyDetails 报废任务详细scrap_apply_details
     * @return 结果
     */
    @Override
    public int insertScrapApplyDetails(ScrapApplyDetails scrapApplyDetails) {
        scrapApplyDetails.setCreateTime(DateUtils.getNowDate());
        return scrapApplyDetailsMapper.insertScrapApplyDetails(scrapApplyDetails);
    }

    /**
     * 修改报废任务详细scrap_apply_details
     *
     * @param scrapApplyDetails 报废任务详细scrap_apply_details
     * @return 结果
     */
    @Override
    public int updateScrapApplyDetails(ScrapApplyDetails scrapApplyDetails) {
        scrapApplyDetails.setUpdateTime(DateUtils.getNowDate());
        return scrapApplyDetailsMapper.updateScrapApplyDetails(scrapApplyDetails);
    }

    /**
     * 批量删除报废任务详细scrap_apply_details
     *
     * @param ids 需要删除的报废任务详细scrap_apply_details主键
     * @return 结果
     */
    @Override
    public int deleteScrapApplyDetailsByIds(Long[] ids) {
        return scrapApplyDetailsMapper.deleteScrapApplyDetailsByIds(ids);
    }

    /**
     * 删除报废任务详细scrap_apply_details信息
     *
     * @param id 报废任务详细scrap_apply_details主键
     * @return 结果
     */
    @Override
    public int deleteScrapApplyDetailsById(Long id) {
        return scrapApplyDetailsMapper.deleteScrapApplyDetailsById(id);
    }

    /**
     * 查看按钮,查询报废任务详细列表
     *
     * @param scrapApplyDetails
     * @return
     */
    @Override
    public List<ScrapApplyDetails> getScrapAuditList(ScrapApplyDetails scrapApplyDetails) {
        return scrapApplyDetailsMapper.selectScrapAuditList(scrapApplyDetails);
    }

    /**
     * 报废任务审核
     *
     * @param scrapAudit 审核信息列表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditScrap(ScrapAudit scrapAudit) throws Exception {
        String checkResult = scrapAudit.getCheckResult();
        //获取报废来源数据
        List<ScrapApplyDetails> scrapDetailList = scrapAudit.getScrapDetailList();
        List<Long> taskIdList = scrapAudit.getTaskIdList();
        for (Long taskId : taskIdList) {
            String status = "0";
            TmTask task1 = taskMapper.selectTmTaskByTaskId(taskId);
            // 查询协议表
            TmTaskAgreement tmTaskAgreement = agreementMapper.selectTmTaskAgreementByTaskId(taskId);
            //获取未审核的数据
            List<ScrapApplyDetails> notScrapList = scrapApplyDetailsMapper.selectnotScrapByTaskId(taskId);
            //获取全部数据
            List<ScrapApplyDetails> scrapAllApplyDetails = scrapApplyDetailsMapper.selectScrapDetailsByTaskId(taskId);

            if (task1.getTaskStatus() == 47) {
                throw new Exception("报废审核已通过");
            }
            TmTask task = new TmTask();
            task.setTaskId(taskId);
            List<ScrapApplyDetails> scrapApplyDetailsList;
            if (scrapDetailList != null && scrapDetailList.size() > 0) {
                scrapApplyDetailsList = new ArrayList<>(scrapDetailList);
            } else {
                scrapApplyDetailsList = new ArrayList<>(scrapAllApplyDetails);
            }
            String taskCode = "";
            int taskStatus = 0;
            int taskType = 0;
            int companyId = 0;
            int parentId = 0;
            if ("通过".equals(checkResult)) {
                status = "1";
                if (scrapApplyDetailsList.size() > 0) {
                    for (ScrapApplyDetails scrapApplyDetails : scrapApplyDetailsList) {
                        Long maId = scrapApplyDetails.getMaId();
                        if (maId != null && maId > 0) {
                            scrapApplyDetailsMapper.updateMachine(maId);
                        }
                    }
                }
                if (notScrapList.size() == scrapApplyDetailsList.size()) {
                    task.setTaskStatus(59);
                }
            } else {
                status = "2";
                List<ScrapApplyDetails> backList = new ArrayList<>();
                List<ScrapApplyDetails> repairList = new ArrayList<>();
                List<BackApplyInfo> wxList = new ArrayList<>();
                if (scrapApplyDetailsList.size() > 0) {
                    for (ScrapApplyDetails bean : scrapApplyDetailsList) {
                        if ("1".equals(bean.getScrapSource())) {
                            backList.add(bean);
                        } else if ("2".equals(bean.getScrapSource())) {
                            repairList.add(bean);
                        }
                        BackApplyInfo backApplyInfo = new BackApplyInfo();
                        backApplyInfo.setAgreementId(tmTaskAgreement.getAgreementId().intValue());
                        backApplyInfo.setMaId(Objects.isNull(bean.getMaId()) ? 0 : bean.getMaId().intValue());
                        backApplyInfo.setTypeId(String.valueOf(bean.getTypeId()));
                        backApplyInfo.setCompanyId(String.valueOf(bean.getCompanyId()));
                        backApplyInfo.setBackNum(bean.getScrapNum().intValue());
                        backApplyInfo.setId(bean.getParentId());
                        backApplyInfo.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                        backApplyInfo.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                        wxList.add(backApplyInfo);
                    }
                }

                //维修的创建维修任务，插入任务协议表
                if (wxList != null && wxList.size() > 0) {
                    //插入任务表tm_task
                    int newTaskId = backReceiveService.insertTt(wxList, TaskTypeEnum.MAINTENANCE_TASK.getCode(), SecurityUtils.getLoginUser().getUsername());
                    //插入协议任务表tm_task_agreement
                    backReceiveService.insertTta(newTaskId, wxList);
                    //插入维修记录表repair_apply_details
                    backReceiveService.insertRad(newTaskId, wxList);
                }

                if (repairList.size() > 0) {
                    if (repairList.get(0).getCompanyId() != null) {
                        companyId = Math.toIntExact(repairList.get(0).getCompanyId());
                    }
                    taskCode = purchaseCodeRule("WX", 45);
                    taskStatus = 46;
                    taskType = 45;
                    long repairTaskId = genTask(taskCode, taskType, taskStatus, tmTaskAgreement, companyId);
                    for (ScrapApplyDetails bean : repairList) {
                        RepairAuditDetails details = scrapApplyDetailsMapper.getRepairAudit(bean.getParentId());
                        details.setTaskId(repairTaskId);
                        details.setStatus("0");
                        details.setRepairedNum(0);
                        details.setScrapNum(bean.getScrapNum());
                        details.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                        details.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                        scrapApplyDetailsMapper.addRepaieAudit(details);
                    }
                }
                if (notScrapList.size() == scrapApplyDetailsList.size()) {
                    task.setTaskStatus(61);
                }
                task.setRemark(scrapAudit.getRemark());
            }
            if (scrapApplyDetailsList.size() > 0) {
                for (ScrapApplyDetails bean : scrapApplyDetailsList) {
                    bean.setAuditBy(SecurityUtils.getLoginUser().getUserid());
                    bean.setStatus(status);
                    bean.setAuditRemark(scrapAudit.getRemark());
                    bean.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                    scrapApplyDetailsMapper.updateStatus(bean);
                }
            }
            task.setUpdateTime(new Date());
            task.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
            taskMapper.updateTmTask(task);
        }
        return 1;
    }

    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;
    }

    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;
    }
}
