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

import cn.hutool.core.collection.CollectionUtil;
import com.bonus.common.biz.constant.GlobalConstants;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.domain.BmFileInfo;
import com.bonus.common.biz.domain.LeaseRecordInfo;
import com.bonus.common.biz.domain.lease.*;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.biz.enums.LeaseTaskStatusEnum;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.bean.BeanUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.back.domain.vo.MaCodeVo;
import com.bonus.material.basic.domain.BmAgreementInfo;
import com.bonus.material.basic.domain.BmProject;
import com.bonus.material.basic.domain.dto.SysUserRoleVo;
import com.bonus.material.basic.mapper.BmAgreementInfoMapper;
import com.bonus.material.basic.mapper.BmFileInfoMapper;
import com.bonus.material.basic.mapper.BmUserRoleMapper;
import com.bonus.material.clz.domain.BmTeam;
import com.bonus.material.clz.domain.vo.IwsTeamUserVo;
import com.bonus.material.clz.mapper.BmTeamMapper;
import com.bonus.material.clz.mapper.IwsTeamUserMapper;
import com.bonus.material.lease.domain.LeaseApplyDetails;
import com.bonus.material.lease.domain.LeasePublishDetails;
import com.bonus.material.lease.domain.vo.LeaseApplyRequestVo;
import com.bonus.material.lease.domain.vo.LeaseDeptInfo;
import com.bonus.material.lease.mapper.LeaseApplyDetailsMapper;
import com.bonus.material.lease.mapper.LeaseApplyInfoMapper;
import com.bonus.material.lease.mapper.LeaseTaskMapper;
import com.bonus.material.lease.service.ILeaseTaskService;
import com.bonus.material.ma.domain.Type;
import com.bonus.material.ma.domain.vo.MaTypeVoLevelTwo;
import com.bonus.material.ma.service.ITypeService;
import com.bonus.material.task.domain.TmTask;
import com.bonus.material.task.domain.TmTaskAgreement;
import com.bonus.material.task.mapper.TmTaskAgreementMapper;
import com.bonus.material.task.mapper.TmTaskMapper;
import com.bonus.material.work.domain.SysWorkflowConfig;
import com.bonus.material.work.domain.SysWorkflowNode;
import com.bonus.material.work.domain.SysWorkflowRecordHistory;
import com.bonus.material.work.mapper.*;
import com.bonus.material.work.service.SysWorkflowRecordService;
import com.bonus.system.api.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.UriComponentsBuilder;

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

/**
 * @author hay
 * @description 业务办理--领用任务
 * @date 2025/2/17 13:16
 */
@Service
@Slf4j
public class LeaseTaskServiceImpl implements ILeaseTaskService {

    @Resource
    private LeaseTaskMapper mapper;

    @Resource
    private LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private LeaseApplyDetailsMapper leaseApplyDetailsMapper;

    @Resource
    private TmTaskMapper tmTaskMapper;

    @Resource
    TmTaskAgreementMapper tmTaskAgreementMapper;

    @Resource
    private BmFileInfoMapper bmFileInfoMapper;

    @Resource
    private SysWorkflowRecordService sysWorkflowRecordService;

    @Resource
    private SysWorkflowConfigMapper sysWorkflowConfigMapper;

    @Resource
    private SysWorkflowRecordHistoryMapper sysWorkflowRecordHistoryMapper;

    @Resource
    private SysWorkflowNodeMapper sysWorkflowNodeMapper;

    @Resource
    private BmUserRoleMapper bmUserRoleMapper;

    @Resource
    private BmAgreementInfoMapper bmAgreementInfoMapper;

    @Resource
    private IwsTeamUserMapper iwsTeamUserMapper;

    @Resource
    private BmTeamMapper bmTeamMapper;

    @Resource
    private ITypeService typeService;


