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

import cn.hutool.core.collection.CollUtil;
import com.bonus.sgzb.app.domain.LeaseApplyDetails;
import com.bonus.sgzb.app.domain.LeaseApplyInfo;
import com.bonus.sgzb.app.domain.TmTask;
import com.bonus.sgzb.app.mapper.LeaseApplyDetailsMapper;
import com.bonus.sgzb.app.mapper.LeaseApplyInfoMapper;
import com.bonus.sgzb.app.mapper.TmTaskMapper;
import com.bonus.sgzb.app.service.*;
import com.bonus.sgzb.base.api.domain.BmFlowRecord;
import com.bonus.sgzb.base.api.domain.BmFlowRelation;
import com.bonus.sgzb.base.api.domain.MachinePart;
import com.bonus.sgzb.common.core.constant.Constants;
import com.bonus.sgzb.common.core.domain.R;
import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:
 *
 * @Author 阮世耀
 * @Create 2023/12/13 15:14
 * @Version 1.0
 */

@Service
@Slf4j
public class TmTaskServiceImpl implements TmTaskService {

    @Resource
    private TmTaskMapper tmTaskMapper;

    @Resource
    private LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private LeaseApplyDetailsMapper leaseApplyDetailsMapper;

    @Resource
    private BmFlowRelationService bmFlowRelationService;

    /**
     * 领料申请信息service
     */
    @Resource
    private LeaseApplyInfoService leaseApplyInfoService;

    /**
     * 领料申请信息明细service
     */
    @Resource
    private LeaseApplyDetailsService leaseApplyDetailsService;

    @Resource
    private LeaseUserBookService leaseUserBookService;

    @Resource
    private BmFlowRecordService bmFlowRecordService;

    private final static String STRING_ADMIN = "admin";

    /**
     * 领料任务审核状态
     *
     * @param record 审核数据及信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateLeaseTaskAuditInfo(TmTask record) {
        int result = 0;
        int taskId = 0;
        int num = 0;
        Long companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();
        if (StringUtils.isNotNull(record)) {
            // 内部审核
            if (record.getTaskStatus() == 33 && companyId != null) {
                // 再审核领料任务信息表
                List<LeaseApplyInfo> leaseApplyInfoList = record.getLeaseApplyInfoList();
                if (CollUtil.isNotEmpty(leaseApplyInfoList)) {
                    List<LeaseApplyInfo> applyInfoList = leaseApplyInfoList.stream().filter(t -> t.getCompanyId().equals(companyId.intValue())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(applyInfoList)) {
                        for (LeaseApplyInfo leaseApplyInfo : applyInfoList) {
                            taskId = leaseApplyInfo.getTaskId();
                            if (leaseApplyInfo != null) {
                                //leaseApplyInfo.setExamineStatusId(record.getExamineStatusId());
                                result += tmTaskMapper.updateLeaseApplyInfoAuditInfo(leaseApplyInfo);
                            }
                        }
                    }
                    List<LeaseApplyInfo> leaseApplyInfo = tmTaskMapper.getLeaseApplyInfo(taskId);
                    for (LeaseApplyInfo applyInfo : leaseApplyInfo) {
                        if (applyInfo.getStatus() != null) {
                            if ("1".equals(applyInfo.getStatus()) || "3".equals(applyInfo.getStatus())) {
                                num++;
                            }
                        }
                    }
                    //说明全部审核完成
                    if (num == leaseApplyInfo.size()) {
                        // 再审核任务表
                        result += tmTaskMapper.updateTmTaskAuditStatus(record);
                    }
                }
                // 再审核领料任务详情表
                List<LeaseApplyDetails> leaseApplyDetails = record.getLeaseApplyDetails();
                if (CollUtil.isNotEmpty(leaseApplyDetails)) {
                    List<LeaseApplyDetails> collect = leaseApplyDetails.stream().filter(d -> d.getCompanyId().equals(companyId.intValue())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)) {
                        for (LeaseApplyDetails details : collect) {
                            if (StringUtils.isNotNull(details)) {
                                result += tmTaskMapper.updateLeaseApplyDetailsAuditInfo(details);
                            }
                        }
                    }
                }
            } else if (record.getTaskStatus() == 32 && companyId != null) {
                // 再审核领料任务信息表
                List<LeaseApplyInfo> leaseApplyInfoList = record.getLeaseApplyInfoList();
                if (CollUtil.isNotEmpty(leaseApplyInfoList)) {
                    List<LeaseApplyInfo> applyInfoList = leaseApplyInfoList.stream().filter(t -> t.getCompanyId().equals(companyId.intValue())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(applyInfoList)) {
                        for (LeaseApplyInfo leaseApplyInfo : applyInfoList) {
                            taskId = leaseApplyInfo.getTaskId();
                            if (leaseApplyInfo != null) {
                                //leaseApplyInfo.setExamineStatusId(record.getExamineStatusId());
                                result += tmTaskMapper.updateLeaseApplyInfoAuditInfo(leaseApplyInfo);
                            }
                        }
                    }
                    List<LeaseApplyInfo> leaseApplyInfo = tmTaskMapper.getLeaseApplyInfo(taskId);
                    for (LeaseApplyInfo applyInfo : leaseApplyInfo) {
                        if (applyInfo.getStatus() != null) {
                            if ("5".equals(applyInfo.getStatus()) || "7".equals(applyInfo.getStatus())) {
                                num++;
                            }
                        }
                    }
                    //说明全部审核完成
                    if (num == leaseApplyInfo.size()) {
                        // 再审核任务表
                        result += tmTaskMapper.updateTmTaskAuditStatus(record);
                    }
                }
                // 再审核领料任务详情表
                List<LeaseApplyDetails> leaseApplyDetails = record.getLeaseApplyDetails();
                if (CollUtil.isNotEmpty(leaseApplyDetails)) {
                    List<LeaseApplyDetails> collect = leaseApplyDetails.stream().filter(d -> d.getCompanyId().equals(companyId.intValue())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)) {
                        for (LeaseApplyDetails details : collect) {
                            if (StringUtils.isNotNull(details)) {
                                result += tmTaskMapper.updateLeaseApplyDetailsAuditInfo(details);
                            }
                        }
                    }
                }
            } else {
                // 先审核任务表
                result += tmTaskMapper.updateTmTaskAuditStatus(record);
                // 分公司审核
                // 再审核领料任务信息表
                List<LeaseApplyInfo> leaseApplyInfoList = record.getLeaseApplyInfoList();
                if (CollUtil.isNotEmpty(leaseApplyInfoList)) {
                    for (LeaseApplyInfo leaseApplyInfo : leaseApplyInfoList) {
                        if (leaseApplyInfo != null) {
                            //leaseApplyInfo.setExamineStatusId(record.getExamineStatusId());
                            result += tmTaskMapper.updateLeaseApplyInfoAuditInfo(leaseApplyInfo);
                        }
                    }
                }
                // 再审核领料任务详情表
                List<LeaseApplyDetails> leaseApplyDetails = record.getLeaseApplyDetails();
                if (CollUtil.isNotEmpty(leaseApplyDetails)) {
                    for (LeaseApplyDetails details : leaseApplyDetails) {
                        if (StringUtils.isNotNull(details)) {
                            result += tmTaskMapper.updateLeaseApplyDetailsAuditInfo(details);
                        }
                    }
                }
            }
        } else {
            return 0;
        }
        return result;

    }

    @Override
    public int updateLeaseTaskAuditInfoCq(TmTask record) {
        int result = 0;
        if (StringUtils.isNotNull(record)) {
            // 先修改任务表
            result += tmTaskMapper.updateTmTaskAuditStatus(record);

            // 再审核领料任务信息表
            List<LeaseApplyInfo> leaseApplyInfoList = record.getLeaseApplyInfoList();
            if (CollUtil.isNotEmpty(leaseApplyInfoList)) {
                for (LeaseApplyInfo leaseApplyInfo : leaseApplyInfoList) {
                    if (leaseApplyInfo != null) {
                        if (leaseApplyInfo.getCompanyId() == null) {
                            result += tmTaskMapper.updateLeaseApplyInfoAuditInfoCq(leaseApplyInfo);
                        } else {
                            result += tmTaskMapper.updateLeaseApplyInfoAuditInfo(leaseApplyInfo);
                        }
                    }
                }
            }
            // 再审核领料任务详情表
            List<LeaseApplyDetails> leaseApplyDetails = record.getLeaseApplyDetails();
            if (CollUtil.isNotEmpty(leaseApplyDetails)) {
                for (LeaseApplyDetails details : leaseApplyDetails) {
                    if (StringUtils.isNotNull(details)) {
                        result += tmTaskMapper.updateLeaseApplyDetailsAuditInfo(details);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public int updateLeaseTaskStatusConfirmByCq(TmTask record) {
        return tmTaskMapper.updateTmTaskAuditStatus(record);
    }

    /**
     * 获取领料申请列表
     */
    @Override
    public List<TmTask> getLeaseAuditListByOne(TmTask record) {
        List<TmTask> leaseDetailByParentId = tmTaskMapper.getLeaseDetailByParentId(record);
       /* for (TmTask tmTask : leaseDetailByParentId) {
            if ("2".equals(tmTask.getManageType())) {
                List<TmTask> manageTypeByTypeId = tmTaskMapper.getManageTypeByTypeId(tmTask);
                // 目前先默认成套只能数量出库或编码出库
                tmTask.setOutboundType(manageTypeByTypeId);
            }
        }*/
        return leaseDetailByParentId;
    }

