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

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.enums.ApprovalStatusEnum;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.approval.annotation.ApprovalRequired;
import com.bonus.material.approval.domain.ApprovalInstance;
import com.bonus.material.approval.domain.ApprovalRecord;
import com.bonus.material.approval.mapper.ApprovalInstanceMapper;
import com.bonus.material.approval.mapper.ApprovalRecordMapper;
import com.bonus.material.back.domain.BackCsDeviceDetails;
import com.bonus.material.back.domain.BackCsDeviceInfo;
import com.bonus.material.back.domain.BackCsDeviceVo;
import com.bonus.material.back.mapper.BackChangeMapper;
import com.bonus.material.back.service.BackChangeService;
import com.bonus.material.common.constants.TypeConstants;
import com.bonus.material.common.enums.TypeEnums;
import com.bonus.material.devchange.domain.CsDeviceInfo;
import com.bonus.material.repair.domain.ToBeRepair;
import com.bonus.material.repair.mapper.RepairMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

import static com.bonus.common.biz.constant.MaterialConstants.ADMIN_ID;
import static com.bonus.common.biz.constant.MaterialConstants.PROVINCE_COMPANY_DEPT_ID;

/**
 * 设备退库
 *
 * @author ma_sh
 */
@Service
@Slf4j
public class BackChangeServiceImpl implements BackChangeService {

    @Resource
    private BackChangeMapper mapper;

    @Resource
    private RepairMapper repairMapper;

    @Resource
    private ApprovalInstanceMapper instanceMapper;

    @Resource
    private ApprovalRecordMapper recordMapper;

    /**
     * 获取添加设备详情
     *
     * @param dto
     * @return
     */
    @Override
    public List<BackCsDeviceDetails> getDevDetailsInfo(BackCsDeviceDetails dto) {
        try {
            if (StringUtils.isBlank(dto.getProCode())) {
                return new ArrayList<>();
            }
            Long thisLoginUserDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            dto.setCompanyId(thisLoginUserDeptId);


            return mapper.getDevDetailsInfo(dto);

        } catch (Exception e) {
            log.error(e.getMessage());
            return new ArrayList<>();
        }
    }