    /**
     * 新增领用任务
     *
     * @param leaseApplyRequestVo 领用任务
     * @return 结果
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertLeaseApplyInfo(LeaseApplyRequestVo leaseApplyRequestVo) {
        if (null == leaseApplyRequestVo.getLeaseApplyInfo()) {
            return AjaxResult.error("请先填写领用任务信息");
        }
        if (CollectionUtil.isEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
            return AjaxResult.error("请先添加领用任务物资明细");
        }
        // 根据单号查询此单号是否已经存在
        List<LeaseApplyInfo> codeInfo = tmTaskMapper.selectLeaseApplyInfoByTaskNo(leaseApplyRequestVo.getLeaseApplyInfo().getCode());
        if (CollectionUtil.isNotEmpty(codeInfo)) {
            return AjaxResult.error("此业务单号已经存在,请叉掉后重新提交");
        }
        LeaseApplyInfo leaseApplyInfo = leaseApplyRequestVo.getLeaseApplyInfo();
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        Date nowDate = DateUtils.getNowDate();

        leaseApplyInfo.setCreateTime(nowDate);
        leaseApplyInfo.setCreateBy(sysUser.getNickName());
        leaseApplyInfo.setTaskDeptId(sysUser.getDeptId());

        Long userId = sysUser.getUserId();
        Long deptId = mapper.getDeptIdByUserId(userId);

        String deptName = "";
        LeaseDeptInfo leaseDeptInfo = new LeaseDeptInfo();
        Long parentIdTemp = deptId;
        final int MAX_LOOP = 10;

        int loopCount = 0;
        while (loopCount++ < MAX_LOOP) {
            leaseDeptInfo = mapper.getDeptIdByParentId(parentIdTemp);
            if (leaseDeptInfo == null) {
                break;
            }

            String ancestors = leaseDeptInfo.getAncestors();
            if (StringUtils.isNotBlank(ancestors)) {
                int commaCount = StringUtils.countMatches(ancestors, ",");
                if (commaCount < 1) {
                    break;
                } else if (commaCount == 1) {
                    deptName = leaseDeptInfo.getDeptName();
                    break;
                }
            }
            parentIdTemp = leaseDeptInfo.getParentId();
        }

        if (!"".equals(deptName)) {
            leaseApplyInfo.setCompanyId(leaseDeptInfo.getDeptId());
        }

        try {
            Integer statusFlag = leaseApplyRequestVo.getStatusFlag();
            Integer taskStatus = (statusFlag != null && statusFlag == 0)
                    ? LeaseTaskStatusEnum.LEASE_TASK_ZERO.getStatus()
                    : LeaseTaskStatusEnum.LEASE_TASK_SUBMIT.getStatus();

            int thisMonthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(
                    DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(),
                    TmTaskTypeEnum.TM_TASK_LEASE_APPLY.getTaskTypeId());

            String taskCode = leaseApplyInfo.getCode();
            TmTask tmTask = new TmTask(null,
                    TmTaskTypeEnum.TM_TASK_LEASE_APPLY.getTaskTypeId(),
                    taskStatus,
                    leaseApplyInfo.getCompanyId(), thisMonthMaxOrder + 1, taskCode);

            tmTask.setCreateTime(nowDate);
            tmTask.setCreateBy(sysUser.getNickName());
            tmTask.setTaskDeptId(sysUser.getDeptId());

            tmTaskMapper.insertTmTask(tmTask);
            leaseApplyInfo.setTaskId(tmTask.getTaskId());
            leaseApplyInfo.setCode(taskCode);
            BmAgreementInfo bmAgreementInfo = new BmAgreementInfo();
            bmAgreementInfo.setUnitId(leaseApplyInfo.getUnitId());
            bmAgreementInfo.setProjectId(leaseApplyInfo.getProjectId());
            List<BmAgreementInfo> bmAgreementInfos = bmAgreementInfoMapper.selectBmAgreementInfoList(bmAgreementInfo);
            if (!CollectionUtils.isEmpty(bmAgreementInfos)) {
                bmAgreementInfo = bmAgreementInfos.get(0);
                TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask.getTaskId(), bmAgreementInfo.getAgreementId());
                tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
                tmTaskAgreement.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                tmTaskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);
            }
            // 设置审批人为默认的董班长
            Long peopleId = leaseApplyInfoMapper.getDirectAuditBy();
            leaseApplyInfo.setDirectAuditBy(peopleId);

            int count = mapper.insertLeaseApplyInfo(leaseApplyInfo);

            handleBmFileInfos(leaseApplyInfo, sysUser, nowDate, tmTask);

            int newId = 0;
            if (statusFlag != null && statusFlag == 0) {
                newId = sysWorkflowRecordService.addSysWorkflowRecord(tmTask.getTaskId().intValue(), taskCode, 19);
            }
            // 根据传入的工程id，查询班组信息，进行数据同步
            BmProject bmProject = mapper.selectById(leaseApplyInfo);
            if (bmProject != null && StringUtils.isNotBlank(bmProject.getExternalId())) {
                List<String> ids = Collections.singletonList(bmProject.getExternalId());
                List<IwsTeamUserVo> iwsTeamUserVos = iwsTeamUserMapper.selectProjectTeamInfoByProjectIds(ids);
                if (!CollectionUtils.isEmpty(iwsTeamUserVos)) {
                    for (IwsTeamUserVo iwsTeamUserVo : iwsTeamUserVos) {
                        BmTeam bmTeam = new BmTeam();
                        bmTeam.setTeamName(StringUtils.isNotBlank(iwsTeamUserVo.getTeamName()) ? iwsTeamUserVo.getTeamName() : null);
                        bmTeam.setCreateUser(SecurityUtils.getLoginUser().getUserid().toString());
                        bmTeam.setRelName(StringUtils.isNotBlank(iwsTeamUserVo.getRelName()) ? iwsTeamUserVo.getRelName() : null);
                        bmTeam.setIdCard(StringUtils.isNotBlank(iwsTeamUserVo.getTeamLeaderIdCard()) ? iwsTeamUserVo.getTeamLeaderIdCard() : null);
                        bmTeam.setProjectId(StringUtils.isNotBlank(iwsTeamUserVo.getProjectId()) ? iwsTeamUserVo.getProjectId() : null);
                        bmTeam.setRelPhone(StringUtils.isNotBlank(iwsTeamUserVo.getRelPhone()) ? iwsTeamUserVo.getRelPhone() : null);
                        // 班组类型固定传值
                        bmTeam.setTypeId(1731L);
                        // 根据班组名称去bm_unit表查询班组信息
                        BmTeam bmTeam1 = bmTeamMapper.selectByName(bmTeam);
                        if (bmTeam1 == null) {
                            // 走新增逻辑
                            int result = bmTeamMapper.insert(bmTeam);
                            if (result <= 0) {
                                return AjaxResult.error(HttpCodeEnum.UPDATE_TO_DATABASE.getCode(), HttpCodeEnum.UPDATE_TO_DATABASE.getMsg());
                            }
                        }
                    }
                }
            }
            if (count > 0) {
                if (statusFlag != null && statusFlag == 0) {
                    createWorkOrderAndPeople(sysUser, leaseApplyInfo, tmTask, newId);
                }
                return insertPurchaseCheckDetails(leaseApplyRequestVo.getLeaseApplyDetailsList(), leaseApplyInfo.getId());
            } else {
                return AjaxResult.error("新增任务失败,lease_apply_info表插入0条");
            }
        } catch (DataAccessException e) {
            throw new RuntimeException("数据库操作失败", e);
        } catch (Exception e) {
            throw new RuntimeException("新增任务失败", e);
        }
    }

    private void handleBmFileInfos(LeaseApplyInfo leaseApplyInfo, SysUser sysUser, Date nowDate, TmTask tmTask) {
        if (!CollectionUtils.isEmpty(leaseApplyInfo.getBmFileInfos())) {
            String createBy = sysUser.getNickName();
            Long taskId = tmTask.getTaskId();
            Long modelId = leaseApplyInfo.getId();
            leaseApplyInfo.getBmFileInfos().forEach(bmFileInfo -> {
                bmFileInfo.setTaskType(2);
                bmFileInfo.setTaskId(taskId);
                bmFileInfo.setModelId(modelId);
                bmFileInfo.setFileType(5L);
                bmFileInfo.setCreateBy(createBy);
                bmFileInfo.setCreateTime(nowDate);
                bmFileInfoMapper.insertBmFileInfo(bmFileInfo);
            });
        }
    }

    private void createWorkOrderAndPeople(SysUser sysUser, LeaseApplyInfo leaseApplyInfo, TmTask tmTask, int newId) {
        //获取工程名称
        String projectName = mapper.getProjectNameById(leaseApplyInfo.getProjectId());
        leaseApplyInfo.setProjectName(projectName);
        String id = UUID.randomUUID().toString().replace("-", "");
        String webUrlBase = "/mea-h5/#/pages/picking/review/details";
        String queryParams = UriComponentsBuilder.newInstance()
                .queryParam("appId", "9fa73f046ef520b09e94bbffc3b07702")
                .queryParam("taskId", tmTask.getTaskId())
                .queryParam("id", leaseApplyInfo.getId())
                .build().encode().toUriString();

        WorkApplyInfo workApplyInfo = new WorkApplyInfo();
        workApplyInfo.setId(id);
        workApplyInfo.setTitle("智能机具-领料申请待审核");
        workApplyInfo.setCreateUserName(sysUser.getUserName());
        workApplyInfo.setContent(sysUser.getNickName() + ":" + leaseApplyInfo.getCode() + "-" + leaseApplyInfo.getProjectName());
        workApplyInfo.setType(1);
        workApplyInfo.setWebAppId("9fa73f046ef520b09e94bbffc3b07702");
        workApplyInfo.setSendUserName(sysUser.getUserName());
        workApplyInfo.setTypeId(2025050801);
        workApplyInfo.setBusinessId(String.valueOf(newId));
        workApplyInfo.setNextStatus("待审核");
        workApplyInfo.setFlowState(null);
        workApplyInfo.setWebUrl(webUrlBase + queryParams);
        workApplyInfo.setRout(webUrlBase + queryParams);

        int countWork = mapper.insertWorkOrder(workApplyInfo);
        if (countWork > 0) {

            //查询审批人集合
            WorkPeopleInfo info = new WorkPeopleInfo();
            info.setFlowId(newId);

            List<WorkPeopleInfo> workPeopleInfoList = mapper.selectWorkPeopleInfoList(info.getFlowId());

            if(workPeopleInfoList != null && workPeopleInfoList.size() > 0){
                WorkPeopleInfo person = workPeopleInfoList.get(0);
                String roleIds = person.getRoleIds();
                String[] roleIdArray = roleIds.split(",");
                long deptId = sysUser.getDeptId();
                //根据角色和部门查询用户集合
                WorkPeopleInfo param = new WorkPeopleInfo();
                param.setRoleIdArray(roleIdArray);
                param.setDeptId(deptId);
                List<WorkPeopleInfo> userList = mapper.selectUserListByRoleAndDept(param);
                for (WorkPeopleInfo user : userList) {
                    WorkPeopleInfo workPeopleInfo = new WorkPeopleInfo();
                    workPeopleInfo.setId(UUID.randomUUID().toString().replace("-", ""));
                    workPeopleInfo.setInformationId(id);
                    workPeopleInfo.setReceiverUsername(user.getReceiverUsername());
                    workPeopleInfo.setReadState(0);
                    workPeopleInfo.setHandleState(0);
                    workPeopleInfo.setIsExamine(0);
                    mapper.insertWorkPeople(workPeopleInfo);
                }

            }
        }
    }



    /**
     * 领用记录列表查询
     *
     * @param leaseApplyInfo 领用任务
     * @return 领用任务
     */
    @Override
    public List<LeaseApplyInfo> selectLeaseApplyInfoList(LeaseApplyInfo leaseApplyInfo) {
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        leaseApplyInfo.setDeptId(deptId == 0 ? null : deptId);
        Long userId = SecurityUtils.getLoginUser().getUserid();
        leaseApplyInfo.setUserId(userId == 1 ? null : userId);
        if(userId == 1 || deptId == 101 || deptId == 345) {
            leaseApplyInfo.setDeptId(null);
        } else {
            //判断祖籍有没有101
            String ancestors = mapper.getAncestors(deptId);
            boolean contains101 = false;
            if (ancestors != null && !ancestors.isEmpty()) {
                String[] parts = ancestors.split(",");
                for (String part : parts) {
                    if ("101".equals(part.trim())) {
                        contains101 = true;
                        break;
                    }
                }
            }
            if(contains101){
                leaseApplyInfo.setDeptId(null);
            } else {
                leaseApplyInfo.setDeptId(deptId);
            }
        }
        List<LeaseApplyInfo> list = mapper.selectLeaseApplyInfoList(leaseApplyInfo);
        if (!CollectionUtils.isEmpty(list)) {
            for (LeaseApplyInfo applyInfo : list) {
                // 根据任务id查询sys_workflow_record表，看任务是否已经开始，修改tm_task表状态为审核中
                Integer status = mapper.selectStatusByTaskId(applyInfo.getTaskId());
                if (status != null && status == 1) {
                    applyInfo.setTaskStatus(LeaseTaskStatusEnum.LEASE_AUDIT_ING.getStatus());
                    applyInfo.setTaskStatusName(LeaseTaskStatusEnum.LEASE_AUDIT_ING.getStatusName());
                    mapper.updateLeaseTaskStatus(applyInfo.getTaskId(), LeaseTaskStatusEnum.LEASE_AUDIT_ING.getStatus());
                }
            }
            Integer taskStatus = leaseApplyInfo.getTaskStatus();
            String keyWord = leaseApplyInfo.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                list = list.stream()
                        .filter(item -> containsKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }

            if(leaseApplyInfo.getIsApp() == null) {
                if (taskStatus != null) {
                    // 如果taskStatus为3，则查询list中状态为1和3的数据
                    if (taskStatus.equals(3)) {
                        list = list.stream()
                                .filter(item -> item.getTaskStatus().equals(1) || item.getTaskStatus().equals(3))
                                .collect(Collectors.toList());
                    } else {
                        list = list.stream()
                                .filter(item -> item.getTaskStatus().equals(taskStatus))
                                .collect(Collectors.toList());
                    }
                }
            }

        }
        return list;
    }