    /**
     * 创建审批流领料申请
     *
     * @param task 任务信息
     * @return 执行结果
     */
    @Override
    public AjaxResult createFlowLeaseApply(TmTask task) {
        // ---------审批流校验---------
        List<BmFlowRelation> bmFlowRelationList = leaseExamFlowParamCheck(task);
        // 校验审批流配置
        if (CollUtil.isEmpty(bmFlowRelationList)) {
            return AjaxResult.error("当前任务类型审批流配置为空，请联系管理员");
        }
        // 审批流排序
        if (!copeOrderByField(bmFlowRelationList)) {
            return AjaxResult.error("审批流排序失败，请联系管理员");
        }
        // 获取起始节点状态
        String flowStartTaskStatus = bmFlowRelationList.get(0).getTaskStatus();
        // 设置任务状态为审批流的起点状态
        task.setTaskStatus(Integer.valueOf(flowStartTaskStatus));
        // -----------审批流处理结束 -------------

        // 生成领料编码
        String code = this.genderLeaseCode();
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("后台生成CODE编号异常，请重试!");
        }
        task.setCode(code);

        // 创建任务
        if (this.insertSelective(task) < 1) {
            return AjaxResult.error("创建领料任务失败，请重试!");
        }
        //任务与协议建立关联关系
        if (this.insertAgreement(task) < 1) {
            return AjaxResult.error("领料任务与协议建立关联关系失败，请重试!");
        }

        // 获取任务编号
        String taskId = task.getId();
        if (StringUtils.isEmpty(taskId)) {
            return AjaxResult.error("任务编号为空,创建失败");
        }

        // 处理任务数据，实例化至DB
        R<String> taskDataCopeResult = leaseTaskDataCope(task, code, taskId, bmFlowRelationList.size());
        if (taskDataCopeResult.getCode() != Constants.SUCCESS) {
            return AjaxResult.error(taskDataCopeResult.getMsg());
        }

        // 数据处理成功后增加审批流记录
        R<?> addLeaseTaskFlowRecordResult = addLeaseTaskFlowRecord(taskId, bmFlowRelationList);
        if (addLeaseTaskFlowRecordResult.getCode() != Constants.SUCCESS) {
            return AjaxResult.error(addLeaseTaskFlowRecordResult.getMsg());
        }