    /**
     * 新增退库申请
     *
     * @param csDeviceVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @ApprovalRequired(
            businessType = "EQUIPMENT_RETURN",
            businessIdExpr = "#result['data']",
            businessDataExpr = "#csDeviceVo"
    )
    public AjaxResult addDevDetails(BackCsDeviceVo csDeviceVo) {
        try {


            if (csDeviceVo == null || csDeviceVo.getDevInfo() == null || CollectionUtils.isEmpty(csDeviceVo.getDevDetailsList())) {
                return AjaxResult.error("请选择需要添加的设备");
            }

            // 判断提交的数据csDeviceVo.getDevDetailsList()中是否存在相同编号或者数量设备typeId相同的数据
            Set<String> devCodeSet = new HashSet<>();
            Set<Long> typeIdSet = new HashSet<>();

            for (BackCsDeviceDetails details : csDeviceVo.getDevDetailsList()) {
                if (details == null) {
                    continue;
                }
                if (ObjectUtils.isEmpty(details.getUseTime())) {
                    return AjaxResult.error(details.getTypeName() + ",退库日期不能为空", AjaxResult.class);
                }
                // 核心业务逻辑
                // ========== 步骤1：获取并处理所有涉及的数值（统一空值转0，消除空指针） ==========
                // 查询在途单据数量（可能为null，转0）
                BigDecimal onWayNum = Optional.ofNullable(mapper.getDetailsNum(details)).orElse(BigDecimal.ZERO);
                // 获取已使用数量（可能为null，转0）
                BigDecimal usedNum = Optional.ofNullable(details.getUseNum()).orElse(BigDecimal.ZERO);
                // 获取本次申请数量（可能为null，转0）
                BigDecimal applyNum = Optional.ofNullable(details.getNum()).orElse(BigDecimal.ZERO);

                // ========== 步骤2：计算总占用数量（在途 + 本次申请） ==========
                BigDecimal totalOccupyNum = onWayNum.add(applyNum);

                // ========== 步骤3：业务校验（usedNum < totalOccupyNum 时触发错误） ==========
                if (usedNum.compareTo(totalOccupyNum) < 0) {
                    // 格式化数值：根据业务场景选择舍入模式（此处以保留2位小数、四舍五入为例，可调整）
                    // 注意：展示的是总占用数量，与校验逻辑一致，避免用户误解
                    String totalOccupyNumStr = formatBigDecimal(onWayNum, 0, RoundingMode.HALF_UP);
                    String applyNumStr = formatBigDecimal(applyNum, 0, RoundingMode.HALF_UP);
                    String typeName = details.getTypeName();

                    // 构建错误信息
                    String errorMsg = String.format("%s，已有在途单据，在途数量%s，本次申请数量%s", typeName, totalOccupyNumStr, applyNumStr);

                    // 记录日志：包含关键参数，便于问题排查
                    log.warn("业务校验失败：{}，已使用数量={}，在途数量={}，本次申请数量={}",
                            errorMsg, usedNum, onWayNum, applyNum);

                    // 返回错误结果
                    return AjaxResult.error(errorMsg, AjaxResult.class);
                }

                Date updateTime = details.getUpdateTime();
                LocalDate updateLocalDate = updateTime.toInstant()
                        .atZone(ZoneId.systemDefault()) // 转换为带时区的ZonedDateTime
                        .toLocalDate(); // 提取日期部分

                // 步骤2：获取useTime并比较
                LocalDate useTime = details.getUseTime();

                boolean isUseTimeGreater = !useTime.isBefore(updateLocalDate);
                if (!isUseTimeGreater) {
                    return AjaxResult.error(details.getTypeName() + ",退库日期不能早于出库日期", AjaxResult.class);
                }
                // 编码重复
                String devCode = details.getDevCode();
                if (!devCode.equals("/") && StringUtils.isNotBlank(devCode) && devCodeSet.contains(devCode)) {
                    return AjaxResult.error("添加的列表中设备编号存在重复：" + devCode);
                } else if (StringUtils.isNotBlank(devCode)) {
                    devCodeSet.add(devCode);
                }
                // typeId重复
                Long typeId = details.getTypeId();
                if (typeId != null && typeIdSet.contains(typeId)) {
                    return AjaxResult.error("添加的列表中设备类型存在重复！");
                } else if (typeId != null && "1".equals(details.getManageType())) {
                    typeIdSet.add(typeId);
                }
            }

            String nickName = SecurityUtils.getLoginUser().getSysUser().getNickName();
            // 获取申请编号
            int thisMonthMaxOrder = mapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TypeEnums.TM_TASK_BACK.getTaskTypeId());
            String code = genderTaskCode(thisMonthMaxOrder);
            BackCsDeviceInfo devInfo = csDeviceVo.getDevInfo();
            devInfo.setCode(code);
            devInfo.setCreateBy(nickName);
            devInfo.setTaskStatus("0");
            devInfo.setCompanyId(SecurityUtils.getLoginUser().getSysUser().getDeptId());
            // 添加主任务
            int num = mapper.addChangeInfoNew(devInfo);
            if (num < 1) {
                throw new RuntimeException("添加主任务失败");
            }
            csDeviceVo.getDevDetailsList().forEach(devDetails -> {
                devDetails.setChangeId(devInfo.getId());
                devDetails.setCreateBy(nickName);
                devDetails.setCreateTime(DateUtils.getNowDate());
            });
            // 添加设备详情
            num = mapper.addDetails(csDeviceVo.getDevDetailsList());
            if (num < 1) {
                throw new RuntimeException("添加设备详情失败");
            }

            // 设置任务ID到devInfo中（用于审批流）
            csDeviceVo.getDevInfo().setId(devInfo.getId());

        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return AjaxResult.success("退库申请提交成功，等待审批", csDeviceVo.getDevInfo().getId());
    }


    // ========== 工具方法：封装BigDecimal格式化逻辑（复用性高） ==========

    /**
     * 格式化BigDecimal为字符串，避免科学计数法，处理空值
     *
     * @param value        待格式化的BigDecimal（可为null）
     * @param scale        保留小数位数
     * @param roundingMode 舍入模式（推荐使用枚举，更直观）
     * @return 格式化后的字符串
     */
    private String formatBigDecimal(BigDecimal value, int scale, RoundingMode roundingMode) {
        // 空值转0后再格式化，消除空指针
        return Optional.ofNullable(value)
                .orElse(BigDecimal.ZERO)
                .setScale(scale, roundingMode)
                .toPlainString(); // 避免科学计数法
    }