    /**
     * 根据id查询领用任务
     *
     * @param id 领用任务id
     * @return 领用任务
     */
    @Override
    public LeaseApplyRequestVo selectLeaseApplyInfoById(Long id, String keyWord) {
        try {
            LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
            leaseApplyInfo.setId(id);
            Long userId = SecurityUtils.getLoginUser().getUserid();
            leaseApplyInfo.setUserId(userId);
            Optional<LeaseApplyInfo> optionalInfo = Optional.ofNullable(mapper.selectLeaseApplyInfoById(leaseApplyInfo));
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();

            optionalInfo.ifPresent(info -> {
                BmFileInfo bmFileInfo = new BmFileInfo();
                bmFileInfo.setModelId(id);
                bmFileInfo.setTaskType(2);
                bmFileInfo.setFileType(5L);
                List<BmFileInfo> bmFileInfoList = bmFileInfoMapper.selectBmFileInfoList(bmFileInfo);
                if (!CollectionUtils.isEmpty(bmFileInfoList)) {
                    info.setBmFileInfos(bmFileInfoList);
                }
                /** 设置审批人签名url  防止代码冲突  **/
                String directAuditUrl =   leaseApplyInfoMapper.getDirectAuditUrl(info);
                info.setDirectAuditSignUrl(directAuditUrl);
                /** 设置审批人签名url  防止代码冲突  **/

                /** 设置发料单位  防止代码冲突  **/
                if(info.getDirectAuditBy() != null){
                    String sendUnit =   leaseApplyInfoMapper.getSendUnit(info);
                    info.setSendUnit(sendUnit);
                }
                /** 设置发料单位  防止代码冲突  **/

                leaseApplyRequestVo.setLeaseApplyInfo(info);
                // 获取领料单详情
                List<LeaseApplyDetails> details = mapper.selectLeaseApplyDetailsList(new LeaseApplyDetails(info.getId(), keyWord, userId, null));
                if (!CollectionUtils.isEmpty(details)) {
                    leaseApplyRequestVo.setLeaseApplyDetailsList(details);
                    for (LeaseApplyDetails detail : details) {
                        // 获取编码详情
                        List<MaCodeVo> maCodeVoList = leaseApplyDetailsMapper.getCodeList(id, detail.getTypeId());
                        if (!CollectionUtils.isEmpty(maCodeVoList)) {
                            detail.setMaCodeVoList(maCodeVoList);
                        }
                    }
                }

            });

            return leaseApplyRequestVo;
        } catch (Exception e) {
            // 记录异常日志
            System.err.println("Error occurred while selecting lease apply info by ID: " + id + e.getMessage());
            throw new RuntimeException("Failed to select lease apply info", e);
        }
    }