        return AjaxResult.success("执行成功,领料任务已添加");
    }

    private R<?> addLeaseTaskFlowRecord(String taskId, List<BmFlowRelation> bmFlowRelationList) {
        BmFlowRecord bmFlowRecord = new BmFlowRecord();
        try {
            bmFlowRecord.setTaskId(Integer.valueOf(taskId));
            bmFlowRecord.setFlowId(bmFlowRelationList.get(0).getFlowId());
            if (bmFlowRelationList.size() > 1) {
                bmFlowRecord.setNextFlowId(bmFlowRelationList.get(1).getFlowId());
            }
            // String loginUserName = SecurityUtils.getLoginUser().getSysUser().getUserName();
            // bmFlowRecord.setCreator(loginUserName == null ? "" : loginUserName);
            bmFlowRecordService.insertSelective(bmFlowRecord);
        } catch (Exception e) {
            return R.fail("数据处理完成，但审批流记录失败，请联系运维人员:{}", e.getMessage());
        }
        return R.ok(Constants.LOGIN_SUCCESS);
    }

    private R<String> leaseTaskDataCope(TmTask task, String code, String taskId, Integer bmFlowRelationListSize) {
        // -----------数据处理开始start ---------------
        // 根据设备所属分公司--拆分集合
        List<List<LeaseApplyDetails>> deviceByCompanyList;
        try {
            deviceByCompanyList = CollUtil.groupByField(task.getLeaseApplyDetails(), "companyId");
        } catch (RuntimeException e) {
            log.error("领料任务数据拆分集合处理异常,请重试:{}", e.getMessage());
            return R.fail("领料任务数据拆分集合处理异常,请重试");
        }

        ArrayList<Integer> ids = new ArrayList<>();
        // 对拆分后的集合进行each遍历
        for (List<LeaseApplyDetails> leaseApplyDetailsList : deviceByCompanyList) {
            // 判断拆分后的集合内是否有数据
            if (CollUtil.isNotEmpty(leaseApplyDetailsList)) {
                // 对领料任务表的对象做数据处理
                LeaseApplyInfo leaseApplyInfo = task.getLeaseApplyInfo();
                leaseApplyInfo.setCode(code);
                leaseApplyInfo.setTaskId(Integer.valueOf(taskId));
                // 设置设备所属分公司,用于交给哪家审核
                leaseApplyInfo.setCompanyId(leaseApplyDetailsList.get(0).getCompanyId());
                // 设置审批层级，根据已启用的审批流进行赋值层数
                leaseApplyInfo.setType(String.valueOf(bmFlowRelationListSize));

                // 创建领料任务，返回领料任务编号
                if (leaseApplyInfoService.genderLeaseCode(leaseApplyInfo) < 1) {
                    return R.fail("创建领料任务失败,或领料明细为空");
                }

                // 领料任务创建完成，进行领料任务明细插入
                ids.clear();
                if (StringUtils.isNotNull(leaseApplyInfo.getId())) {
                    for (LeaseApplyDetails leaseApplyDetails : leaseApplyDetailsList) {
                        // 设置领料任务ID
                        leaseApplyDetails.setParenntId(leaseApplyInfo.getId());
                        ids.add(leaseApplyDetails.getId());
                    }
                    // 插入领料任务明细
                    if (leaseApplyDetailsService.batchInsert(leaseApplyDetailsList) > 0) {
                        leaseUserBookService.batchDel(ids);
                    } else {
                        log.error("领料任务明细插入失败:{}", task.getTaskId());
                        System.out.println(("领料任务明细插入失败，请重试"));
                    }
                } else {
                    return R.fail("领料任务编号为空");
                }
            }
        }
        // -----------数据处理结束end ---------------
        return R.ok(null, "领料任务数据插入成功");
    }

    /**
     * 审批流排序
     *
     * @param bmFlowRelationList 审批流数据集合
     * @return 排序结果
     */
    public static boolean copeOrderByField(List<BmFlowRelation> bmFlowRelationList) {
        // 使用lambda表达式 按order字段从小到大进行排序
        try {
            bmFlowRelationList.sort(Comparator.comparingInt(BmFlowRelation::getOrder));
        } catch (Exception e) {
            log.error("审批流排序处理异常:{}", e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 根据任务入参查询审批流信息
     *
     * @param task 任务
     * @return 审批流数据集合
     */
    private List<BmFlowRelation> leaseExamFlowParamCheck(TmTask task) {
        // 查询当前任务类型的审批流配置
        BmFlowRelation bmFlowRelation = new BmFlowRelation();
        // 赋值任务类型
        bmFlowRelation.setTaskType(29);
        // 赋值组织机构
        bmFlowRelation.setCompanyId(task.getCompanyId());
        return bmFlowRelationService.selectAllByPrimaryKey(bmFlowRelation);
    }


    /**
     * 获取单个申请列表
     */
    @Override
    public List<TmTask> getLeaseAuditList(TmTask record) {
        Set<String> roles = SecurityUtils.getLoginUser().getRoles();
        List<TmTask> tmTaskList;
        if (roles.contains(STRING_ADMIN)) {
            tmTaskList = tmTaskMapper.getAuditListByLeaseTmTask(record);
        } else {
            String username = SecurityUtils.getLoginUser().getUsername();
            record.setCreateBy(username);
            tmTaskList = tmTaskMapper.getAuditListByLeaseTmTaskByPeople(record);
        }
        for (TmTask tmTask : tmTaskList) {
            int count = 0;
            if (tmTask != null) {
                // 去查询任务分单表
                List<LeaseApplyInfo> auditListByLeaseInfo = tmTaskMapper.getAuditListByLeaseInfo(tmTask);
                if (auditListByLeaseInfo != null && !auditListByLeaseInfo.isEmpty()) {
                    // 对领料任务集合查询具体详情
                    for (LeaseApplyInfo leaseApplyInfo : auditListByLeaseInfo) {
                        if (leaseApplyInfo != null) {
                            // 去查询领料任务详情表
                            List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyDetails(leaseApplyInfo);
                            if (leaseApplyDetails != null && !leaseApplyDetails.isEmpty()) {
                                for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                                    if (leaseApplyDetail != null && leaseApplyDetail.getPreNum() != null) {
                                        // 统计预领数量
                                        count += leaseApplyDetail.getPreNum();
                                    }
                                }
                                // 塞入领料任务详情的集合中
                                leaseApplyInfo.setLeaseApplyDetails(leaseApplyDetails);
                            }
                        }
                    }
                    // 存入领料任务实体集合
                    tmTask.setLeaseApplyInfoList(auditListByLeaseInfo);
                    tmTask.setRemark(auditListByLeaseInfo.get(0).getRemark());
                }
                // 塞入预领的合计数量
                tmTask.setPreCountNum(count);
            }
        }

        return tmTaskList;
    }

    @Override
    public List<TmTask> getLeaseAuditManageListCq(TmTask record) {
        List<TmTask> tmTaskList = tmTaskMapper.getAuditManageListByLeaseTmTask(record);
        for (TmTask tmTask : tmTaskList) {
            int count = 0;
            if (tmTask != null) {
                // 去查询任务分单表
                List<LeaseApplyInfo> collect = tmTaskMapper.getAuditManageListByLeaseInfo(tmTask);
                // 对领料任务集合查询具体详情
                for (LeaseApplyInfo leaseApplyInfo : collect) {
                    if (leaseApplyInfo != null) {
                        // 去查询领料任务详情表
                        List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyManageDetails(leaseApplyInfo);
                        if (leaseApplyDetails != null && !leaseApplyDetails.isEmpty()) {
                            for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                                if (leaseApplyDetail != null && leaseApplyDetail.getPreNum() != null) {
                                    // 统计预领数量
                                    count += leaseApplyDetail.getPreNum();
                                }
                            }
                            // 塞入领料任务详情的集合中
                            leaseApplyInfo.setLeaseApplyDetails(leaseApplyDetails);
                            tmTask.setRemark(collect.get(0).getRemark());
                        }
                    }
                }
                // 存入领料任务实体集合
                tmTask.setLeaseApplyInfoList(collect);
                tmTask.setPreCountNum(count);
            }
        }
        List<TmTask> tmTasks = tmTaskList.stream().filter(t -> t.getLeaseApplyInfoList() != null).collect(Collectors.toList());
        return tmTasks;
    }

    @Override
    public List<TmTask> getLeaseListAllCq(TmTask task) {
        List<TmTask> tmTaskList = new ArrayList<>();
        TmTask tmTask = tmTaskMapper.getLeaseListTmTask(task);
        if (tmTask != null) {
            List<LeaseApplyInfo> leaseApplyInfoList = tmTaskMapper.getLeaseListByLeaseInfo(task);
            tmTask.setLeaseApplyInfoList(leaseApplyInfoList);

            List<LeaseApplyDetails> listLeaseDetails = new ArrayList<>();
            for (LeaseApplyInfo leaseApplyInfo : leaseApplyInfoList) {
                if (leaseApplyInfo != null) {
                    // 去查询领料任务详情表
                    List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyDetailsCq(leaseApplyInfo);
                    if (leaseApplyDetails.size() > 0) {
                        for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                            List<MachinePart> machineParts = new ArrayList<>();
                            List<TmTask> typeIds = tmTaskMapper.getMaTypeDetails(leaseApplyDetail);
                            typeIds.removeIf(item -> item == null);
                            for (TmTask typeId : typeIds) {
                                MachinePart machinePart = tmTaskMapper.getMachineParts(typeId);
                                machinePart.setPartNum((typeId.getPartNum() * leaseApplyDetail.getPreNum()));
                                machineParts.add(machinePart);
                            }
                            leaseApplyDetail.setMaTypeDetails(machineParts);
                        }
                        listLeaseDetails.addAll(leaseApplyDetails);
                    }
                }
            }
            // 塞入领料任务详情的集合中
            tmTask.setLeaseApplyDetails(listLeaseDetails);
        }
        tmTaskList.add(tmTask);
        return tmTaskList;
    }

    @Override
    public List<TmTask> getLeaseOutListByUser(TmTask task) {
        return tmTaskMapper.getLeaseOutListByUser(task);
    }

    @Override
    public String selectTaskNumByMonths(Date nowDate, Integer taskType) {
        return tmTaskMapper.selectTaskNumByMonths(nowDate, taskType);
    }


    /**
     * 获取领料申请列表
     */
    @Override
    public List<TmTask> getLeaseAuditListByAdmin(TmTask record) {
        List<TmTask> tmTaskList = tmTaskMapper.getAuditListByLeaseTmTask(record);
        for (TmTask tmTask : tmTaskList) {
            int count = 0;
            if (tmTask != null) {
                // 去查询任务分单表
                List<LeaseApplyInfo> auditListByLeaseInfo = tmTaskMapper.getAuditListByLeaseInfo(tmTask);
                if (auditListByLeaseInfo != null && !auditListByLeaseInfo.isEmpty()) {
                    // 对领料任务集合查询具体详情
                    for (LeaseApplyInfo leaseApplyInfo : auditListByLeaseInfo) {
                        if (leaseApplyInfo != null) {
                            // 去查询领料任务详情表
                            List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyDetails(leaseApplyInfo);
                            if (leaseApplyDetails != null && !leaseApplyDetails.isEmpty()) {
                                for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                                    if (leaseApplyDetail != null) {
                                        // 统计预领数量
                                        count += leaseApplyDetail.getPreNum();
                                    }
                                }
                                // 塞入领料任务详情的集合中
                                leaseApplyInfo.setLeaseApplyDetails(leaseApplyDetails);
                            }
                        }
                    }
                    // 存入领料任务实体集合
                    tmTask.setLeaseApplyInfoList(auditListByLeaseInfo);
                }
                // 塞入预领的合计数量
                tmTask.setPreCountNum(count);
            }
        }

        return tmTaskList;
    }

    /**
     * 获取领料管理列表
     */
    @Override
    public List<TmTask> getLeaseAuditManageList(TmTask record) {
        List<TmTask> tmTaskList = tmTaskMapper.getAuditManageListByLeaseTmTask(record);
        Long companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();
        Set<String> roles = SecurityUtils.getLoginUser().getRoles();
        for (TmTask tmTask : tmTaskList) {
            int count = 0;
            if (tmTask != null) {
                // 去查询任务分单表
                List<LeaseApplyInfo> collect = tmTaskMapper.getAuditManageListByLeaseInfo(tmTask);
                //没有companyId的用户或者是分公司账号可以看到所有数据
                if (companyId == null || roles.contains("fgs")) {
                    // 对领料任务集合查询具体详情
                    for (LeaseApplyInfo leaseApplyInfo : collect) {
                        if (leaseApplyInfo != null) {
                            // 去查询领料任务详情表
                            List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyManageDetails(leaseApplyInfo);
                            if (leaseApplyDetails.size() > 0) {
                                for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                                    if (leaseApplyDetail != null && leaseApplyDetail.getPreNum() != null) {
                                        // 统计预领数量
                                        count += leaseApplyDetail.getPreNum();
                                    }
                                }
                                // 塞入领料任务详情的集合中
                                leaseApplyInfo.setLeaseApplyDetails(leaseApplyDetails);
                                // 存入领料任务实体集合
                                tmTask.setLeaseApplyInfoList(collect);
                                tmTask.setRemark(collect.get(0).getRemark());
                            }
                        }
                    }
                    // 存入领料任务实体集合
                    tmTask.setLeaseApplyInfoList(collect);
                    if (collect.size() > 0) {
                        tmTask.setRemark(collect.get(0).getRemark());
                    }
                }
                //施管部只能看到机具分公司（101）的数据
                if ((roles.contains("jjfgs") || roles.contains("sgb")) && companyId != null) {
                    List<LeaseApplyInfo> auditListByLeaseInfo = collect.stream().filter(t -> t.getCompanyId() != null).filter(t -> t.getCompanyId() == companyId.intValue()).collect(Collectors.toList());
                    if (auditListByLeaseInfo != null && !auditListByLeaseInfo.isEmpty()) {
                        // 对领料任务集合查询具体详情
                        for (LeaseApplyInfo leaseApplyInfo : auditListByLeaseInfo) {
                            if (leaseApplyInfo != null) {
                                // 去查询领料任务详情表
                                List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyManageDetails(leaseApplyInfo);
                                if (leaseApplyDetails.size() > 0) {
                                    for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                                        if (leaseApplyDetail != null && leaseApplyDetail.getPreNum() != null) {
                                            // 统计预领数量
                                            count += leaseApplyDetail.getPreNum();
                                        }
                                    }
                                    // 塞入领料任务详情的集合中
                                    leaseApplyInfo.setLeaseApplyDetails(leaseApplyDetails);
                                    // 存入领料任务实体集合
                                    tmTask.setLeaseApplyInfoList(auditListByLeaseInfo);
                                    tmTask.setRemark(collect.get(0).getRemark());
                                }
                            }
                        }
                    }
                }
                //安监部只能看到设备分公司（102）的数据
                if ((roles.contains("tsfgs") || roles.contains("ajb")) && companyId != null) {
                    List<LeaseApplyInfo> auditListByLeaseInfo = collect.stream().filter(t -> t.getCompanyId() != null).filter(t -> t.getCompanyId() == companyId.intValue()).collect(Collectors.toList());
                    if (auditListByLeaseInfo != null && !auditListByLeaseInfo.isEmpty()) {
                        // 对领料任务集合查询具体详情
                        for (LeaseApplyInfo leaseApplyInfo : auditListByLeaseInfo) {
                            if (leaseApplyInfo != null) {
                                // 去查询领料任务详情表
                                List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyManageDetails(leaseApplyInfo);
                                if (leaseApplyDetails.size() > 0) {
                                    for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                                        if (leaseApplyDetail != null) {
                                            // 统计预领数量
                                            count += leaseApplyDetail.getPreNum();
                                        }
                                    }
                                    // 塞入领料任务详情的集合中
                                    leaseApplyInfo.setLeaseApplyDetails(leaseApplyDetails);
                                    // 存入领料任务实体集合
                                    tmTask.setLeaseApplyInfoList(auditListByLeaseInfo);
                                    tmTask.setRemark(collect.get(0).getRemark());
                                }
                            }
                        }
                    }
                }
                // 塞入预领的合计数量
                tmTask.setPreCountNum(count);
            }
        }
        List<TmTask> tmTasks = tmTaskList.stream().filter(t -> t.getLeaseApplyInfoList() != null).collect(Collectors.toList());
        return tmTasks;
    }

    /**
     * 获取审核列表 - App端
     */
    @Override
    public List<TmTask> getLeaseAuditListForApp(TmTask record) {
        List<TmTask> tmTaskList = tmTaskMapper.getAuditListByLeaseTmTask(record);
        for (TmTask tmTask : tmTaskList) {
            int count = 0;
            if (tmTask != null) {
                // 去查询任务分单表
                List<LeaseApplyInfo> auditListByLeaseInfo = tmTaskMapper.getAuditListByLeaseInfo(tmTask);
                if (auditListByLeaseInfo != null && !auditListByLeaseInfo.isEmpty()) {
                    // 对领料任务集合查询具体详情
                    for (LeaseApplyInfo leaseApplyInfo : auditListByLeaseInfo) {
                        if (leaseApplyInfo != null) {
                            // 去查询领料任务详情表
                            List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyDetails(leaseApplyInfo);
                            if (leaseApplyDetails != null && !leaseApplyDetails.isEmpty()) {
                                for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                                    if (leaseApplyDetail != null) {
                                        Integer typeId = leaseApplyDetail.getTypeId();
                                        //根据器具id找到对应的库管员信息
                                        Integer userId = tmTaskMapper.getKgByMaType(typeId);
                                        if (userId != null && userId != 0 && SecurityUtils.getLoginUser().getUserid().equals((long) userId)) {
                                            // 统计预领数量
                                            count += leaseApplyDetail.getPreNum();
                                            leaseApplyDetail.setUserId(userId);
                                        }
                                    }

                                }
                                // 塞入领料任务详情的集合中
                                leaseApplyInfo.setLeaseApplyDetails(leaseApplyDetails);
                            }
                        }
                    }
                    // 存入领料任务实体集合
                    tmTask.setLeaseApplyInfoList(auditListByLeaseInfo);
                }
                // 塞入预领的合计数量
                tmTask.setPreCountNum(count);
            }
        }
        return tmTaskList;
    }

    /**
     * 领料任务驳回
     *
     * @param record 审核数据及信息
     */
    @Override
    @Transactional
    public int updateLeaseTaskRejectInfo(TmTask record) {
        int result = 0;
        int taskId = 0;
        int num = 0;
        Long companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();
        if (StringUtils.isNotNull(record)) {
            // 先审核任务表
            result += tmTaskMapper.updateTmTaskAuditStatus(record);
            // 内部审核驳回
            if (record.getTaskStatus() == 100 && companyId != null) {
                // 再审核领料任务信息表
                List<LeaseApplyInfo> leaseApplyInfoList = record.getLeaseApplyInfoList();
                if (CollUtil.isNotEmpty(leaseApplyInfoList)) {
                    List<LeaseApplyInfo> applyInfoList = leaseApplyInfoList.stream().filter(t -> t.getCompanyId().equals(companyId.intValue())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(applyInfoList)) {
                        for (LeaseApplyInfo leaseApplyInfo : applyInfoList) {
                            taskId = leaseApplyInfo.getTaskId();
                            if (leaseApplyInfo != null) {
                                //leaseApplyInfo.setExamineStatusId(record.getExamineStatusId());
                                result += tmTaskMapper.updateLeaseApplyInfoRejectInfo(leaseApplyInfo);

                            }
                        }
                    }
                    List<LeaseApplyInfo> leaseApplyInfo = tmTaskMapper.getLeaseApplyInfo(taskId);
                    for (LeaseApplyInfo applyInfo : leaseApplyInfo) {
                        if (applyInfo.getStatus() != null) {
                            if (applyInfo.getStatus().equals("2") || applyInfo.getStatus().equals("4")) {
                                num++;
                            }
                        }
                    }
                    //说明全部审核完成
                    if (num == leaseApplyInfo.size()) {
                        // 再审核任务表
                        result += tmTaskMapper.updateTmTaskAuditStatus(record);
                    }
                }
                // 再审核领料任务详情表
                List<LeaseApplyDetails> leaseApplyDetails = record.getLeaseApplyDetails();
                if (CollUtil.isNotEmpty(leaseApplyDetails)) {
                    List<LeaseApplyDetails> collect = leaseApplyDetails.stream().filter(d -> d.getCompanyId().equals(companyId.intValue())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)) {
                        for (LeaseApplyDetails details : collect) {
                            if (StringUtils.isNotNull(details)) {
                                result += tmTaskMapper.updateLeaseApplyDetailsRejectInfo(details);
                            }
                        }
                    }
                }
            } else if (record.getTaskStatus() == 99 && companyId != null) {
                // 再审核领料任务信息表
                List<LeaseApplyInfo> leaseApplyInfoList = record.getLeaseApplyInfoList();
                if (CollUtil.isNotEmpty(leaseApplyInfoList)) {
                    List<LeaseApplyInfo> applyInfoList = leaseApplyInfoList.stream().filter(t -> t.getCompanyId().equals(companyId.intValue())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(applyInfoList)) {
                        for (LeaseApplyInfo leaseApplyInfo : applyInfoList) {
                            taskId = leaseApplyInfo.getTaskId();
                            if (leaseApplyInfo != null) {
                                //leaseApplyInfo.setExamineStatusId(record.getExamineStatusId());
                                result += tmTaskMapper.updateLeaseApplyInfoRejectInfo(leaseApplyInfo);

                            }
                        }
                    }
                    List<LeaseApplyInfo> leaseApplyInfo = tmTaskMapper.getLeaseApplyInfo(taskId);
                    for (LeaseApplyInfo applyInfo : leaseApplyInfo) {
                        if (applyInfo.getStatus() != null) {
                            if (applyInfo.getStatus().equals("6") || applyInfo.getStatus().equals("8")) {
                                num++;
                            }
                        }
                    }
                    //说明全部审核完成
                    if (num == leaseApplyInfo.size()) {
                        // 再审核任务表
                        result += tmTaskMapper.updateTmTaskAuditStatus(record);
                    }
                }
                // 再审核领料任务详情表
                List<LeaseApplyDetails> leaseApplyDetails = record.getLeaseApplyDetails();
                if (CollUtil.isNotEmpty(leaseApplyDetails)) {
                    List<LeaseApplyDetails> collect = leaseApplyDetails.stream().filter(d -> d.getCompanyId().equals(companyId.intValue())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)) {
                        for (LeaseApplyDetails details : collect) {
                            if (StringUtils.isNotNull(details)) {
                                result += tmTaskMapper.updateLeaseApplyDetailsRejectInfo(details);
                            }
                        }
                    }
                }
            } else {
                // 先审核任务表
                result += tmTaskMapper.updateTmTaskAuditStatus(record);
                // 分公司驳回
                // 再审核领料任务信息表
                List<LeaseApplyInfo> leaseApplyInfoList = record.getLeaseApplyInfoList();
                if (CollUtil.isNotEmpty(leaseApplyInfoList)) {
                    for (LeaseApplyInfo leaseApplyInfo : leaseApplyInfoList) {
                        if (leaseApplyInfo != null) {
                            //leaseApplyInfo.setExamineStatusId(record.getExamineStatusId());
                            result += tmTaskMapper.updateLeaseApplyInfoRejectInfo(leaseApplyInfo);
                        }
                    }
                }
                // 再审核领料任务详情表
                List<LeaseApplyDetails> leaseApplyDetails = record.getLeaseApplyDetails();
                if (CollUtil.isNotEmpty(leaseApplyDetails)) {
                    for (LeaseApplyDetails details : leaseApplyDetails) {
                        if (StringUtils.isNotNull(details)) {
                            result += tmTaskMapper.updateLeaseApplyDetailsRejectInfo(details);
                        }
                    }
                }
            }
        } else {
            return result;
        }
        return result;
    }

    @Override
    public int updateLeaseTaskRejectInfoCq(TmTask record) {
        int result = 0;
        if (StringUtils.isNotNull(record)) {
            // 先审核任务表
            result += tmTaskMapper.updateTmTaskAuditStatus(record);
            // 分公司驳回
            // 再审核领料任务信息表
            List<LeaseApplyInfo> leaseApplyInfoList = record.getLeaseApplyInfoList();
            if (CollUtil.isNotEmpty(leaseApplyInfoList)) {
                for (LeaseApplyInfo leaseApplyInfo : leaseApplyInfoList) {
                    if (leaseApplyInfo != null) {
                        if (leaseApplyInfo.getCompanyId() == null) {
                            result += tmTaskMapper.updateLeaseApplyInfoRejectInfoCq(leaseApplyInfo);
                        } else {
                            result += tmTaskMapper.updateLeaseApplyInfoRejectInfo(leaseApplyInfo);
                        }
                    }
                }
            }
            // 再审核领料任务详情表
            List<LeaseApplyDetails> leaseApplyDetails = record.getLeaseApplyDetails();
            if (CollUtil.isNotEmpty(leaseApplyDetails)) {
                for (LeaseApplyDetails details : leaseApplyDetails) {
                    if (StringUtils.isNotNull(details)) {
                        result += tmTaskMapper.updateLeaseApplyDetailsRejectInfo(details);
                    }
                }
            }

        } else {
            return result;
        }
        return result;
    }

    @Override
    public String genderLeaseCode() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        int num = tmTaskMapper.selectNumByMonth(nowDate);
        num = num + 1;
        String code;
        if (num > 9 && num < 100) {
            code = "L" + result + "-00" + num;
        } else if (num > 99 && num < 1000) {
            code = "L" + result + "-0" + num;
        } else {
            code = "L" + result + "-000" + num;
        }
        return code;

        /*Random random = new Random();
        // 先生成随机4位字符，后期根据数据库当月最大CODE值+1
        int number = random.nextInt(9999);
        // 将随机整激格式化4位字符串，不足4位在前面补
        return "L" + DateUtils.getDate() + "-" + String.format("%04d", number);*/
    }

    @Override
    public AjaxResult deleteByPrimaryKey(String taskId) {
        int i = tmTaskMapper.deleteTaskByPrimaryKey(taskId);
        int j = tmTaskMapper.deleteTaskInfoByTaskId(taskId);
        int m = tmTaskMapper.deleteTaskAgreementByTaskId(taskId);
        if (i == 1 && j == 1 && m == 1) {
            return AjaxResult.success("删除成功");
        } else if (i < 1 || j < 1 || m < 1) {
            return AjaxResult.error("删除失败,任务表或信息表或任务协议关联表未删除!");
        } else {
            return AjaxResult.success("删除成功");
        }
    }

    @Override
    public int deleteLeaseInfoByTaskId(String taskId) {
        int i = tmTaskMapper.deleteTaskInfoByTaskId(taskId);
        return i;
    }

    /**
     * 根据id删除详情表配置的设备
     *
     * @param id 数据id
     * @return 结果
     */
    @Override
    public int deleteDetailsByTaskId(String id) {
        return tmTaskMapper.deleteDetailsByTaskId(id);
    }

    /**
     * 根据parentID删除详情表配置的设备
     *
     * @param parentId 所属ID
     * @return 结果
     */
    @Override
    public int deleteDetailsByParentId(String parentId) {
        return tmTaskMapper.deleteDetailsByParentId(parentId);
    }

    @Override
    public int createTask(TmTask record) {
        return tmTaskMapper.insert(record);
    }

    @Override
    public int insertOrUpdate(TmTask record) {
        return tmTaskMapper.insertOrUpdate(record);
    }

    @Override
    public int insertOrUpdateSelective(TmTask record) {
        return tmTaskMapper.insertOrUpdateSelective(record);
    }

    @Override
    public int insertSelective(TmTask record) {
        return tmTaskMapper.insertSelective(record);
    }

    @Override
    public TmTask selectByPrimaryKey(Long taskId) {
        return tmTaskMapper.selectByPrimaryKey(taskId);
    }

    @Override
    public int updateByPrimaryKeySelective(TmTask record) {
        return tmTaskMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int edit(TmTask tmTask) {
        int res = 0;
        //修改任务信息（tm_task）
        this.updateByPrimaryKeySelective(tmTask);
        try {
            if (CollUtil.isEmpty(tmTask.getLeaseApplyInfoList())) {
                throw new RuntimeException("参数异常");
            }
            // 修改任务关联的协议
            this.updateAgreementByTask(tmTask);
            //先删除leaseApplyDetail
            res = deletePreDetailData(tmTask);
            if (res == 0) {
                throw new RuntimeException("删除leaseApplyDetail异常");
            }
            //再删除leaseApplyInfo
            res = deletePreData(tmTask);
            if (res == 0) {
                throw new RuntimeException("删除leaseApplyInfo异常");
            }
            // 先查询lease apply info，根据task id,company id,不存在则插入，领料任务，领料单号，领料人，联系电话，备注，存在则不插入
            res = insertNewData(tmTask);
            if (res == 0) {
                throw new RuntimeException("insertNewData异常");
            }
            // 再插入lease apply detail
            res = insertNewDetailData(tmTask);
            if (res == 0) {
                throw new RuntimeException("insertNewDetailData异常");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editCq(TmTask tmTask) {
        int res = 0;
        //修改任务信息（tm_task）
        this.updateByPrimaryKeySelective(tmTask);
        try {
            if (CollUtil.isEmpty(tmTask.getLeaseApplyInfoList())) {
                throw new RuntimeException("参数异常");
            }
            // 修改任务关联的协议
            this.updateAgreementByTask(tmTask);
            //先删除leaseApplyDetail
            res = deletePreDetailData(tmTask);
            if (res == 0) {
                throw new RuntimeException("删除leaseApplyDetail异常");
            }
            //再删除leaseApplyInfo
            res = deletePreData(tmTask);
            if (res == 0) {
                throw new RuntimeException("删除leaseApplyInfo异常");
            }
            // 先查询lease apply info，根据task id,company id,不存在则插入，领料任务，领料单号，领料人，联系电话，备注，存在则不插入
            res = insertNewDataCq(tmTask);
            if (res == 0) {
                throw new RuntimeException("insertNewData异常");
            }
            // 再插入lease apply detail
            res = insertNewDetailData(tmTask);
            if (res == 0) {
                throw new RuntimeException("insertNewDetailData异常");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return res;
    }

    private int deletePreDetailData(TmTask tmTask) {
        int res = 0;
        List<LeaseApplyDetails> leaseApplyDetails = leaseApplyDetailsMapper.selectByTaskId(tmTask);
        for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
            res = leaseApplyDetailsMapper.deleteByPrimaryKey(leaseApplyDetail.getId());
        }
        return res;
    }

    private int insertNewData(TmTask task) {
        int res = 0;
        LeaseApplyInfo leaseApplyInfo1 = task.getLeaseApplyInfo();
        String leasePerson = "";
        String remark = "";
        String phone = "";
        if (leaseApplyInfo1 != null) {
            leasePerson = leaseApplyInfo1.getLeasePerson();
            remark = leaseApplyInfo1.getRemark();
            phone = leaseApplyInfo1.getPhone();
        }
        List<LeaseApplyInfo> LeaseApplyInfoList = task.getLeaseApplyInfoList();
        Long taskId = task.getTaskId();
        if (CollUtil.isNotEmpty(LeaseApplyInfoList)) {
            for (LeaseApplyInfo leaseApply : LeaseApplyInfoList) {
                LeaseApplyInfo leaseApplyInfos = new LeaseApplyInfo();
                if (leaseApply.getCompanyId() == null) {
                    leaseApplyInfos = leaseApplyInfoMapper.selectByTaskIdAndCompIdCq(String.valueOf(taskId));
                } else {
                    leaseApplyInfos = leaseApplyInfoMapper.selectByTaskIdAndCompId(String.valueOf(taskId), leaseApply.getCompanyId());
                }
                if (leaseApplyInfos == null) {
                    LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
                    String code = this.genderLeaseCode();
                    leaseApplyInfo.setCode(code);
                    leaseApplyInfo.setTaskId(task.getTaskId().intValue());
                    leaseApplyInfo.setCode(task.getLeaseApplyInfoList().get(0).getCode());
                    leaseApplyInfo.setLeasePerson(leasePerson);
                    leaseApplyInfo.setPhone(phone);
                    if (task.getTaskStatus() == 32 && task.getSouceByRefuse() == 1) {
                        leaseApplyInfo.setDeptAuditBy(task.getLeaseApplyInfoList().get(0).getDeptAuditBy());
                        leaseApplyInfo.setDeptAuditTime(task.getLeaseApplyInfoList().get(0).getDeptAuditTime());
                        leaseApplyInfo.setDeptAuditRemark(task.getLeaseApplyInfoList().get(0).getDeptAuditRemark());
                    }
                    leaseApplyInfo.setRemark(remark);
                    leaseApplyInfo.setType(task.getLeaseApplyInfoList().get(0).getType());
                    leaseApplyInfo.setCompanyId(leaseApply.getCompanyId());
                    leaseApplyInfo.setEstimateLeaseTime(task.getEstimateLeaseTime());
                    leaseApplyInfo.setLeaseType(task.getLeaseType());
                    leaseApplyInfo.setCostBearingParty(leaseApply.getCostBearingParty());
                    res = leaseApplyInfoMapper.insert(leaseApplyInfo);
                }
            }
        }
        return res;
    }

    private int insertNewDataCq(TmTask task) {
        int res = 0;
        LeaseApplyInfo leaseApplyInfo1 = task.getLeaseApplyInfo();
        String leasePerson = "";
        String remark = "";
        String phone = "";
        if (leaseApplyInfo1 != null) {
            leasePerson = leaseApplyInfo1.getLeasePerson();
            remark = leaseApplyInfo1.getRemark();
            phone = leaseApplyInfo1.getPhone();
        }
        List<LeaseApplyDetails> leaseApplyDetails = task.getLeaseApplyDetails();
        Long taskId = task.getTaskId();
        if (CollUtil.isNotEmpty(leaseApplyDetails)) {
            for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                LeaseApplyInfo leaseApplyInfos = leaseApplyInfoMapper.selectByTaskIdAndCompIdCq(String.valueOf(taskId));
                if (leaseApplyInfos == null) {
                    LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
                    String code = this.genderLeaseCode();
                    leaseApplyInfo.setCode(code);
                    leaseApplyInfo.setTaskId(task.getTaskId().intValue());
                    leaseApplyInfo.setCode(task.getLeaseApplyInfoList().get(0).getCode());
                    leaseApplyInfo.setLeasePerson(leasePerson);
                    leaseApplyInfo.setPhone(phone);
                    if (task.getTaskStatus() == 32 && task.getSouceByRefuse() == 1) {
                        leaseApplyInfo.setDeptAuditBy(task.getLeaseApplyInfoList().get(0).getDeptAuditBy());
                        leaseApplyInfo.setDeptAuditTime(task.getLeaseApplyInfoList().get(0).getDeptAuditTime());
                        leaseApplyInfo.setDeptAuditRemark(task.getLeaseApplyInfoList().get(0).getDeptAuditRemark());
                    }
                    leaseApplyInfo.setRemark(remark);
                    leaseApplyInfo.setType(task.getLeaseApplyInfoList().get(0).getType());
                    leaseApplyInfo.setCompanyId(leaseApplyDetail.getCompanyId());
                    leaseApplyInfo.setEstimateLeaseTime(task.getEstimateLeaseTime());
                    leaseApplyInfo.setLeaseType(task.getLeaseType());
                    res = leaseApplyInfoMapper.insert(leaseApplyInfo);
                }
            }
        }
        return res;
    }

    private int insertNewDetailData(TmTask task) {
        int res = 0;
        List<LeaseApplyDetails> leaseApplyDetails = task.getLeaseApplyDetails();
        Long taskId = task.getTaskId();
        if (CollUtil.isNotEmpty(leaseApplyDetails)) {
            for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                LeaseApplyInfo leaseApplyInfos = new LeaseApplyInfo();
                if (leaseApplyDetail.getCompanyId() == null) {
                    leaseApplyInfos = leaseApplyInfoMapper.selectByTaskIdAndCompIdCq(String.valueOf(taskId));
                } else {
                    leaseApplyInfos = leaseApplyInfoMapper.selectByTaskIdAndCompId(String.valueOf(taskId), leaseApplyDetail.getCompanyId());
                }
                Integer id = leaseApplyInfos.getId();
                if (leaseApplyDetail.getCompanyId() == null && leaseApplyInfos.getCompanyId() == null) {
                    leaseApplyDetail.setParenntId(id);
                    res = leaseApplyDetailsMapper.insert(leaseApplyDetail);
                } else if (leaseApplyDetail.getCompanyId().equals(leaseApplyInfos.getCompanyId())) {
                    leaseApplyDetail.setParenntId(id);
                    res = leaseApplyDetailsMapper.insert(leaseApplyDetail);
                }
            }
        }
        return res;
    }

    private int deletePreData(TmTask task) {
        Long taskId = task.getTaskId();
        return this.deleteLeaseInfoByTaskId(String.valueOf(taskId));
    }

    /**
     * @param task 查询条件
     * @return 协议的id
     */
    @Override
    public Integer getAgreementIdByUnit(TmTask task) {
        return tmTaskMapper.getAgreementIdByUnit(task);
    }

    /**
     * @param record 修改信息
     * @return 结果
     */
    @Override
    public int updateAgreementByTask(TmTask record) {
        return tmTaskMapper.updateAgreementByTask(record);
    }

    @Override
    public int updateByPrimaryKey(TmTask record) {
        return tmTaskMapper.updateByPrimaryKey(record);
    }

    @Override
    public int updateBatch(List<TmTask> list) {
        return tmTaskMapper.updateBatch(list);
    }

    @Override
    public int updateBatchSelective(List<TmTask> list) {
        return tmTaskMapper.updateBatchSelective(list);
    }

    @Override
    public int batchInsert(List<TmTask> list) {
        return tmTaskMapper.batchInsert(list);
    }

    @Override
    public int insertAgreement(TmTask record) {
        return tmTaskMapper.insertAgreement(record);
    }

    @Override
    public List<TmTask> getLeaseListAll(TmTask task) {
        List<TmTask> tmTaskList = new ArrayList<>();
        TmTask tmTask = tmTaskMapper.getLeaseListTmTask(task);
        Long companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();
        if (tmTask != null) {
            List<LeaseApplyInfo> leaseApplyInfoList = tmTaskMapper.getLeaseListByLeaseInfo(task);
            List<LeaseApplyInfo> leaseApplyInfoList2 = tmTaskMapper.getLeaseListByLeaseInfo(task);
            tmTask.setLeaseApplyInfoList(leaseApplyInfoList);

           /* List<LeaseApplyInfo> leaseApplyInfos = new ArrayList<>();
            leaseApplyInfos = ObjectUtil.clone(leaseApplyInfoList);*/
            List<LeaseApplyDetails> listLeaseDetails = new ArrayList<>();
            for (LeaseApplyInfo leaseApplyInfo : leaseApplyInfoList2) {
                if (leaseApplyInfo != null) {
                    Set<String> roles = SecurityUtils.getLoginUser().getRoles();
                    //如果是内部人员，加上所属公司
                    if (roles.contains("jjfgs") || roles.contains("sgb")) {
                        if (companyId != null) {
                            leaseApplyInfo.setCompanyId(companyId.intValue());
                        }
                    }
                    //如果是内部人员，加上所属公司
                    if (roles.contains("tsfgs") || roles.contains("ajb")) {
                        if (companyId != null) {
                            leaseApplyInfo.setCompanyId(companyId.intValue());
                        }

                    }
                    // 去查询领料任务详情表
                    List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyDetails(leaseApplyInfo);
                    if (leaseApplyDetails != null && !leaseApplyDetails.isEmpty()) {
                        listLeaseDetails.addAll(leaseApplyDetails);
                    }
                }
            }
            // 塞入领料任务详情的集合中
            tmTask.setLeaseApplyDetails(listLeaseDetails);
        }
        tmTaskList.add(tmTask);
        return tmTaskList;
    }

    @Override
    public List<TmTask> getLeaseApplyListAll(TmTask task) {
        List<TmTask> tmTaskList = new ArrayList<>();
        TmTask tmTask = tmTaskMapper.getLeaseListTmTask(task);
        List<LeaseApplyInfo> leaseApplyInfos = new ArrayList<>();
        if (tmTask != null) {
            List<LeaseApplyInfo> leaseApplyInfoList = tmTaskMapper.getLeaseListByLeaseInfo(task);
            if (task.getFlag() == 0) {
                for (LeaseApplyInfo applyInfo : leaseApplyInfoList) {
                    if ("2".equals(applyInfo.getStatus()) || "4".equals(applyInfo.getStatus()) || "6".equals(applyInfo.getStatus()) || "8".equals(applyInfo.getStatus()) || "10".equals(applyInfo.getStatus())) {
                        leaseApplyInfos.add(applyInfo);
                    }
                }
                tmTask.setLeaseApplyInfoList(leaseApplyInfoList);

                List<LeaseApplyDetails> listLeaseDetails = new ArrayList<>();
                for (LeaseApplyInfo leaseApplyInfo : leaseApplyInfos) {
                    if (leaseApplyInfo != null) {
                        // 去查询领料任务详情表
                        List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyDetailsByApply(leaseApplyInfo);
                        if (leaseApplyDetails != null && !leaseApplyDetails.isEmpty()) {
                            leaseApplyInfo.setLeaseApplyDetails(leaseApplyDetails);
                            listLeaseDetails.addAll(leaseApplyDetails);
                        }
                    }
                }
                // 塞入领料任务详情的集合中
                tmTask.setLeaseApplyDetails(listLeaseDetails);
            }

            if (task.getFlag() == 1) {
                tmTask.setLeaseApplyInfoList(leaseApplyInfoList);

                List<LeaseApplyDetails> listLeaseDetails = new ArrayList<>();
                for (LeaseApplyInfo leaseApplyInfo : leaseApplyInfoList) {
                    if (leaseApplyInfo != null) {
                        // 去查询领料任务详情表
                        List<LeaseApplyDetails> leaseApplyDetails = tmTaskMapper.getLeaseApplyDetailsByApply(leaseApplyInfo);
                        if (leaseApplyDetails != null && !leaseApplyDetails.isEmpty()) {
                            leaseApplyInfo.setLeaseApplyDetails(leaseApplyDetails);
                            listLeaseDetails.addAll(leaseApplyDetails);
                        }
                    }
                }
                // 塞入领料任务详情的集合中
                tmTask.setLeaseApplyDetails(listLeaseDetails);
            }
        }
        tmTaskList.add(tmTask);
        return tmTaskList;
    }

    @Override
    public void updateLeaseInfo(LeaseApplyInfo task) {
        tmTaskMapper.updateLeaseInfo(task);
    }

    @Override
    public List<LeaseApplyInfo> getListSome(Long taskId) {
        return tmTaskMapper.getListSome(taskId);
    }

    @Override
    public LeaseApplyInfo getListSomeol(LeaseApplyInfo info) {
        return tmTaskMapper.getListSomeol(info);
    }
}