    /**
     * 生成申请编号
     *
     * @param thisMonthMaxOrder
     * @return
     */
    private String genderTaskCode(int thisMonthMaxOrder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        return TypeConstants.BACK_TASK_TYPE_LABEL + result + String.format("-%04d", thisMonthMaxOrder + 1);
    }

    /**
     * 修改退库申请
     *
     * @param csDeviceVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateDevDetails(BackCsDeviceVo csDeviceVo) {
        try {
            if (csDeviceVo == null || csDeviceVo.getDevInfo() == null || csDeviceVo.getDevInfo().getId() == null
                    || CollectionUtils.isEmpty(csDeviceVo.getDevDetailsList())) {
                return AjaxResult.error("请选择需要修改的设备");
            }
            // 判断提交的数据csDeviceVo.getDevDetailsList()中是否存在相同编号或者数量设备typeId相同的数据
            Set<String> devCodeSet = new HashSet<>();
            Set<Long> typeIdSet = new HashSet<>();

            for (BackCsDeviceDetails details : csDeviceVo.getDevDetailsList()) {
                if (details == null) {
                    continue;
                }
                // 编码重复
                String devCode = details.getDevCode();
                if (!devCode.equals("/") && StringUtils.isNotBlank(devCode) && devCodeSet.contains(devCode)) {
                    return AjaxResult.error("添加的列表中设备编号存在重复：" + devCode);
                } else if (StringUtils.isNotBlank(devCode)) {
                    devCodeSet.add(devCode);
                }
                // typeId重复
                Long typeId = details.getTypeId();
                if (typeId != null && typeIdSet.contains(typeId)) {
                    return AjaxResult.error("添加的列表中设备类型存在重复！");
                } else if (typeId != null && "1".equals(details.getManageType())) {
                    typeIdSet.add(typeId);
                }
            }

            String nickName = SecurityUtils.getLoginUser().getSysUser().getNickName();
            csDeviceVo.getDevInfo().setUpdateBy(nickName);
            // 修改主任务
            csDeviceVo.getDevInfo().setTaskStatus("0");
            csDeviceVo.getDevInfo().setCompanyId(SecurityUtils.getLoginUser().getSysUser().getDeptId());
            int num = mapper.updateCsDevInfo(csDeviceVo.getDevInfo());
            if (num < 1) {
                throw new RuntimeException("修改主任务失败");
            }
            // 先将设备详情删除，重新添加
            num = mapper.deleteChangeDetails(csDeviceVo.getDevInfo().getId());
            if (num < 1) {
                throw new RuntimeException("删除设备详情失败");
            }
            csDeviceVo.getDevDetailsList().forEach(devDetails -> {
                devDetails.setChangeId(csDeviceVo.getDevInfo().getId());
                devDetails.setUpdateBy(nickName);
                devDetails.setCreateBy(nickName);
                devDetails.setCreateTime(DateUtils.getNowDate());
                devDetails.setUpdateTime(DateUtils.getNowDate());
            });
            num = mapper.addDetails(csDeviceVo.getDevDetailsList());
            if (num < 1) {
                throw new RuntimeException("添加设备详情失败");
            }
            // 根据id，针对编辑进行审批流重置修改
            // 根据主id查询目前审批流是否存在驳回数据，驳回需重置审批
            ApprovalInstance approvalInstance = new ApprovalInstance();
            approvalInstance.setBusinessId(csDeviceVo.getDevInfo().getId().toString());
            List<ApprovalInstance> approvalInstances = instanceMapper.selectInstanceList(approvalInstance);
            if (CollectionUtils.isNotEmpty(approvalInstances)) {
                ApprovalInstance instance = approvalInstances.get(0);
                if ("3".equals(instance.getStatus())) {
                    // 如果当前节点为第一节点，则状态修改为待审批
                    if (instance.getCurrentNodeOrder() == 1) {
                        num = instanceMapper.updateInstanceStatus(instance.getId(), ApprovalStatusEnum.PENDING.getCode());
                    } else {
                        // 审批中
                        num = instanceMapper.updateInstanceStatus(instance.getId(), ApprovalStatusEnum.IN_PROGRESS.getCode());
                    }
                    if (num < 1) {
                        throw new RuntimeException("修改审批实例状态失败");
                    }
                    // 根据当前节点及id去记录表查询是否存在驳回记录，存在即删除
                    List<ApprovalRecord> approvalRecords = recordMapper.selectRecordListByNode(instance.getId(), instance.getCurrentNodeId());
                    if (CollectionUtils.isNotEmpty(approvalRecords)) {
                        ApprovalRecord approvalRecord = approvalRecords.get(0);
                        // 如果是驳回状态，则删除
                        if ("2".equals(approvalRecord.getApproveResult())) {
                            num = recordMapper.deleteRecordById(approvalRecord.getId());
                            if (num < 1) {
                                throw new RuntimeException("删除审批记录失败");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("修改失败");
        }
        return AjaxResult.success("修改成功");
    }

    /**
     * 删除退料申请
     *
     * @param csDeviceInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteDevDetails(BackCsDeviceInfo csDeviceInfo) {
        try {
            // 删除主任务
            int num = mapper.deleteChangeInfo(csDeviceInfo);
            if (num < 1) {
                throw new RuntimeException("删除主任务失败");
            }
            // 删除设备详情
            num = mapper.deleteChangeDetails(csDeviceInfo.getId());
            if (num < 1) {
                throw new RuntimeException("删除设备详情失败");
            }
        } catch (RuntimeException e) {
            log.error(e.getMessage());
            throw new RuntimeException("删除失败");
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 获取退料申请详情
     *
     * @param dto
     * @return
     */
    @Override
    public BackCsDeviceVo getDevDetailsById(BackCsDeviceDetails dto) {
        BackCsDeviceVo csDeviceVo = new BackCsDeviceVo();
        // 根据id查询主任务表数据
        BackCsDeviceInfo devInfo = mapper.getDevInfoById(dto);
        // 根据id查询设备详情表数据
        List<BackCsDeviceDetails> devDetailsList = mapper.getDevDetailsById(dto);
        if (CollectionUtils.isNotEmpty(devDetailsList)) {
            // 根据devType去查询装备或工具详情
            for (BackCsDeviceDetails csDeviceDetails : devDetailsList) {
                BackCsDeviceDetails devDetails = new BackCsDeviceDetails();
                if (StringUtils.isNotBlank(csDeviceDetails.getDevType()) && "1".equals(csDeviceDetails.getDevType())) {
                    if ("/".equals(csDeviceDetails.getDevCode())) {
                        csDeviceDetails.setDevCode(null);
                    }
                    devDetails = mapper.getTypeMaDevInfo(csDeviceDetails);
                } else if (StringUtils.isNotBlank(csDeviceDetails.getDevType()) && "2".equals(csDeviceDetails.getDevType())) {
                    if ("/".equals(csDeviceDetails.getDevCode())) {
                        csDeviceDetails.setDevCode(null);
                    }
                    devDetails = mapper.getTypeToolInfo(csDeviceDetails);
                }
                if (devDetails != null) {
                    csDeviceDetails.setCategory(StringUtils.isNotBlank(devDetails.getCategory()) ? devDetails.getCategory() : "");
                    csDeviceDetails.setTypeName(StringUtils.isNotBlank(devDetails.getTypeName()) ? devDetails.getTypeName() : "");
                    csDeviceDetails.setTypeModelName(StringUtils.isNotBlank(devDetails.getTypeModelName()) ? devDetails.getTypeModelName() : "");
                    csDeviceDetails.setManageType(StringUtils.isNotBlank(devDetails.getManageType()) ? devDetails.getManageType() : "");
                    csDeviceDetails.setDevCode(StringUtils.isNotBlank(devDetails.getDevCode()) ? devDetails.getDevCode() : "");
                    csDeviceDetails.setUseNum(devDetails.getUseNum());
                    // 用于编辑显示数据是否选中（前端根据typeId和id结合判断）
                    csDeviceDetails.setId(devDetails.getId());
                }
            }
        }
        csDeviceVo.setDevInfo(devInfo);
        csDeviceVo.setDevDetailsList(devDetailsList);
        return csDeviceVo;
    }

