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

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.bonus.common.biz.config.PoiOutPage;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.domain.BmFileInfo;
import com.bonus.common.biz.domain.lease.LeaseOutSign;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.biz.enums.LeaseTaskStatusEnum;
import com.bonus.common.biz.enums.MaMachineStatusEnum;
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.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.back.domain.vo.MaCodeVo;
import com.bonus.material.basic.domain.BmQrcodeInfo;
import com.bonus.material.basic.mapper.BmFileInfoMapper;
import com.bonus.material.lease.domain.LeaseApplyDetails;
import com.bonus.common.biz.domain.lease.LeaseOutDetails;
import com.bonus.material.lease.domain.vo.LeaseApplyRequestVo;
import com.bonus.common.biz.domain.lease.LeaseOutRequestVo;
import com.bonus.material.lease.domain.vo.LeaseOutVo;
import com.bonus.material.lease.mapper.LeaseApplyDetailsMapper;
import com.bonus.material.lease.service.ILeaseOutDetailsService;
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 lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import com.bonus.material.lease.mapper.LeaseApplyInfoMapper;
import com.bonus.common.biz.domain.lease.LeaseApplyInfo;
import com.bonus.material.lease.service.ILeaseApplyInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 领料任务Service业务层处理
 *
 * @author xsheng
 * @date 2024-10-16
 */
@Service
@Slf4j
public class LeaseApplyInfoServiceImpl implements ILeaseApplyInfoService {

    @Resource
    private ILeaseOutDetailsService leaseOutDetailsService;

    @Resource
    private LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private LeaseApplyDetailsMapper leaseApplyDetailsMapper;

    @Resource
    private TmTaskMapper tmTaskMapper;

    @Resource
    TmTaskAgreementMapper tmTaskAgreementMapper;

    @Resource
    private BmFileInfoMapper bmFileInfoMapper;