    /**
     * 生成采购申请编号
     *
     */
    @Override
    public LeaseDeptInfo getCode() {
        try {
            Long userId = SecurityUtils.getLoginUser().getUserid();
            Long deptId =  mapper.getDeptIdByUserId(userId);
            LeaseDeptInfo leaseDeptInfo = new LeaseDeptInfo();
            leaseDeptInfo = mapper.getDeptIdByParentId(deptId);
            Long parentIdTemp =  leaseDeptInfo.getParentId();
            String deptName = "";
            String taskCode = "";
            while (leaseDeptInfo != null) {
                parentIdTemp = leaseDeptInfo.getParentId();
                String ancestors = leaseDeptInfo.getAncestors();
                if (ancestors != null && StringUtils.countMatches(ancestors, ",") < 1) {
                    break;
                }
                if (ancestors != null && StringUtils.countMatches(ancestors, ",") == 1) {
                    deptName = leaseDeptInfo.getDeptName();
                    break;
                }
                leaseDeptInfo = mapper.getDeptIdByParentId(parentIdTemp);
            }
            if(!deptName.equals("")){
                int thisMonthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_LEASE_APPLY.getTaskTypeId());
                int lzThisMonthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
                if (StringUtils.isBlank(leaseDeptInfo.getCompanySX())) {
                    thisMonthMaxOrder = Math.max(thisMonthMaxOrder, lzThisMonthMaxOrder);
                }
                 taskCode = genderTaskCodeTwo(thisMonthMaxOrder,leaseDeptInfo.getCompanySX());
                 leaseDeptInfo.setTaskCode(taskCode);
            }
            return leaseDeptInfo;
        } catch (DataAccessException dae) {
            throw new ServiceException("数据访问异常: " + dae.getMessage());
        }
    }

    @Override
    public boolean updateLeaseApplyInfo(LeaseApplyRequestVo leaseApplyRequestVo) {
        try {
            // 提取到局部变量中，减少重复代码
            LeaseApplyInfo leaseApplyInfo = leaseApplyRequestVo.getLeaseApplyInfo();
            // 根据状态标志选择合适的状态
            Integer statusFlag = leaseApplyRequestVo.getStatusFlag();
            Integer taskStatus;
            if (statusFlag != null && statusFlag == 0) {
                taskStatus = LeaseTaskStatusEnum.LEASE_TASK_ZERO.getStatus();
            } else {
                taskStatus = LeaseTaskStatusEnum.LEASE_TASK_SUBMIT.getStatus();
            }

            if (leaseApplyInfo != null && leaseApplyInfo.getId() != null) {
                leaseApplyInfo.setUpdateTime(DateUtils.getNowDate());
                leaseApplyInfo.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                //修改任务状态
               mapper.updateLeaseTaskStatus(leaseApplyInfo.getTaskId(),taskStatus);


                // 去除创建一个新的数组对象，直接复用
                Long[] ids = {leaseApplyInfo.getId()};
                if (CollectionUtil.isNotEmpty(leaseApplyInfo.getBmFileInfos())) {
                    // 删除原有数据
                    BmFileInfo bmFileInfo = new BmFileInfo();
                    bmFileInfo.setTaskId(leaseApplyInfo.getTaskId());
                    bmFileInfo.setModelId(leaseApplyInfo.getId());
                    bmFileInfo.setTaskType(2);
                    bmFileInfo.setFileType(5L);
                    bmFileInfoMapper.deleteBmFileInfoByBizInfo(bmFileInfo);
                    for (BmFileInfo fileInfo : leaseApplyInfo.getBmFileInfos()) {
                        fileInfo.setTaskId(leaseApplyInfo.getTaskId());
                        fileInfo.setModelId(leaseApplyInfo.getId());
                        fileInfo.setTaskType(2);
                        fileInfo.setFileType(5L);
                        fileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                        fileInfo.setCreateTime(DateUtils.getNowDate());
                        bmFileInfoMapper.insertBmFileInfo(fileInfo);
                    }
                }
                if (CollectionUtil.isNotEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
                    // 业务逻辑代码
                    leaseApplyDetailsMapper.deleteLeaseApplyDetailsByParentIds(ids);
                    insertPurchaseCheckDetails(leaseApplyRequestVo.getLeaseApplyDetailsList(), leaseApplyInfo.getId());
                }
                TmTask tmTask = tmTaskMapper.selectTmTaskByTaskId(leaseApplyInfo.getTaskId());
                if (statusFlag == 0) {
                    // 判断该任务是否已经在sys_workflow_record表中创建
                    int result = sysWorkflowRecordService.selectSysWorkflowRecordByTaskId(leaseApplyInfo);
                    if (result == 0) {
                        sysWorkflowRecordService.addSysWorkflowRecord(leaseApplyInfo.getTaskId().intValue(), tmTask.getCode(), 19);
                    }
                }
                // 修改外层info
                leaseApplyInfo.setCode(tmTask.getCode());
                mapper.updateLeaseApplyInfo(leaseApplyInfo);
                return true;
            }
            return false;
        } catch (DataAccessException dae) {
            throw new ServiceException("数据访问异常: " + dae.getMessage());
        } catch (IllegalArgumentException iae) {
            throw new ServiceException("非法参数异常: " + iae.getMessage());
        } catch (Exception e) {
            throw new ServiceException("未知异常: " + e.getMessage());
        }
    }

    /**
     * 批量删除领用任务
     *
     * @param ids 需要删除的领用任务主键
     * @return 结果
     */
    @Override
    public int deleteLeaseApplyInfoByIds(Long[] ids) {
        return leaseApplyInfoMapper.deleteLeaseApplyInfoByIds(ids);
    }

    @Override
    public List<Type> getTypeDataList(Type bean) {
        return mapper.getTypeDataList(bean);
    }

    @Override
    public List<LeaseApplyInfo> selectAuditLeaseApplyInfoList(LeaseApplyInfo leaseApplyInfo) {
        Long userId = SecurityUtils.getLoginUser().getUserid();
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        leaseApplyInfo.setUserId(userId == 1 ? null : userId);
        if(userId == 1 || deptId == 101){
            leaseApplyInfo.setDeptId(null);
        }else{
            //判断祖籍有没有101
            String ancestors = mapper.getAncestors(deptId);
            boolean contains101 = false;
            if (ancestors != null && !ancestors.isEmpty()) {
                String[] parts = ancestors.split(",");
                for (String part : parts) {
                    if ("101".equals(part.trim())) {
                        contains101 = true;
                        break;
                    }
                }
            }
            if(contains101){
                leaseApplyInfo.setDeptId(null);
            }else{
                leaseApplyInfo.setDeptId(deptId);
            }
        }

//        leaseApplyInfo.setDeptId((userId == 1 || deptId == 101) ? null : deptId);
        log.info("用户id为{}",userId);
        List<LeaseApplyInfo> list = mapper.selectAuditLeaseApplyInfoList(leaseApplyInfo);
        try {
            if (!CollectionUtils.isEmpty(list)) {
                String keyWord = leaseApplyInfo.getKeyWord();
                // 如果关键字不为空，进行过滤
                if (!StringUtils.isBlank(keyWord)) {
                    list = list.stream()
                            .filter(item -> containsKeyword(item, keyWord))
                            .collect(Collectors.toList());
                }
            }
            for (LeaseApplyInfo leaseApplyInfoNew : list) {
                //获取当前节点，并根据当前节点获取审核人审核的角色信息
                if (leaseApplyInfoNew.getNodeId() != null) {
                    log.info("当前节点为{}",leaseApplyInfoNew.getNodeId());
                    SysWorkflowRecordHistory sysWorkflowRecordHistory = sysWorkflowRecordHistoryMapper.getWorkflowRecordHistoryByRecordId(leaseApplyInfoNew.getRecordId());
                    leaseApplyInfoNew.setNodeId(sysWorkflowRecordHistory.getNodeId());
                    //设置当前节点
                    if (1==leaseApplyInfoNew.getNodeSignType() && sysWorkflowRecordHistory.getNodeSort()==1){
                        leaseApplyInfoNew.setNodeId(sysWorkflowRecordHistory.getNextNodeId());
                    }
                    String configValue = sysWorkflowConfigMapper.selectConfigValueByNodeId(leaseApplyInfoNew.getNodeId());
                    SysWorkflowNode sysWorkflowNode = sysWorkflowNodeMapper.selectSysWorkflowNodeById(leaseApplyInfoNew.getNodeId());
                    leaseApplyInfoNew.setConfigValue(configValue);
                    //判断当前节点是否审核
                    sysWorkflowRecordHistory.setRecordId(leaseApplyInfoNew.getRecordId());
                    sysWorkflowRecordHistory.setNodeId(leaseApplyInfoNew.getNodeId());
                    List<SysWorkflowRecordHistory> SysWorkflowRecordHistoryList = sysWorkflowRecordHistoryMapper.seleteSysWorkflowRecordHistory(sysWorkflowRecordHistory);
                    //判断是或签还是会签0:或签  1:会签
                    if (0==sysWorkflowNode.getNodeSignType()){
                        //当前节点已经审核需要修改节点值
                        if (SysWorkflowRecordHistoryList.get(0) != null) {
                            // 固定的人员id 修改成 判断人员/角色 如果是人员的话要进行二次查询
//                            String configValueNew = sysWorkflowConfigMapper.selectConfigValueByNodeId(SysWorkflowRecordHistoryList.get(0).getNextNodeId());
//                            leaseApplyInfoNew.setNodeId(SysWorkflowRecordHistoryList.get(0).getNextNodeId());
//                            leaseApplyInfoNew.setConfigValue(configValueNew);
                            SysWorkflowConfig nextNodeConfigValueInfoNew = sysWorkflowConfigMapper.selectConfigValueInfoByNodeId(SysWorkflowRecordHistoryList.get(0).getNextNodeId());
                            if (nextNodeConfigValueInfoNew != null) {
                                leaseApplyInfoNew.setNodeId(SysWorkflowRecordHistoryList.get(0).getNextNodeId());
                                // 0:角色  1:用户
                                if (nextNodeConfigValueInfoNew.getConfigType() == 1) {
                                    leaseApplyInfoNew.setConfigValue(nextNodeConfigValueInfoNew.getConfigValue());
                                } else if (nextNodeConfigValueInfoNew.getConfigType() == 0) {
                                    if (nextNodeConfigValueInfoNew.getRoleIds() != null) {
                                        String[] roleIds = nextNodeConfigValueInfoNew.getRoleIds().split(",");
                                        List<Long> configUserIds = new ArrayList<>();
                                        for (String roleId : roleIds) {
                                            if (roleId == null || roleId.isEmpty()) {
                                                continue;
                                            }
                                            List<SysUserRoleVo> userRoleList = bmUserRoleMapper.getUserRoleListByDeptId(SecurityUtils.getLoginUser().getSysUser().getDeptId(), Long.valueOf(roleId));
                                            if (!userRoleList.isEmpty()) {
                                                configUserIds.addAll(
                                                        userRoleList.stream().filter(Objects::nonNull).map(SysUserRoleVo::getUserId).collect(Collectors.toList())
                                                );
                                            }
                                        }
                                        leaseApplyInfoNew.setConfigValue(configUserIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
                                    }
                                }
                            }
                        }
                    } else {
                        String[] ConfigValue =  configValue.split(",");
                        List<String> filteredList = Arrays.stream(ConfigValue).collect(Collectors.toList());
                        for (SysWorkflowRecordHistory sysWorkflowRecordHistoryNew : SysWorkflowRecordHistoryList) {
                            if (sysWorkflowRecordHistoryNew!=null){
                                // 过滤数组元素
                                filteredList = filteredList.stream()
                                        .filter(value ->value != null && !value.equals(sysWorkflowRecordHistoryNew.getCreateBy()))
                                        .collect(Collectors.toList());
                                leaseApplyInfoNew.setConfigValue(filteredList.toString());
                            }
                        }
                        //判断是否这个节点的所有人都审核
                        if (filteredList.isEmpty()){
                            String configValueNew = sysWorkflowConfigMapper.selectConfigValueByNodeId(SysWorkflowRecordHistoryList.get(0).getNextNodeId());
                            leaseApplyInfoNew.setNodeId(SysWorkflowRecordHistoryList.get(0).getNextNodeId());
                            leaseApplyInfoNew.setConfigValue(configValueNew);
                        }else {
                            if (!SysWorkflowRecordHistoryList.isEmpty()){
                                leaseApplyInfoNew.setNodeId(leaseApplyInfoNew.getNodeId());
                                leaseApplyInfoNew.setConfigValue(filteredList.toString());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("查询失败",e.getMessage());
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 关键字搜索
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(LeaseApplyInfo item, String keyWord) {
        return (item.getMaTypeNames() != null && item.getMaTypeNames().contains(keyWord)) ||
                (item.getLeaseUnit() != null && item.getLeaseUnit().contains(keyWord)) ||
                (item.getLeaseProject() != null && item.getLeaseProject().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord)) ||
                (item.getCreateBy() != null && item.getCreateBy().contains(keyWord)) ||
                (item.getLeasePerson() != null && item.getLeasePerson().contains(keyWord)) ||
                (item.getLeasePhone() != null && item.getLeasePhone().contains(keyWord)) ||
                (item.getImpUnitName() != null && item.getImpUnitName().contains(keyWord));
    }


    private AjaxResult insertPurchaseCheckDetails(List<LeaseApplyDetails> leaseApplyDetailsList, Long parentId) {
        if (!CollectionUtils.isEmpty(leaseApplyDetailsList)) {
            for (LeaseApplyDetails details : leaseApplyDetailsList) {
                details.setParentId(parentId);
                details.setCreateTime(DateUtils.getNowDate());
                details.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                // 将 maTypeIds 数组转换为用逗号分隔的字符串
                if (details.getMaTypeIds() != null && details.getMaTypeIds().length > 0) {
                    String maType = Arrays.stream(details.getMaTypeIds())
                            .mapToObj(String::valueOf)
                            .collect(Collectors.joining(","));
                    details.setMaTypeIdsStr(maType);
                } else {
                    details.setMaTypeIdsStr("");
                }
            }
            // 批量插入详情数据
            int count = mapper.insertLeaseApplyDetailsList(leaseApplyDetailsList);
            if (count > 0) {
                return AjaxResult.success("新增任务成功");
            } else {
                return AjaxResult.error("新增任务失败,lease_apply_detail详情表插入0条");
            }
        } else {
            return AjaxResult.success("新增任务成功");
        }
    }

    /**
     * 生成任务编号并构造Tm_Task任务对象
     * @param thisMonthMaxOrder 当月最大单号
     * @return 任务对象
     */
    private static String genderTaskCode(Integer thisMonthMaxOrder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        return MaterialConstants.LEASE_TASK_TYPE_LABEL + result + String.format("-%05d", thisMonthMaxOrder + 1);
    }
    private static String genderTaskCodeTwo(Integer thisMonthMaxOrder,String deptName) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        if(deptName!=null && !"".equals(deptName)){
            return deptName + result + String.format("-%05d", thisMonthMaxOrder + 1);
        }else{
            return MaterialConstants.LEASE_TASK_TYPE_LABEL + result + String.format("-%05d", thisMonthMaxOrder + 1);
        }
    }

    @Override
    public List<Type> getEquipmentThreeTypes() {
        List<Type> maTypes = mapper.selectMaTypeThreeLists();
        List<Type> list = new ArrayList<>();
        for (Type maType : maTypes) {
            if (maType.getParentId() == 0) {
                list.add(maType);
            }
        }
        //根据父节点获取对应的儿子节点
        for (Type maType : list) {
            List<Type> child = getChild(maTypes, maType.getTypeId());
            maType.setChildren(child);
        }
        return list;
    }

    /**
     * 递归调用获取子级
     * @param list 集合
     * @param parentId 父级id
     */
    public List<Type> getChild(List<Type> list, Long parentId) {
        List<Type> childList = new ArrayList<Type>();
        for (Type maType : list) {
            Long typeId = maType.getTypeId();
            Long pid = maType.getParentId();
            if (parentId.equals(pid)) {
                List<Type> childLists = getChild(list, typeId);
                maType.setChildren(childLists);
                childList.add(maType);
            }
        }
        return childList;
    }

    @Override
    public List<MaTypeVoLevelTwo> selectParentId() {
        return mapper.selectParentId();
    }
    /**
     * 根据id查询领用任务信息
     *
     * @param taskId
     * @return 领用任务
     */
    @Override
    public LeaseApplyInfo getApplyInfo(Long taskId) {
        try {
            LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
            leaseApplyInfo = mapper.getApplyInfo(taskId);
            return leaseApplyInfo;
        } catch (Exception e) {
            // 记录异常日志
            System.err.println("查看失败" + e.getMessage());
            throw new RuntimeException("失败", e);
        }
    }

    /**
     * 获取详情
     *
     * @param taskId
     * @return 领用任务
     */
    @Override
    public List<LeaseApplyDetails> getApplyDetails(Long taskId) {
        try {

            List<LeaseApplyDetails> list = mapper.getApplyDetails(taskId);
            return list;
        } catch (Exception e) {
            // 记录异常日志
            System.err.println("查看失败" + e.getMessage());
            throw new RuntimeException("失败", e);
        }
    }

    /**
     * 领用发布查询
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public List<LeasePublishInfo> getPublishList(LeaseApplyInfo leaseApplyInfo) {
        Long userId = SecurityUtils.getLoginUser().getUserid();
        // 首先根据用户名去ma_type_manage表查询是否存在绑定物资信息
        List<Long> typeIdList = leaseApplyInfoMapper.selectTypeIdList(userId);
        if (CollectionUtils.isEmpty(typeIdList)) {
            leaseApplyInfo.setUserId(userId == 0 ? null : userId);
        }
        if (StringUtils.isNotBlank(leaseApplyInfo.getStatus())) {
            List<String> stringList = Arrays.asList(leaseApplyInfo.getStatus().split(","));
            List<Integer> integerList = stringList.stream()
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            leaseApplyInfo.setStatusList(integerList);
        }
        List<LeasePublishInfo> list = mapper.getPublishList(leaseApplyInfo);
        if (!CollectionUtils.isEmpty(list)) {
            if (!CollectionUtils.isEmpty(typeIdList)) {
                // 使用流过滤符合条件的元素
                list = list.stream()
                        .filter(item -> {
                            String firstIdStr = item.getFirstId();
                            if (firstIdStr == null) {
                                return false;
                            }
                            // 将逗号分隔的字符串转为集合
                            Set<Long> firstIds = Arrays.stream(firstIdStr.split(","))
                                    .map(String::trim)
                                    .filter(s -> !s.isEmpty())
                                    .map(Long::parseLong)
                                    .collect(Collectors.toSet());

                            // 判断两个集合是否有交集
                            return firstIds.stream().anyMatch(typeIdList::contains);
                        })
                        .collect(Collectors.toList());
            }
            String keyWord = leaseApplyInfo.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                list = list.stream()
                        .filter(item -> containsKeyWord(item, keyWord))
                        .collect(Collectors.toList());
            }
        }
        return list;
    }

    /**
     * 判断关键字是否包含在item中
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyWord(LeasePublishInfo item, String keyWord) {
        return (item.getMaTypeNames() != null && item.getMaTypeNames().contains(keyWord)) ||
                (item.getLeaseUnit() != null && item.getLeaseUnit().contains(keyWord)) ||
                (item.getLeaseProject() != null && item.getLeaseProject().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord)) ||
                (item.getCreateBy() != null && item.getCreateBy().contains(keyWord)) ||
                (item.getLeasePerson() != null && item.getLeasePerson().contains(keyWord)) ||
                (item.getPhone() != null && item.getPhone().contains(keyWord)) ||
                (item.getImpUnitName() != null && item.getImpUnitName().contains(keyWord));
    }

    /**
     * 获取详情
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public LeaseApplyRequestVo getDetailsById(LeaseApplyInfo leaseApplyInfo) {
        try {
            Long userId = SecurityUtils.getLoginUser().getUserid();
            leaseApplyInfo.setUserId(userId);
            Optional<LeaseApplyInfo> optionalInfo = Optional.ofNullable(mapper.selectLeaseApplyInfoById(leaseApplyInfo));
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();

            optionalInfo.ifPresent(info -> {
                leaseApplyRequestVo.setLeaseApplyInfo(info);
                // 获取领料单详情
                List<LeaseApplyDetails> details = mapper.selectPublishDetails(leaseApplyInfo);
                if (!CollectionUtils.isEmpty(details)) {
                    for (LeaseApplyDetails detail : details) {
                        //查询类型的待出库数量
                        LeaseApplyDetails pendingOutNum = mapper.selectPendingOutNum(detail);
                        detail.setPendingOutNum(pendingOutNum.getPendingOutNum());
                    }
                    leaseApplyRequestVo.setLeaseApplyDetailsList(details);
                }
            });
            return leaseApplyRequestVo;
        } catch (Exception e) {
            throw new RuntimeException("Failed to select lease apply info", e);
        }
    }


    /**
     * 领用发布驳回
     *
     * @param leaseApplyDetails 领用任务详情
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult leasePublishReject(LeaseApplyDetails leaseApplyDetails) {
        if (leaseApplyDetails == null) {
            return AjaxResult.error("参数不能为空");
        }
        //查询是否有newType
        LeaseApplyDetails newType = mapper.selectTypeByNewType(leaseApplyDetails);
        if (newType != null) {
            leaseApplyDetails.setTypeId(newType.getTypeId());
        }
        // 根据parentId及typeId更新lease_apply_details表的发布数量
        int result = mapper.updatePublishSub(leaseApplyDetails);
        if (result == 0) {
            return AjaxResult.error("发布驳回失败,请联系管理员");
        }

        // 根据parentId及newTypeId删除lease_publish_details
        int details = mapper.deletePublishDetails(leaseApplyDetails);
        if (details == 0) {
            throw new ServiceException("发布驳回详情删除失败,请联系管理员");
        }

        // 任务修改为未完成状态
        int taskResult = tmTaskMapper.updateTaskStatus(String.valueOf(leaseApplyDetails.getTaskId()), 1);
        if (taskResult == 0) {
            System.err.println("任务修改为未完成状态失败,请联系管理员");
        }
        return AjaxResult.success("驳回成功");
    }

    /**
     * 发布数据保存
     * @param leaseApplyRequestVo
     * @return
     */
    @Override
    public AjaxResult addPublish(LeaseApplyRequestVo leaseApplyRequestVo) {
        if (leaseApplyRequestVo == null || leaseApplyRequestVo.getLeaseApplyInfo() == null
        || CollectionUtils.isEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
            return AjaxResult.error("参数不能为空");
        }
        try {
            int result = 0;
            LeaseApplyInfo leaseApplyInfo = leaseApplyRequestVo.getLeaseApplyInfo();
            List<LeaseApplyDetails> leaseApplyDetailsList = leaseApplyRequestVo.getLeaseApplyDetailsList();
            Long parentId = leaseApplyDetailsList.get(0).getParentId();
            int thisMonthMaxOrder = mapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth());
            int monthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
            LeasePublishDetails publishDetails = mapper.selectPublishDetailsByCode();
            if (publishDetails != null && StringUtils.isNotBlank(publishDetails.getCode())) {
                String code = publishDetails.getCode();
                if (code.contains("-")) {
                    // 分割字符串，获取"-"后面的部分
                    String suffix = code.split("-")[1];
                    try {
                        // 转换为整数
                        int value = Integer.parseInt(suffix);
                        // 比较并更新最大值
                        if (value > monthMaxOrder) {
                            monthMaxOrder = value;
                        }
                    } catch (NumberFormatException e) {
                        throw new ServiceException("保存失败，请联系管理员");
                    }
                }
            }
            String code  = genderTaskCode(monthMaxOrder);

//            TmTaskAgreement taskAgreement = mapper.getAgreementInfo(leaseApplyInfo);
//
//            taskAgreement.setTaskId(parentId);
//
//            tmTaskAgreementMapper.insertTmTaskAgreement(taskAgreement);

            for (LeaseApplyDetails applyDetails : leaseApplyDetailsList) {
                // 根据parentId及typeId更新lease_apply_details表的发布数量
                result = mapper.updatePublish(applyDetails);
                if (result == 0) {
                    return AjaxResult.error("发布失败,请联系管理员");
                }
                applyDetails.setUnitId(leaseApplyInfo.getUnitId());
                applyDetails.setProjectId(leaseApplyInfo.getProjectId());
                applyDetails.setLeasePerson(leaseApplyInfo.getLeasePerson() != null ? leaseApplyInfo.getLeasePerson() : "");
                applyDetails.setPhone(leaseApplyInfo.getPhone() != null ? leaseApplyInfo.getPhone() : "");
                applyDetails.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                applyDetails.setCreateTime(DateUtils.getNowDate());
                applyDetails.setMonthOrder(thisMonthMaxOrder + 1);
                String publishTask = genderPublishTask(thisMonthMaxOrder);
                applyDetails.setPublishTask(publishTask);
                applyDetails.setCode(code);
                result = mapper.addPublish(applyDetails);
                if (result == 0) {
                    return AjaxResult.error("发布失败,请联系管理员");
                }
            }
            List<LeaseApplyDetails> leaseApplyDetails = mapper.selectLeaseApplyDetailsById(parentId);
            boolean allMatch = true;
            if (!CollectionUtils.isEmpty(leaseApplyDetails)) {
                for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
                    if (leaseApplyDetail.getPreNum().compareTo(leaseApplyDetail.getPublishNum()) > 0) {
                        allMatch = false;
                        break;
                    }
                }
            }
            if (allMatch) {
                TmTask tmTask = new TmTask();
                tmTask.setTaskId(leaseApplyInfo.getTaskId());
                // 出库完成
                tmTask.setTaskStatus(3);
                result = tmTaskMapper.updateTmTask(tmTask);
                if (result == 0) {
                    return AjaxResult.error("发布失败,请联系管理员");
                }
            }
            return AjaxResult.success("发布成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error("发布失败,请联系管理员");
        }
    }


    /**
     * 结束发布
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public AjaxResult endPublish(LeaseApplyInfo leaseApplyInfo) {
        if (leaseApplyInfo == null || leaseApplyInfo.getTaskId() == null) {
            return AjaxResult.error("参数不能为空");
        }
        // 根据taskId修改任务状态为终结
        int result = tmTaskMapper.updateTaskStatus(String.valueOf(leaseApplyInfo.getTaskId()), 5);
        if (result == 0) {
            return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
        }
        return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg());
    }

    /**
     * 导出领料发布详情
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public List<LeasePublishDetails> getPublishDetails(LeaseApplyInfo leaseApplyInfo) {
        Long userId = SecurityUtils.getLoginUser().getUserid();
        leaseApplyInfo.setUserId(userId);
        List<LeasePublishDetails> list = new ArrayList<>();
        // 获取领料单详情
        List<LeaseApplyDetails> details = mapper.selectPublishDetails(leaseApplyInfo);
        if (!CollectionUtils.isEmpty(details)) {
            for (LeaseApplyDetails detail : details) {
                LeasePublishDetails leasePublishDetails = new LeasePublishDetails();
                BeanUtils.copyProperties(detail, leasePublishDetails);
                list.add(leasePublishDetails);
            }
        }
        return list;
    }

    /**
     * 导出领料记录查询
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public List<LeaseRecordInfo> getLeaseRecordList(LeaseApplyInfo leaseApplyInfo) {
        List<LeaseRecordInfo> leaseRecordInfos = new ArrayList<>();
        List<LeaseApplyInfo> list = selectLeaseApplyInfoList(leaseApplyInfo);
        if (!CollectionUtils.isEmpty(list)) {
            for (LeaseApplyInfo applyInfo : list) {
                LeaseRecordInfo leaseRecordInfo = new LeaseRecordInfo();
                BeanUtils.copyProperties(applyInfo, leaseRecordInfo);
                leaseRecordInfos.add(leaseRecordInfo);
            }
        }
        return leaseRecordInfos;
    }

    @Override
    public AjaxResult getPendingOutNumByTypeId(Long typeId) {
        try {
            LeaseApplyDetails leaseApplyDetails = new LeaseApplyDetails();
            leaseApplyDetails.setTypeId(typeId);
            LeaseApplyDetails pendingOutNum = mapper.selectPendingOutNum(leaseApplyDetails);
            return AjaxResult.success(pendingOutNum);
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error("待出库数量查询失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult leaseOutReject(LeaseApplyDetails leaseApplyDetails) {
        try {
            //1、查询整个单子是否已完成，根据taskId
            TmTask tmTask = tmTaskMapper.selectStatusByTaskId(leaseApplyDetails.getTaskId());
            Type type = new Type();
            type.setModelTitle("领料出库驳回");
            type.setCode(tmTask.getCode());
            type.setStyle("6");
            if (tmTask.getTaskStatus() == 4) {
                return AjaxResult.error("该领料任务已出库完成，不可退回");
            }
            //判断是编码还是数量
            if (leaseApplyDetails.getMaCodeVoList()!=null){
                //编码
                for (MaCodeVo maCodeVo : leaseApplyDetails.getMaCodeVoList()) {
                    //更改设备状态为在库
                    int res = mapper.updateMaStatus(maCodeVo);
                    if (res == 0) {
                        throw new ServiceException("设备状态修改失败,请联系管理员");
                    }
                    type.setTypeId(Long.parseLong(maCodeVo.getTypeId()));
                    type.setMaId(maCodeVo.getMaId());
                    type.setInputNum(BigDecimal.ONE);
                    typeService.updateNumAddOrSubtract(type);
                }
            }
            //判断是领用任务还是领料任务，根据newType
            LeaseApplyDetails bean1 = new LeaseApplyDetails();
            if (leaseApplyDetails.getNewTypeId()!=null){
                //清除已领设备
                //把数量清除
                int res1 = mapper.updateLeaseOutNum(leaseApplyDetails);
                //修改库存
                bean1.setTypeId(leaseApplyDetails.getNewTypeId());
                bean1.setAlNum(leaseApplyDetails.getAlNum());
            } else {
                //清除已领设备
                //把数量清除
                int res1 = mapper.updateLeaseOutNumNew(leaseApplyDetails);
                //修改库存
                bean1.setTypeId(leaseApplyDetails.getTypeId());
                bean1.setAlNum(leaseApplyDetails.getAlNum());
            }
            if (CollectionUtils.isEmpty(leaseApplyDetails.getMaCodeVoList())) {
                // 数量设备库存修改
                type.setTypeId(bean1.getTypeId());
                type.setInputNum(bean1.getAlNum());
                typeService.updateNumAddOrSubtract(type);
            /*int res = mapper.updateInventory(bean1);
            if (res == 0) {
                throw new ServiceException("库存修改失败,请联系管理员");
            }*/
            }
            int res = 0;
            // 3、修改任务状态（tm_task）
            if (leaseApplyDetails.getTaskId()!= null) {
                LeaseOutDetails leaseOutDetails = new LeaseOutDetails();
                leaseOutDetails.setTaskId(leaseApplyDetails.getTaskId()+"");
                res = editTaskStatus(leaseOutDetails);
                if (res == GlobalConstants.INT_0) {
                    throw new RuntimeException("出库退回失败,修改任务状态失败");
                }
            }
            // 删除领料出库明细表（lease_out_details）
            int res2 = mapper.deleteLeaseOutDetails(leaseApplyDetails);
            // 4、删除结算记录
            res = deleteSltInfo(leaseApplyDetails);
            if (res == GlobalConstants.INT_0) {
                throw new RuntimeException("出库失败,插入结算记录失败");
            }

            //增加退回记录
            insertBackRecord(leaseApplyDetails);
            return AjaxResult.success("领用出库退回成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("领用出库退回失败:",e.getMessage());
            return AjaxResult.error("领用出库退回失败");
        }
    }

    /**
     * 添加退回记录
     * @param leaseApplyDetails
     */
    public void insertBackRecord(LeaseApplyDetails leaseApplyDetails) {
        // 查询当前登陆用户信息
        Long theLoginUserId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        LeaseApplyDetails bean = new LeaseApplyDetails();
        //判断是编码还是数量
        if (leaseApplyDetails.getMaCodeVoList()!=null){
            //编码
            for (MaCodeVo maCodeVo : leaseApplyDetails.getMaCodeVoList()) {
                //添加退回记录
                bean.setMaId(maCodeVo.getMaId());
                bean.setParentId(leaseApplyDetails.getParentId());
                bean.setTypeId(leaseApplyDetails.getTypeId());
                bean.setNewTypeId(leaseApplyDetails.getNewTypeId());
                bean.setNum(BigDecimal.valueOf(1));
                bean.setCreateBy(String.valueOf(theLoginUserId));
                int res = mapper.insertBackRecordByMaId(bean);
            }
        } else {
            //数量
            bean.setParentId(leaseApplyDetails.getParentId());
            bean.setTypeId(leaseApplyDetails.getTypeId());
            bean.setNewTypeId(leaseApplyDetails.getNewTypeId());
            bean.setNum(leaseApplyDetails.getAlNum());
            bean.setCreateBy(String.valueOf(theLoginUserId));
            int res = mapper.insertBackRecordByMaId(bean);
        }

    }

    /**
     * 删除结算记录
     * @param leaseApplyDetails
     * @return
     */
    private int deleteSltInfo(LeaseApplyDetails leaseApplyDetails) {
        return mapper.deleteSltInfo(leaseApplyDetails);
    }

    /**
     * 修改任务状态（tm_task）
     * @param leaseOutDetails
     * @return
     */
    private int editTaskStatus(LeaseOutDetails leaseOutDetails) {
        return tmTaskMapper.updateTaskStatus(leaseOutDetails.getTaskId(), LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
    }

    @Override
    public AjaxResult delLeaseDetails(LeaseApplyDetails leaseApplyDetails) {
        try {
            int res = mapper.delLeaseDetails(leaseApplyDetails);
            if (res == 0) {
                return AjaxResult.error("领料详情删除失败");
            }
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            log.error("领料详情删除失败:",e.getMessage());
            return AjaxResult.error("领料详情删除失败");
        }
    }

    /**
     * 生成发布批次任务
     * @param thisMonthMaxOrder
     * @return
     */
    private String genderPublishTask(int thisMonthMaxOrder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        return MaterialConstants.LEASE_PUBLISH + result + String.format("-%03d", thisMonthMaxOrder + 1);
    }
}