    /**
     * 获取退料申请列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<BackCsDeviceInfo> getList(BackCsDeviceInfo dto) {
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        Long userId = SecurityUtils.getLoginUser().getUserid();
        // 管理员和省公司可查看所有数据
//        if (userId != null && deptId != null
//                && !userId.equals(ADMIN_ID)
//                && !deptId.equals(PROVINCE_COMPANY_DEPT_ID)) {
//            dto.setCompanyId(deptId);
//        }
        if(ADMIN_ID.equals(userId)){
            dto.setCompanyId(1L);
        }else{
            dto.setCompanyId(deptId);
        }

        return mapper.getList(dto);
    }

    /**
     * 审核退库申请
     * 注意：此方法由审批回调内部调用，不应直接暴露给前端
     *
     * @param backCsDeviceDetails
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult approve(BackCsDeviceDetails backCsDeviceDetails) {
        try {
            int num = 0;
            backCsDeviceDetails.setUpdateBy(SecurityUtils.getLoginUser().getUserid().toString());
            // 如果通过，则需要修改设备具体库存及维修数量
            if ("2".equals(backCsDeviceDetails.getTaskStatus())) {
                // 根据id查询设备详情表数据
                List<BackCsDeviceDetails> devDetailsList = mapper.getDevDetailsById(backCsDeviceDetails);
                if (CollectionUtils.isNotEmpty(devDetailsList)) {
                    // 根据devType去查询装备或工具详情
                    for (BackCsDeviceDetails csDeviceDetails : devDetailsList) {
                        BackCsDeviceDetails devDetails = new BackCsDeviceDetails();
                        if (StringUtils.isNotBlank(csDeviceDetails.getDevType()) && "1".equals(csDeviceDetails.getDevType())) {
                            if ("/".equals(csDeviceDetails.getDevCode())) {
                                csDeviceDetails.setDevCode(null);
                            }
                            devDetails = mapper.getTypeMaDevInfo(csDeviceDetails);
                        } else if (StringUtils.isNotBlank(csDeviceDetails.getDevType()) && "2".equals(csDeviceDetails.getDevType())) {
                            if ("/".equals(csDeviceDetails.getDevCode())) {
                                csDeviceDetails.setDevCode(null);
                            }
                            devDetails = mapper.getTypeToolInfo(csDeviceDetails);
                        }
                        if (devDetails != null) {
                            csDeviceDetails.setCategory(StringUtils.isNotBlank(devDetails.getCategory()) ? devDetails.getCategory() : "");
                            csDeviceDetails.setTypeName(StringUtils.isNotBlank(devDetails.getTypeName()) ? devDetails.getTypeName() : "");
                            csDeviceDetails.setTypeModelName(StringUtils.isNotBlank(devDetails.getTypeModelName()) ? devDetails.getTypeModelName() : "");
                            csDeviceDetails.setManageType(StringUtils.isNotBlank(devDetails.getManageType()) ? devDetails.getManageType() : "");
                            csDeviceDetails.setDevCode(StringUtils.isNotBlank(devDetails.getDevCode()) ? devDetails.getDevCode() : "");
                            csDeviceDetails.setUseNum(devDetails.getUseNum());
                        }
                        // 判断在用数量是否有为0的，若有，不予审核通过
                        if (csDeviceDetails.getUseNum().compareTo(BigDecimal.ZERO) == 0) {
                            return AjaxResult.error("该条单据中存在在用数量为0的设备，无法审核通过，请驳回后进行修改", AjaxResult.class);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(devDetailsList)) {
                    // 创建维修任务
                    String re = createRepairTask(devDetailsList);
                    if ("-1".equals(re)) {
                        throw new RuntimeException("创建维修任务失败");
                    }

                    for (BackCsDeviceDetails csDeviceDetails : devDetailsList) {
                        // 装备
                        if ("1".equals(csDeviceDetails.getDevType())) {
                            // 无需维修，直接入库
                            if ("0".equals(csDeviceDetails.getIsRepair())) {
                                csDeviceDetails.setMaStatus("1");
                                num = mapper.updateMaDevInfo(csDeviceDetails);
                                if (num < 1) {
                                    throw new RuntimeException("修改装备状态失败");
                                }
                            } else if ("1".equals(csDeviceDetails.getIsRepair())) {
                                csDeviceDetails.setMaStatus("5");
                                num = mapper.updateMaDevInfo(csDeviceDetails);
                                if (num < 1) {
                                    throw new RuntimeException("修改装备状态失败");
                                }
                            }
                        }
                        // 工具
                        if ("2".equals(csDeviceDetails.getDevType())) {
                            // 无需维修，直接入库
                            if ("0".equals(csDeviceDetails.getIsRepair())) {
                                if (StringUtils.isNotBlank(csDeviceDetails.getDevCode()) && !"/".equals(csDeviceDetails.getDevCode())) {
                                    csDeviceDetails.setMaStatus("0");
                                    num = mapper.updateToolInfo(csDeviceDetails);
                                    if (num < 1) {
                                        throw new RuntimeException("修改工具设备入库状态失败");
                                    }
                                } else {
                                    num = mapper.updateToolInfoNum(csDeviceDetails);
                                    if (num < 1) {
                                        throw new RuntimeException("修改工具设备入库数量失败");
                                    }
                                }
                            } else if ("1".equals(csDeviceDetails.getIsRepair())) {
                                if (StringUtils.isNotBlank(csDeviceDetails.getDevCode()) && !"/".equals(csDeviceDetails.getDevCode())) {
                                    csDeviceDetails.setMaStatus("2");
                                    num = mapper.updateToolInfoRepair(csDeviceDetails);
                                    if (num < 1) {
                                        throw new RuntimeException("修改工具设备维修状态失败");
                                    }
                                } else {
                                    num = mapper.updateToolInfoRepairNum(csDeviceDetails);
                                    if (num < 1) {
                                        throw new RuntimeException("修改工具设备维修数量失败");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 修改主任务状态为通过或驳回
            num = mapper.approve(backCsDeviceDetails);
            if (num < 1) {
                throw new RuntimeException("修改主任务失败");
            }
        } catch (RuntimeException e) {
            log.error(e.getMessage());
            throw new RuntimeException("审核失败");
        }
        return AjaxResult.success("审核成功");
    }

    private String createRepairTask(List<BackCsDeviceDetails> devDetailsList) {
        try {
            //在此处将需要维修的设备，生成一个维修单
            List<ToBeRepair> toBeRepairList = new ArrayList<>();
            for (BackCsDeviceDetails csDeviceDetails : devDetailsList) {
                if ("1".equals(csDeviceDetails.getIsRepair())) {
                    ToBeRepair toBeRepair = new ToBeRepair();
                    toBeRepair.setCode(csDeviceDetails.getDevCode());
                    toBeRepair.setDevType(csDeviceDetails.getDevType());
                    toBeRepair.setRepairNum(csDeviceDetails.getRealNum());
                    toBeRepair.setTypeId(csDeviceDetails.getTypeId() + "");
                    toBeRepairList.add(toBeRepair);
                }
            }
            //如果有需要维修的设备
            if (toBeRepairList.size() > 0) {
                //创建维修任务
                String userName = SecurityUtils.getLoginUser().getSysUser().getNickName();
                Long changeId = addRepairTask(userName);
                //保存明细
                for (ToBeRepair toBeRepair : toBeRepairList) {
                    toBeRepair.setChangeId(changeId);
                    toBeRepair.setCreateUser(userName);
                    repairMapper.addRepairData(toBeRepair);
                }
            }
            return "1";
        } catch (Exception e) {
            log.error(e.getMessage());
            return "-1";
        }

    }


    /**
     * 创建维修任务
     */
    private Long addRepairTask(String username) throws Exception {
        int maxOrder = repairMapper.getMonthMaxOrderByDate(
                DateUtils.getCurrentYear(),
                DateUtils.getCurrentMonth(),
                TypeEnums.TM_TASK_REPAIR.getTaskTypeId()
        );
        String code = genderRepairTaskCode(maxOrder);
        CsDeviceInfo deviceInfo = new CsDeviceInfo();
        deviceInfo.setType("4");
        deviceInfo.setCode(code);
        deviceInfo.setReviewStatus("5");
        deviceInfo.setCreateUser(username);
        deviceInfo.setCompanyId(SecurityUtils.getLoginUser().getSysUser().getDeptId());
        int result = repairMapper.addDeviceChange(deviceInfo);
        if (result < 1) {
            throw new Exception("添加任务失败");
        }
        return deviceInfo.getId();
    }

    /**
     * 生成维修任务编号
     *
     * @param thisMonthMaxOrder
     * @return
     */
    private String genderRepairTaskCode(int thisMonthMaxOrder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        return TypeConstants.REPAIR_TASK_TYPE_LABEL + result + String.format("-%04d", thisMonthMaxOrder + 1);
    }
}