    /**
     * 查询领料任务
     *
     * @param id 领料任务主键
     * @return 领料任务
     */
    @Override
    public LeaseApplyRequestVo selectLeaseApplyInfoById(Long id, String keyword, String publishTask) {
        try {
            LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
            leaseApplyInfo.setId(id);
            Long userId = SecurityUtils.getLoginUser().getUserid();
            leaseApplyInfo.setUserId(userId);
            Optional<LeaseApplyInfo> optionalInfo = Optional.ofNullable(leaseApplyInfoMapper.selectLeaseApplyInfoById(leaseApplyInfo));
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();
            // 查询领用出库数据
            if (StringUtils.isNotBlank(publishTask)) {
                leaseApplyInfo.setPublishTask(publishTask);
                List<LeaseApplyInfo> leaseApplyOutList = leaseApplyInfoMapper.selectPublishList(leaseApplyInfo);
                if (!CollectionUtils.isEmpty(leaseApplyOutList)) {
                    LeaseApplyInfo applyInfo = leaseApplyOutList.get(0);
                    if (applyInfo.getPreCountNum().compareTo(applyInfo.getAlNum()) == 0) {
                        applyInfo.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatus());
                        applyInfo.setTaskStatusName(LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatusName());
                    } else {
                        applyInfo.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
                        applyInfo.setTaskStatusName(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatusName());
                    }
                    optionalInfo = Optional.of(leaseApplyOutList.get(0));
                }
            }
            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);
                }
                // 电子签名进行base64拼接
                if (StringUtils.isNotBlank(info.getLeaseSignUrl())) {
                    info.setLeaseSignUrl("data:image/png;base64," + info.getLeaseSignUrl());
                }
                /** 设置发料单位  防止代码冲突  **/

                leaseApplyRequestVo.setLeaseApplyInfo(info);
                // 获取领料单详情
                List<LeaseApplyDetails> details = leaseApplyDetailsMapper.selectLeaseApplyDetailsList(new LeaseApplyDetails(info.getId(), keyword, userId));
                // 走单独的领用详情查询
                if (StringUtils.isNotBlank(publishTask)) {
                    // 根据领用批次查询领用详情
                    details = leaseApplyDetailsMapper.getDetailsPublish(keyword, publishTask);
                    if (!CollectionUtils.isEmpty(details)) {
                        for (LeaseApplyDetails detail : details) {
                            if (detail.getPreNum().compareTo(detail.getAlNum()) == 0) {
                                detail.setStatus("2");
                            } else {
                                detail.setStatus("1");
                            }
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(details)) {
                    /*if (StringUtils.isNotBlank(keyword)) {
                        details = details.stream()
                                .filter(item -> containsDetailsKeyword(item, keyword))
                                .collect(Collectors.toList());
                    }*/
                    leaseApplyRequestVo.setLeaseApplyDetailsList(details);
                    for (LeaseApplyDetails detail : details) {
                        // 获取编码详情
                        List<MaCodeVo> maCodeVoList = leaseApplyDetailsMapper.getCodeList(id, detail.getTypeId());
                        if (!CollectionUtils.isEmpty(maCodeVoList)) {
                            detail.setMaCodeVoList(maCodeVoList);
                        }
                    }
                }
                // 根据id查询领料出库情况，查询出库人电子签名详情
                List<LeaseOutSign> outSignList = leaseApplyInfoMapper.selectLeaseApplyOutList(id);
                if (!CollectionUtils.isEmpty(outSignList)) {
                    for (LeaseOutSign applyInfo : outSignList) {
                        if (StringUtils.isNotBlank(applyInfo.getOutSignUrl())) {
                            applyInfo.setOutSignUrl("data:image/png;base64," + applyInfo.getOutSignUrl());
                        }
                    }
                    leaseApplyRequestVo.setKgSignList(outSignList);
                }

            });

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

    /**
     * 查询领料任务列表
     *
     * @param leaseApplyInfo 领料任务
     * @return 领料任务
     */
    @Override
    public List<LeaseApplyInfo> selectLeaseApplyInfoList(LeaseApplyInfo leaseApplyInfo) {
        leaseApplyInfo.setUserId(SecurityUtils.getLoginUser().getUserid());
        List<LeaseApplyInfo> list = leaseApplyInfoMapper.selectLeaseApplyInfoList(leaseApplyInfo);
        // 如果statusList包含3、4、5，则为领料出库查询，需查询领用出库数据，进行拼接
        if (!CollectionUtils.isEmpty(leaseApplyInfo.getStatusList())) {
            if (((leaseApplyInfo.getStatusList().contains(3) || leaseApplyInfo.getStatusList().contains(4)) && !leaseApplyInfo.getStatusList().contains(1))
                    || leaseApplyInfo.getStatusList().containsAll(Arrays.asList(3, 4, 5))) {
                // 查询领用出库数据
                extracted(leaseApplyInfo, list);
            }
        }
        if (!CollectionUtils.isEmpty(list)) {
            if (leaseApplyInfo.getHasSign() != null && leaseApplyInfo.getHasSign() == 1) {
                // 将list集合中leaseSignUrl不为null的数据过滤出来
                list = list.stream()
                        .filter(info -> StringUtils.isNotBlank(info.getLeaseSignUrl()))
                        .collect(Collectors.toList());
            } else if (leaseApplyInfo.getHasSign() != null && leaseApplyInfo.getHasSign() == 0) {
                extracted(leaseApplyInfo, list);
                // 查询待签名的领料单
                list = list.stream()
                        .filter(info -> StringUtils.isBlank(info.getLeaseSignUrl()))
                        .collect(Collectors.toList());
            }
        }
        // 使用 Stream API 进行降序排序
        List<LeaseApplyInfo> sortedList = list.stream()
                .sorted(Comparator.comparing(LeaseApplyInfo::getCreateTime,
                        Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(sortedList)) {
            String keyWord = leaseApplyInfo.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                sortedList = sortedList.stream()
                        .filter(item -> containsKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }
            // 判断状态
            if (!CollectionUtils.isEmpty(leaseApplyInfo.getStatusList())) {
                // 将集合sortedList中状态taskStatus包含在leaseApplyInfo.getStatusList()中的元素
                sortedList = sortedList.stream()
                        .filter(item -> leaseApplyInfo.getStatusList().contains(item.getTaskStatus()))
                        .collect(Collectors.toList());
            }
        }
        return sortedList;
    }

    /**
     * 查询领用数据抽取
     * @param leaseApplyInfo
     * @param list
     */
    private void extracted(LeaseApplyInfo leaseApplyInfo, List<LeaseApplyInfo> list) {
        // 查询领用出库数据
        List<LeaseApplyInfo> leaseApplyOutList = leaseApplyInfoMapper.selectPublishList(leaseApplyInfo);
        if (!CollectionUtils.isEmpty(leaseApplyOutList)) {
            for (LeaseApplyInfo applyInfo : leaseApplyOutList) {
                if (applyInfo.getPreCountNum().compareTo(applyInfo.getAlNum()) == 0) {
                    applyInfo.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatus());
                    applyInfo.setTaskStatusName(LeaseTaskStatusEnum.LEASE_TASK_FINISHED.getStatusName());
                } else {
                    applyInfo.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
                    applyInfo.setTaskStatusName(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatusName());
                }
            }
            list.addAll(leaseApplyOutList);
        }
    }

    /**
     * 材料员确认service
     *
     * @param id
     * @param isConfirm
     * @param confirmRemark
     * @return
     */
    @Override
    public int confirmLeaseTask(String id, Integer isConfirm, String confirmRemark) {
        return leaseApplyInfoMapper.confirmLeaseTask(id, isConfirm, SecurityUtils.getUserId(), new Date(), confirmRemark);
    }

    /**
     * 查询已完成出库任务
     *
     * @param leaseApplyInfo 领料任务
     * @return 领料任务集合
     */
    @Override
    public List<LeaseApplyInfo> getCompleteOutTaskList(LeaseApplyInfo leaseApplyInfo) {
        leaseApplyInfo.setUserId(SecurityUtils.getUserId());
        List<LeaseApplyInfo> list = leaseApplyInfoMapper.selectLeaseApplyInfoList(leaseApplyInfo);
        // 如果statusList包含3、4、5，则为领料出库查询，需查询领用出库数据，进行拼接
        if (!CollectionUtils.isEmpty(leaseApplyInfo.getStatusList())) {
            if (leaseApplyInfo.getStatusList().contains(4)) {
                // 查询领用出库数据
                extracted(leaseApplyInfo, list);
            }
        }
        // 使用 Stream API 进行降序排序
        List<LeaseApplyInfo> sortedList = list.stream()
                .sorted(Comparator.comparing(LeaseApplyInfo::getCreateTime,
                        Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(sortedList)) {
            String keyWord = leaseApplyInfo.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                sortedList = sortedList.stream()
                        .filter(item -> containsKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }
            // 判断状态
            if (!CollectionUtils.isEmpty(leaseApplyInfo.getStatusList())) {
                // 将集合sortedList中状态taskStatus包含在leaseApplyInfo.getStatusList()中的元素
                sortedList = sortedList.stream()
                        .filter(item -> leaseApplyInfo.getStatusList().contains(item.getTaskStatus()))
                        .collect(Collectors.toList());
            }
        }
        sortedList.removeIf(Objects::isNull);
        if (leaseApplyInfo.getIsConfirm() != null) {
            if (leaseApplyInfo.getIsConfirm() == 1) {
                sortedList.removeIf(item -> item.getIsConfirm() != null && item.getIsConfirm() == 2);
            } else if (leaseApplyInfo.getIsConfirm() == 2) {
                sortedList.removeIf(item -> item.getIsConfirm() == null || item.getIsConfirm() != 2);
            }
        }
        // 再次移除可能的null值
        sortedList.removeIf(Objects::isNull);
        // 只有出库完成的任务才需要进行确认，这里过滤掉任务状态不等于4（出库已完成）的
        sortedList.removeIf(item -> item.getTaskStatus() != 4);

        return sortedList;
    }

    /**
     * 关键字搜索
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(LeaseApplyInfo item, String keyWord) {
        return (item.getMaTypeNames() != null && item.getMaTypeNames().contains(keyWord)) ||
                (item.getUnitName() != null && item.getUnitName().contains(keyWord)) ||
                (item.getProjectName() != null && item.getProjectName().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.getContractPart() != null && item.getContractPart().contains(keyWord)) ||
                (item.getImpUnitName() != null && item.getImpUnitName().contains(keyWord));
    }

    /**
     * 新增领料任务
     *
     * @param leaseApplyRequestVo 领料任务
     * @return 结果
     */
    @Override
    public AjaxResult insertLeaseApplyInfo(LeaseApplyRequestVo leaseApplyRequestVo) {
        /*int result = 0;
        if (null == leaseApplyRequestVo.getLeaseApplyInfo()) {
            return AjaxResult.error("请先填写领料任务信息");
        }
        if (CollectionUtil.isEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
            return AjaxResult.error("请先添加领料任务物资明细");
        }
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateTime(DateUtils.getNowDate());
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        try {
            // 获取 LeaseApplyDetails 列表
            List<LeaseApplyDetails> leaseApplyDetailsList = leaseApplyRequestVo.getLeaseApplyDetailsList();
            for (LeaseApplyDetails applyDetails : leaseApplyDetailsList) {
                if (applyDetails.getCompanyId() == null) {
                    throw new RuntimeException("未知所属公司领料任务，无法操作！");
                }
            }
            // 按 companyId 进行分组
            Map<Long, List<LeaseApplyDetails>> groupedByCompanyId = leaseApplyDetailsList.stream()
                    .collect(Collectors.groupingBy(LeaseApplyDetails::getCompanyId));
            for (Map.Entry<Long, List<LeaseApplyDetails>> entry : groupedByCompanyId.entrySet()) {
                Long key = entry.getKey();
                List<LeaseApplyDetails> details = entry.getValue();
                TmTaskTypeEnum splitType = null;
                String taskTypeLabel = null;
                // 机具领料任务
                if (key == 101) {
                    splitType = TmTaskTypeEnum.TM_TASK_JJ_LEASE;
                    taskTypeLabel = MaterialConstants.JJ_LEASE_TASK_TYPE_LABEL;
                    // 安全工器具领料任务
                } else if (key == 102) {
                    splitType = TmTaskTypeEnum.TM_TASK_SAFE_LEASE;
                    taskTypeLabel = MaterialConstants.AQ_LEASE_TASK_TYPE_LABEL;
                    // 宏源领料任务
                } else if (key == 309) {
                    splitType = TmTaskTypeEnum.TM_TASK_HY_LEASE;
                    taskTypeLabel = MaterialConstants.HY_LEASE_TASK_TYPE_LABEL;
                } else {
                    throw new RuntimeException("未知所属公司领料任务，无法操作！");
                }
                result += processLeaseTask(leaseApplyRequestVo, splitType, taskTypeLabel);
                if (result > 0) {
                    return insertPurchaseCheckDetails(details, leaseApplyRequestVo.getLeaseApplyInfo().getId());
                } else {
                    return AjaxResult.error("新增任务失败,lease_apply_info表插入0条");
                }
            }
        } catch (DataAccessException e) {
            throw new RuntimeException("数据库操作失败:" + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException("新增任务失败:" + e.getMessage());
        }
        return AjaxResult.error("新增任务失败");*/
        if (null == leaseApplyRequestVo.getLeaseApplyInfo()) {
            return AjaxResult.error("请先填写领料任务信息");
        }
        if (CollectionUtil.isEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
            return AjaxResult.error("请先添加领料任务物资明细");
        }
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateTime(DateUtils.getNowDate());
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        try {
            int thisMonthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
            String taskCode = genderTaskCode(thisMonthMaxOrder);
            TmTask tmTask = new TmTask(null, TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId(),
                    LeaseTaskStatusEnum.LEASE_TASK_TO_PUBLISHED.getStatus(),
                    leaseApplyRequestVo.getLeaseApplyInfo().getCompanyId(),thisMonthMaxOrder + 1, taskCode);
            tmTask.setCreateTime(DateUtils.getNowDate());
            tmTask.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            tmTaskMapper.insertTmTask(tmTask);
            TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask.getTaskId(), leaseApplyRequestVo.getLeaseApplyInfo().getAgreementId());
            tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
            tmTaskAgreement.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            tmTaskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);
            leaseApplyRequestVo.getLeaseApplyInfo().setTaskId(tmTask.getTaskId());
            leaseApplyRequestVo.getLeaseApplyInfo().setCode(taskCode);

            /** 设置审批人为默认的董班长 --防止代码冲突 **/
            Long peopleId = leaseApplyInfoMapper.getDirectAuditBy();
            leaseApplyRequestVo.getLeaseApplyInfo().setDirectAuditBy(peopleId);
            /** 设置审批人为默认的董班长 --防止代码冲突 **/

            int count = leaseApplyInfoMapper.insertLeaseApplyInfo(leaseApplyRequestVo.getLeaseApplyInfo());
            if (!CollectionUtils.isEmpty(leaseApplyRequestVo.getLeaseApplyInfo().getBmFileInfos())) {
                leaseApplyRequestVo.getLeaseApplyInfo().getBmFileInfos().forEach(bmFileInfo -> {
                    bmFileInfo.setTaskType(2);
                    bmFileInfo.setTaskId(tmTask.getTaskId());
                    bmFileInfo.setModelId(leaseApplyRequestVo.getLeaseApplyInfo().getId());
                    bmFileInfo.setFileType(5L);
                    bmFileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                    bmFileInfo.setCreateTime(DateUtils.getNowDate());
                    bmFileInfoMapper.insertBmFileInfo(bmFileInfo);
                });
            }
            if (count > 0) {
                return insertPurchaseCheckDetails(leaseApplyRequestVo.getLeaseApplyDetailsList(), leaseApplyRequestVo.getLeaseApplyInfo().getId());
            } else {
                return AjaxResult.error("新增任务失败,lease_apply_info表插入0条");
            }
        } catch (DataAccessException e) {
            return AjaxResult.error("数据库操作失败:" + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("新增任务失败:" + e.getMessage());
        }
    }

    /**
     * 处理任务
     * @param leaseApplyRequestVo
     * @param splitType
     * @param taskTypeLabel
     * @return
     */
    /*private int processLeaseTask(LeaseApplyRequestVo leaseApplyRequestVo, TmTaskTypeEnum splitType, String taskTypeLabel) {
        int thisMonthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(),
                TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
        String taskCode = genderTaskCode(thisMonthMaxOrder, taskTypeLabel);

        TmTask tmTask = new TmTask(null, TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId(),
                LeaseTaskStatusEnum.LEASE_TASK_TO_PUBLISHED.getStatus(),
                leaseApplyRequestVo.getLeaseApplyInfo().getCompanyId(), thisMonthMaxOrder + 1, taskCode);
        tmTask.setCreateTime(DateUtils.getNowDate());
        tmTask.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        tmTask.setSplitType(splitType.getTaskTypeId());
        tmTaskMapper.insertTmTask(tmTask);

        TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask.getTaskId(), leaseApplyRequestVo.getLeaseApplyInfo().getAgreementId());
        tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
        tmTaskAgreement.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        tmTaskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);

        leaseApplyRequestVo.getLeaseApplyInfo().setTaskId(tmTask.getTaskId());
        leaseApplyRequestVo.getLeaseApplyInfo().setCode(taskCode);

        // 设置审批人为默认的董班长 --防止代码冲突
        Long peopleId = leaseApplyInfoMapper.getDirectAuditBy();
        leaseApplyRequestVo.getLeaseApplyInfo().setDirectAuditBy(peopleId);

        int count = leaseApplyInfoMapper.insertLeaseApplyInfo(leaseApplyRequestVo.getLeaseApplyInfo());

        if (!CollectionUtils.isEmpty(leaseApplyRequestVo.getLeaseApplyInfo().getBmFileInfos())) {
            leaseApplyRequestVo.getLeaseApplyInfo().getBmFileInfos().forEach(bmFileInfo -> {
                bmFileInfo.setTaskType(2);
                bmFileInfo.setTaskId(tmTask.getTaskId());
                bmFileInfo.setModelId(leaseApplyRequestVo.getLeaseApplyInfo().getId());
                bmFileInfo.setFileType(5L);
                bmFileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                bmFileInfo.setCreateTime(DateUtils.getNowDate());
                bmFileInfoMapper.insertBmFileInfo(bmFileInfo);
            });
        }
        return count;
    }*/

    /**
     * 发布任务
     *
     * @param leaseApplyInfo 领料任务info
     */
    @Override
    @Transactional
    public AjaxResult publish(LeaseApplyInfo leaseApplyInfo) {
        if (leaseApplyInfo.getId() == null) {
            return AjaxResult.error("ID为空,请完善后重新发布!");
        }
        if (leaseApplyInfo.getTaskId() == null) {
            return AjaxResult.error("任务ID为空,请完善后重新发布!");
        }
        try {
            int result = leaseApplyInfoMapper.updateLeaseApplyInfo(leaseApplyInfo);
            if (result > 0) {
                // 同步修改tm_task任务状态, 如果不需要审核，改成 LEASE_TASK_IN_PROGRESS， 如果需要审核，改成 LEASE_TASK_TO_AUDIT
                TmTask tmTask = new TmTask();
                tmTask.setTaskType(TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
                tmTask.setTaskId(leaseApplyInfo.getTaskId());
                tmTask.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
                tmTaskMapper.updateTmTask(tmTask);
                return AjaxResult.success("发布成功");
            }
            return AjaxResult.error("发布失败");
        } catch (DataAccessException e) {
            // 抛出异常、回滚数据
            throw new RuntimeException();
        } catch (Exception e) {
            return AjaxResult.error("发布失败:" + e.getMessage());
        }
    }

    /**
     * 领用任务审核
     */
    @Override
    public AjaxResult useExamine(LeaseApplyInfo leaseApplyInfo) {
        if (leaseApplyInfo.getId() == null) {
            return AjaxResult.error("ID为空,请完善后重新发布!");
        }
        if (leaseApplyInfo.getTaskId() == null) {
            return AjaxResult.error("任务ID为空,请完善后重新发布!");
        }
        try {
            int result = leaseApplyInfoMapper.updateLeaseApplyInfo(leaseApplyInfo);
            if (result > 0) {
                // 同步修改tm_task任务状态, 如果不需要审核，改成 LEASE_TASK_IN_PROGRESS， 如果需要审核，改成 LEASE_TASK_TO_AUDIT
                TmTask tmTask = new TmTask();
                tmTask.setTaskType(TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
                tmTask.setTaskId(leaseApplyInfo.getTaskId());
                tmTask.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_TO_PUBLISHED.getStatus());
                tmTaskMapper.updateTmTask(tmTask);
                return AjaxResult.success("审核成功");
            }
            return AjaxResult.error("审核失败");
        } catch (DataAccessException e) {
            // 抛出异常、回滚数据
            throw new RuntimeException();
        } catch (Exception e) {
            return AjaxResult.error("审核失败:" + e.getMessage());
        }
    }



    /**
     * 插入领料任务详情数据
     * @param leaseApplyDetailsList
     * @param parentId
     * @return
     */
    private AjaxResult insertPurchaseCheckDetails(List<LeaseApplyDetails> leaseApplyDetailsList, Long parentId) {
        if (!CollectionUtils.isEmpty(leaseApplyDetailsList)) {
            for (LeaseApplyDetails details : leaseApplyDetailsList) {
                details.setParentId(parentId); // 设置info.parentId
                details.setCreateTime(DateUtils.getNowDate());
                details.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            }
            // 批量插入详情数据
            int count = leaseApplyDetailsMapper.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, String taskType) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        return taskType + result + String.format("-%03d", thisMonthMaxOrder + 1);
    }*/
    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("-%03d", thisMonthMaxOrder + 1);
    }

    /**
     * 修改领料任务
     *
     * @param leaseApplyRequestVo 领料任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateLeaseApplyInfo(LeaseApplyRequestVo leaseApplyRequestVo) {
        try {
            // 提取到局部变量中，减少重复代码
            LeaseApplyInfo leaseApplyInfo = leaseApplyRequestVo.getLeaseApplyInfo();
            if (leaseApplyInfo != null && leaseApplyInfo.getId() != null) {
                leaseApplyInfo.setUpdateTime(DateUtils.getNowDate());
                leaseApplyInfo.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());

                // 去除创建一个新的数组对象，直接复用
                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());
                }
                // 修改外层info
                leaseApplyInfoMapper.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());
        }
        /*try {
            int result = 0;
            // 提取到局部变量中，减少重复代码
            LeaseApplyInfo leaseApplyInfo = leaseApplyRequestVo.getLeaseApplyInfo();
            if (leaseApplyInfo != null && leaseApplyInfo.getId() != null) {
                // 去除创建一个新的数组对象，直接复用
                Long[] ids = {leaseApplyInfo.getId()};
                result = leaseApplyInfoMapper.deleteLeaseApplyInfoByIds(ids);
                if (result == 0) {
                    throw new RuntimeException("删除主要任务失败");
                }
                if (CollectionUtil.isNotEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
                    // 业务逻辑代码
                    result = leaseApplyDetailsMapper.deleteLeaseApplyDetailsByParentIds(ids);
                    if (result == 0) {
                        throw new RuntimeException("删除详情任务失败");
                    }
                }
                // 查询是否存在文件
                BmFileInfo fileInfo = new BmFileInfo();
                fileInfo.setTaskId(leaseApplyInfo.getTaskId());
                fileInfo.setModelId(leaseApplyInfo.getId());
                fileInfo.setTaskType(2);
                fileInfo.setFileType(5L);
                List<BmFileInfo> bmFileInfos = bmFileInfoMapper.selectBmFileInfoList(fileInfo);
                // 删除原有数据
                if (!CollectionUtils.isEmpty(bmFileInfos)) {
                    result = bmFileInfoMapper.deleteBmFileInfoByBizInfo(fileInfo);
                    if (result == 0) {
                        throw new RuntimeException("删除文件失败");
                    }
                }
                // 重新走新增逻辑
                AjaxResult ajaxResult = insertLeaseApplyInfo(leaseApplyRequestVo);
                if (!ajaxResult.isSuccess()) {
                    System.err.println(ajaxResult.get("msg"));
                    throw new RuntimeException("修改新增数据异常");
                }
                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 leaseApplyInfo
     */
    @Override
    public int updateLeaseApplyInfoSign(LeaseApplyInfo leaseApplyInfo) {
        // 领用电子签名修改
        if (leaseApplyInfo.getTaskType() != null && leaseApplyInfo.getTaskType() == 19) {
            return leaseApplyInfoMapper.updateLeasePublishInfoSign(leaseApplyInfo);
        }
        return leaseApplyInfoMapper.updateLeaseApplyInfoSign(leaseApplyInfo);
    }


    /**
     * 领料：出库
     *
     * @param leaseOutRequestVo 领料：出库
     * @return 结果
     */
    @Override
    public AjaxResult leaseOut(LeaseOutRequestVo leaseOutRequestVo) {
        for (LeaseOutDetails bean : leaseOutRequestVo.getLeaseOutDetailsList()) {
            AjaxResult ajaxResult = leaseOutDetailsService.leaseOut(bean);
            if (ajaxResult.isError()) {
                return ajaxResult;
            }
        }
        return AjaxResult.success();
    }



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

    /**
     * 删除领料任务信息
     *
     * @param id 领料任务主键
     * @return 结果
     */
    @Override
    public int deleteLeaseApplyInfoById(Long id) {
        return leaseApplyInfoMapper.deleteLeaseApplyInfoById(id);
    }

    /**
     * 领料任务详情
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public List<LeaseApplyDetails> selectLeaseApplyDetailsList(LeaseApplyInfo leaseApplyInfo) {
        return leaseApplyDetailsMapper.selectLeaseApplyDetailsList(new LeaseApplyDetails(leaseApplyInfo.getId(), leaseApplyInfo.getKeyWord(), leaseApplyInfo.getUserId()));
    }

    /**
     * 根据qrcode查询在库机具信息
     * @param bmQrcodeInfo
     * @return
     */
    @Override
    public AjaxResult getInfoByQrcode(BmQrcodeInfo bmQrcodeInfo) {
        if (StringUtils.isBlank(bmQrcodeInfo.getQrCode())) {
            return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), "二维码code不能为空");
        }
        List<LeaseOutDetails> recordList = leaseApplyDetailsMapper.getInfoByQrcode(bmQrcodeInfo);
        String msg = "";
        if (CollectionUtil.isNotEmpty(recordList)) {
            recordList = recordList.stream().filter(item -> item.getMaStatus().equals(MaMachineStatusEnum.IN_STORE.getStatus().toString())).collect(Collectors.toList());
            if (recordList.size() > 0) {
                msg = "监测到当前设备符合出库条件,请确认是否出库!";
            }else{
                msg = "监测到当前设备不符合出库条件，无法出库!";
            }
        } else {
            msg = "监测到当前设备不符合出库条件，无法出库!!";
        }
        // 返回包含设备列表和消息的结果
        Map<String, Object> result = new HashMap<>(2);
        result.put("recordList", recordList);
        result.put("msg", msg);
        return AjaxResult.success(result);
    }

    @Override
    public LeaseApplyRequestVo getInfo(Long id) {
        try {
            LeaseApplyInfo leaseApplyInfo = new LeaseApplyInfo();
            leaseApplyInfo.setId(id);
            Long userId = SecurityUtils.getLoginUser().getUserid();
            Optional<LeaseApplyInfo> optionalInfo = Optional.ofNullable(leaseApplyInfoMapper.selectLeaseApplyInfoById(leaseApplyInfo));
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();

            optionalInfo.ifPresent(info -> {
                leaseApplyRequestVo.setLeaseApplyInfo(info);
                // 获取领料单详情
                List<LeaseOutVo> details = leaseApplyDetailsMapper.selectLeaseOutDetailsList(id, userId);
                if (!CollectionUtils.isEmpty(details)) {
                    leaseApplyRequestVo.setLeaseOutVoList(details);
                }
            });
            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 void exportInfo(LeaseApplyInfo leaseApplyInfo, LeaseApplyRequestVo leaseApplyRequestVo, HttpServletResponse response) {
        try {
            String fileName = "施工机具设备出库检验记录表";
            String projectName = "";
            String unit = "";
            List<LeaseOutVo> list = new ArrayList<>();
            if (leaseApplyRequestVo != null && leaseApplyRequestVo.getLeaseApplyInfo() != null) {
                projectName ="领用工程：" + leaseApplyRequestVo.getLeaseApplyInfo().getLeaseProject();
                unit ="使用单位：" + leaseApplyRequestVo.getLeaseApplyInfo().getLeaseUnit();
                list = leaseApplyRequestVo.getLeaseOutVoList();
                if (leaseApplyInfo.getMaId() != null) {
                    // 过滤出list中和leaseApplyInfo.getMaId()相等的元素
                    list = list.stream()
                            .filter(item -> item.getMaId().equals(leaseApplyInfo.getMaId()))
                            .collect(Collectors.toList());
                }
            }
            expOutExcel(response,list,fileName,projectName,unit);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * 领料单详情
     * @param leaseApplyDetails
     * @return
     */
    @Override
    public LeaseApplyDetails getInnerById(LeaseApplyDetails leaseApplyDetails) {
        LeaseApplyDetails info =  leaseApplyDetailsMapper.getInnerById(leaseApplyDetails);
        // 根据领用批次查询领用详情
        if (StringUtils.isNotBlank(leaseApplyDetails.getPublishTask())) {
            info = leaseApplyDetailsMapper.selectInfo(leaseApplyDetails);
        }
        return info;
    }

    /**
     * 领料单详情
     * @param leaseApplyDetails
     * @return
     */
    @Override
    public List<LeaseApplyDetails> getDetailsById(LeaseApplyDetails leaseApplyDetails) {
        List<LeaseApplyDetails> list = leaseApplyDetailsMapper.getDetailsById(leaseApplyDetails);
        if (StringUtils.isNotBlank(leaseApplyDetails.getPublishTask())) {
            list = leaseApplyDetailsMapper.selectPublishDetails(leaseApplyDetails);
        }
        return list;
    }

    /**
     * app领料出库退回
     * @param leaseOutDetails
     * @return
     */
    @Override
    public AjaxResult leaseOutBack(LeaseOutDetails leaseOutDetails) {
        return leaseOutDetailsService.leaseOutBack(leaseOutDetails);
    }

    /**
     * 导出领料单
     * @param response
     * @param list
     * @param filename
     * @param projectName
     * @param unit
     * @throws Exception
     */
    private void expOutExcel(HttpServletResponse response, List<LeaseOutVo> list, String filename,String projectName,String unit)
            throws Exception {
        if (list != null) {
            List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                LeaseOutVo bean = list.get(i);
                Map<String, Object> maps = outReceiveDetailsBeanToMap(bean);
                results.add(maps);
            }
            List<String> headers = receiveDetailsHeader();
            HSSFWorkbook workbook = PoiOutPage.excelForcheck(results, headers, filename,projectName,unit);
            OutputStream out = null;
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xls");
            response.setHeader("Pragma", "No-cache");
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        }else{
            List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
            List<String> headers = receiveDetailsHeader();
            HSSFWorkbook workbook = PoiOutPage.excel(results, headers, filename);
            OutputStream out = null;
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xls");
            response.setHeader("Pragma", "No-cache");
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        }
    }

    /**
     * 领料单数据转换
     * @param bean
     * @return
     */
    private Map<String, Object> outReceiveDetailsBeanToMap(LeaseOutVo bean) {
        Map<String, Object> maps = new LinkedHashMap<String, Object>();
        maps.put("typeName", bean.getTypeName());
        maps.put("typeModelName", bean.getTypeModelName());
        maps.put("unit", bean.getUnit());
        maps.put("num", bean.getNum());
        maps.put("maCode", bean.getMaCode());
        maps.put("ratedLoad", bean.getRatedLoad());
        maps.put("testLoad", bean.getTestLoad());
        maps.put("holdingTime", bean.getHoldingTime());
        maps.put("testTime", bean.getTestTime());
        maps.put("nextTestTime", bean.getNextTestTime());
        maps.put("checkResult", bean.getCheckResult());
        maps.put("remark", bean.getRemark());
        return maps;
    }

    /**
     * 领料单表头
     * @return
     */
    private List<String> receiveDetailsHeader() {
        ArrayList<String> list = new ArrayList<String>();
        list.add("机具名称");
        list.add("规格型号");
        list.add("单位");
        list.add("数量");
        list.add("设备编码");
        list.add("额定载荷KN");
        list.add("试验载荷KN");
        list.add("持荷时间min");
        list.add("试验日期");
        list.add("下次试验日期");
        list.add("检验结论");
        list.add("备注");
        return list;
    }
}
