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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.json.JSONObject;
import com.ah.sbd.SmsTool;
import com.ah.sbd.utils.param.SmsParam;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.constant.BmConfigItems;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.domain.BmFileInfo;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.biz.enums.LeaseInfoEnum;
import com.bonus.common.biz.enums.MessageTypeEnum;
import com.bonus.common.biz.enums.NoticeSmsEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.SpringUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.utils.sms.SmsUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.redis.service.RedisService;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.basic.domain.BmMessage;
import com.bonus.material.basic.mapper.BmMessageMapper;
import com.bonus.material.device.mapper.BmFileInfoMapper;
import com.bonus.material.largeScreen.entity.MaLeaseOnlyInfo;
import com.bonus.material.lease.domain.*;
import com.bonus.material.lease.domain.vo.MaLeaseVo;
import com.bonus.material.lease.mapper.MaLeaseInfoMapper;
import com.bonus.material.lease.service.MaLeaseInfoService;
import com.bonus.material.notice.entity.Notice;
import com.bonus.material.notice.mapper.NoticeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 租赁需求大厅实现层
 *
 * @Author ma_sh
 * @create 2024/11/26 10:42
 */
@Service
@Slf4j
public class MaLeaseInfoServiceImpl implements MaLeaseInfoService {

    @Resource
    private MaLeaseInfoMapper leaseInfoMapper;

    @Resource
    private BmFileInfoMapper bmFileInfoMapper;

    @Resource
    private BmMessageMapper bmMessageMapper;

    @Resource
    private NoticeMapper noticeMapper;

    /**
     * 发布租赁需求
     *
     * @param maLeaseInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(MaLeaseInfo maLeaseInfo) {
        //1.判断手机号是否合法
        if (StringUtils.isNotBlank(maLeaseInfo.getPersonPhone()) && !PhoneUtil.isMobile(maLeaseInfo.getPersonPhone())) {
            return AjaxResult.error(HttpCodeEnum.INVALID_PHONE_FORMAT.getCode(), HttpCodeEnum.INVALID_PHONE_FORMAT.getMsg());
        }
        // 2. 生成需求编号及其他字段
        populateLeaseInfoFields(maLeaseInfo);
        // 3. 插入租赁需求
        int result = leaseInfoMapper.insert(maLeaseInfo);
        if (result > 0 && maLeaseInfo.getId() != null) {
            Integer id = maLeaseInfo.getId();
            //4.插入详情信息
            if (CollectionUtils.isNotEmpty(maLeaseInfo.getDetailsList())) {
                long distinctCodes = maLeaseInfo.getDetailsList().stream().map(MaLeaseDetails::getTypeId).distinct().count();
                if (distinctCodes < maLeaseInfo.getDetailsList().size()) {
                    throw new ServiceException("提交的数据中设备类型存在重复，请勿重复添加", HttpCodeEnum.FAIL.getCode());
                }
                for (MaLeaseDetails maLeaseDetails : maLeaseInfo.getDetailsList()) {
                    if (CollectionUtils.isNotEmpty(maLeaseDetails.getTypeIds())) {
                        maLeaseDetails.setIds(String.join(",", maLeaseDetails.getTypeIds()));
                    }
                    maLeaseDetails.setLeaseId(id);
                    result += leaseInfoMapper.insertDetails(maLeaseDetails);
                    if (result > 0 && maLeaseDetails.getId() != null) {
                        insertFile(maLeaseDetails, id);
                    }
                }
            }
        }
        //发送短信通知
        if (NoticeSmsEnum.SENDSMS_ENABLED.getCode().equals(maLeaseInfo.getIsSms())) {
            Notice notice = new Notice();
            notice.setDeptId(maLeaseInfo.getDeptId());
            notice.setRoleId(maLeaseInfo.getRoleId());
            List<Notice> smsList = noticeMapper.getSmsList(notice);
            if (org.springframework.util.CollectionUtils.isEmpty(smsList)) {
                return AjaxResult.error("所选组织机构及角色下属人员信息为空，无法进行发送短信通知公告服务");
            }
            if (!org.springframework.util.CollectionUtils.isEmpty(smsList)) {
                for (Notice info : smsList) {
                    if (StringUtils.isBlank(info.getPhoneNumber())) {
                        continue;
                    }
                    String phoneNumber = info.getPhoneNumber();
                    if (Objects.nonNull(info.getPhoneNumber()) && info.getPhoneNumber().length() > 11) {
                        phoneNumber = Sm4Utils.decrypt(info.getPhoneNumber());
                    }
                    // 根据电话号码数量发送短信
                    JSONObject sendResult = SmsTool.sendSms(new SmsParam(phoneNumber, notice.getNoticeContent()), BmConfigItems.ANHUI_COMPANY_SMS_KEY);
                    //String sendResult = SmsUtils.smsToken(phoneNumber, maLeaseInfo.getLeaseName(), "");
                    if (StringUtils.isBlank(sendResult.toString())) {
                        return AjaxResult.error("短信发送失败");
                    } else {
                        System.out.println("短信发送成功:" + sendResult);
                    }
                }
            }
        }

        // 5. 返回成功结果
        return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg());
    }

    /**
     * 插入文件信息
     *
     * @param maLeaseDetails
     * @param id
     */
    private void insertFile(MaLeaseDetails maLeaseDetails, Integer id) {
        if (CollectionUtils.isNotEmpty(maLeaseDetails.getFileInfoList())) {
            List<BmFileInfo> bmFileInfos = new ArrayList<>();
            for (BmFileInfo fileInfo : maLeaseDetails.getFileInfoList()) {
                fileInfo.setModelId(Long.valueOf(id));
                fileInfo.setTaskType(MaterialConstants.LEASE_FILE_TYPE_CODE);
                fileInfo.setFileType(1L);
                fileInfo.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
                bmFileInfos.add(fileInfo);
            }
            bmFileInfoMapper.insertBmFileInfos(bmFileInfos);
        }
    }

    /**
     * 修改租赁需求
     *
     * @param maLeaseInfo
     * @return
     */
    @Override
    @Transactional
    public AjaxResult edit(MaLeaseInfo maLeaseInfo) {
        if (maLeaseInfo.getId() == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        //判断手机号是否合法
        if (StringUtils.isNotBlank(maLeaseInfo.getPersonPhone()) && !PhoneUtil.isMobile(maLeaseInfo.getPersonPhone())) {
            return AjaxResult.error(HttpCodeEnum.INVALID_PHONE_FORMAT.getCode(), HttpCodeEnum.INVALID_PHONE_FORMAT.getMsg());
        }
        //根据id修改租赁需求信息
        Long userId = SecurityUtils.getUserId();
        maLeaseInfo.setUpdateBy(String.valueOf(userId));
        maLeaseInfo.setUpdateTime(DateUtils.getNowDate());
        if (maLeaseInfo.getIsSubmit() != null && maLeaseInfo.getIsSubmit()) {
            maLeaseInfo.setLeaseStatus(LeaseInfoEnum.LEASE_PENDING_ORDER.getStatus());
            maLeaseInfo.setStartTime(DateUtils.getNowDate());
            maLeaseInfo.setPublishUser(String.valueOf(userId));
            if (maLeaseInfo.getEndTime() != null && maLeaseInfo.getEndTime().before(new Date())) {
                return AjaxResult.error(HttpCodeEnum.LEASE_END_TIME_ERROR.getCode(), HttpCodeEnum.LEASE_END_TIME_ERROR.getMsg());
            }
        }
        int result = leaseInfoMapper.updateDevInfo(maLeaseInfo);
        //根据id查询删除详情信息
        result += leaseInfoMapper.deleteDetailsById(maLeaseInfo);
        //首先根据id查询文件信息是否存在
        BmFileInfo bmFileInfo = new BmFileInfo();
        bmFileInfo.setModelId(Long.valueOf(maLeaseInfo.getId()));
        bmFileInfo.setTaskType(MaterialConstants.LEASE_FILE_TYPE_CODE);
        List<BmFileInfo> bmFileInfoList = bmFileInfoMapper.selectBmFileInfoList(bmFileInfo);
        if (CollectionUtils.isNotEmpty(bmFileInfoList)) {
            bmFileInfoMapper.deleteBmFileInfoByIds(bmFileInfoList.stream().map(BmFileInfo::getId).toArray(Long[]::new));
        }
        //插入文件信息
        if (CollectionUtils.isNotEmpty(maLeaseInfo.getDetailsList())) {
            long distinctCodes = maLeaseInfo.getDetailsList().stream().map(MaLeaseDetails::getTypeId).distinct().count();
            if (distinctCodes < maLeaseInfo.getDetailsList().size()) {
                throw new ServiceException("提交的数据中设备类型存在重复，请勿重复添加", HttpCodeEnum.FAIL.getCode());
            }
            for (MaLeaseDetails maLeaseDetails : maLeaseInfo.getDetailsList()) {
                if (CollectionUtils.isNotEmpty(maLeaseDetails.getTypeIds())) {
                    maLeaseDetails.setIds(String.join(",", maLeaseDetails.getTypeIds()));
                }
                maLeaseDetails.setLeaseId(maLeaseInfo.getId());
                result += leaseInfoMapper.insertDetails(maLeaseDetails);
                if (result > 0 && maLeaseDetails.getId() != null) {
                    insertFile(maLeaseDetails, maLeaseInfo.getId());
                }
            }
        }
        return result > 0 ? AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg()) : AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 查询单个租赁需求详情
     *
     * @param maLeaseInfo
     * @return
     */
    @Override
    public AjaxResult getById(MaLeaseInfo maLeaseInfo) {
        // 1. 参数检查
        if (maLeaseInfo.getId() == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }

        // 2. 查询租赁信息
        MaLeaseVo maLeaseVo = leaseInfoMapper.selectByName(maLeaseInfo);
        maLeaseVo.setOrderPhone(Sm4Utils.decrypt(maLeaseVo.getOrderPhone()));
        List<MaLeaseDetails> leaseDetailsList = leaseInfoMapper.selectDetailsById(maLeaseInfo);

        // 3. 处理租赁详情信息
        if (CollectionUtil.isNotEmpty(leaseDetailsList)) {
            // 处理每个租赁详情
            processLeaseDetails(leaseDetailsList, maLeaseVo.getId());
            maLeaseVo.setLeaseTotalNum(leaseDetailsList.stream().mapToInt(MaLeaseDetails::getLeaseNum).sum());
        }

        // 4. 更新浏览量（仅在待接单状态时）
        updateHotSearchIfNeeded(maLeaseVo, maLeaseInfo.getId());

        // 5. 返回结果
        maLeaseVo.setDetailsList(leaseDetailsList);
        return AjaxResult.success(maLeaseVo);
    }

    /**
     * 查询文件信息
     *
     * @param modelId
     * @param fileType
     * @return
     */
    private List<BmFileInfo> getBmFileInfoList(Integer modelId, Long fileType) {
        BmFileInfo bmFileInfo = new BmFileInfo();
        bmFileInfo.setModelId(Long.valueOf(modelId));
        bmFileInfo.setTaskType(MaterialConstants.LEASE_FILE_TYPE_CODE);
        bmFileInfo.setFileType(fileType);
        return bmFileInfoMapper.selectBmFileInfoList(bmFileInfo);
    }

    /**
     * 处理租赁详情
     *
     * @param leaseDetailsList
     * @param modelId
     */
    private void processLeaseDetails(List<MaLeaseDetails> leaseDetailsList, Integer modelId) {
        List<String> list = new ArrayList<>();
        for (MaLeaseDetails details : leaseDetailsList) {
            if (StringUtils.isNotBlank(details.getIds())) {
                String[] idsArray = StringUtils.split(details.getIds(), ",");
                // 将所有 IDs 添加到 list 中
                list.addAll(Arrays.asList(idsArray));
                details.setTypeIds(list);
            }
            // 查询文件信息：FileType = 1
            List<BmFileInfo> fileList = getBmFileInfoList(modelId, 1L);
            if (CollectionUtil.isNotEmpty(fileList)) {
                details.setFileInfoList(fileList);
            }
        }
    }

    /**
     * 更新浏览量（仅在待接单状态时）
     *
     * @param maLeaseVo
     * @param leaseId
     */
    private void updateHotSearchIfNeeded(MaLeaseVo maLeaseVo, Integer leaseId) {
        try {
            if (maLeaseVo.getLeaseStatus() != null && maLeaseVo.getLeaseStatus().equals(LeaseInfoEnum.LEASE_PENDING_ORDER.getStatus())) {
                updateHotSearch(leaseId);
            }
        } catch (Exception e) {
            log.error("更新租赁需求浏览量失败, 不影响主业务流程", e);
        }
    }

    /**
     * 更新浏览量
     *
     * @param id
     */
    private void updateHotSearch(Integer id) {
        int count = leaseInfoMapper.getHotSearchCountByLeaseId(id);
        if (count == 0) {
            leaseInfoMapper.insertHotSearch(id);
        } else {
            leaseInfoMapper.updateHotSearchByLeaseId(id);
        }
    }

    /**
     * 查询租赁需求列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<MaLeaseVo> list(MaLeaseDto dto) {
        //获取当前登录人id
        String companyId = String.valueOf(SecurityUtils.getLoginUser().getSysUser().getCompanyId());
        dto.setPublishCompany(companyId);
        List<MaLeaseVo> list = leaseInfoMapper.list(dto);
        //查询列表中数据，如果需求截止日期超过当前，则修改状态为已过期
        for (MaLeaseVo maLeaseVo : list) {
            Date endTime = maLeaseVo.getEndTime();
            maLeaseVo.setOrderPhone(Sm4Utils.decrypt(maLeaseVo.getOrderPhone()));
            if (maLeaseVo.getLeaseStatus().equals(LeaseInfoEnum.LEASE_PENDING_ORDER.getStatus())
                    && endTime != null && endTime.before(new Date())) {
                //根据id修改状态为已过期
                MaLeaseInfo maLeaseInfo = new MaLeaseInfo();
                maLeaseInfo.setId(maLeaseVo.getId());
                maLeaseInfo.setLeaseStatus(LeaseInfoEnum.LEASE_PAST_DUE.getStatus());
                maLeaseInfo.setUpdateTime(DateUtils.getNowDate());
                int result = leaseInfoMapper.updateDevInfo(maLeaseInfo);
                if (result > 0) {
                    maLeaseVo.setLeaseStatusName(LeaseInfoEnum.LEASE_PAST_DUE.getStatusName());
                }
            }
        }
        return list;
    }

    /**
     * 删除租赁需求
     *
     * @param maLeaseInfo
     * @return
     */
    @Override
    public AjaxResult deleteById(MaLeaseInfo maLeaseInfo) {
        if (maLeaseInfo.getId() == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        //根据id查询租赁需求详情，已接单状态不可删除
        MaLeaseVo maLeaseVo = leaseInfoMapper.selectByName(maLeaseInfo);
        if (maLeaseVo != null && maLeaseVo.getLeaseStatus().equals(LeaseInfoEnum.LEASE_ORDER_RECEIVED.getStatus())) {
            return AjaxResult.error(HttpCodeEnum.LEASE_ORDER_RECEIVED_NOT_DELETE.getCode(), HttpCodeEnum.LEASE_ORDER_RECEIVED_NOT_DELETE.getMsg());
        }
        int result = leaseInfoMapper.deleteById(maLeaseInfo);
        //首先根据id查询文件信息是否存在
        BmFileInfo bmFileInfo = new BmFileInfo();
        bmFileInfo.setModelId(Long.valueOf(maLeaseInfo.getId()));
        bmFileInfo.setTaskType(MaterialConstants.LEASE_FILE_TYPE_CODE);
        List<BmFileInfo> bmFileInfoList = bmFileInfoMapper.selectBmFileInfoList(bmFileInfo);
        if (result > 0 && CollectionUtils.isNotEmpty(bmFileInfoList)) {
            bmFileInfoMapper.deleteBmFileInfoByIds(bmFileInfoList.stream().map(BmFileInfo::getId).toArray(Long[]::new));
        }
        //根据id查询删除详情信息
        result += leaseInfoMapper.deleteDetailsById(maLeaseInfo);
        return result > 0 ? AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg()) : AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 查询租赁需求列表首页
     *
     * @param maLease
     * @return
     */
    @Override
    public List<MaLeaseVo> leaseList(MaLease maLease) {
        List<MaLeaseVo> list;
        list = leaseInfoMapper.leaseList(maLease);
        int result = 0;
        //查询列表中数据，如果需求截止日期超过当前，则修改状态为已过期
        for (MaLeaseVo maLeaseVo : list) {
            Date endTime = maLeaseVo.getEndTime();
            if (maLeaseVo.getLeaseStatus().equals(LeaseInfoEnum.LEASE_PENDING_ORDER.getStatus())
                    && endTime != null && endTime.before(new Date())) {
                //根据id修改状态为已过期
                MaLeaseInfo maLeaseInfo = new MaLeaseInfo();
                maLeaseInfo.setId(maLeaseVo.getId());
                maLeaseInfo.setLeaseStatus(LeaseInfoEnum.LEASE_PAST_DUE.getStatus());
                maLeaseInfo.setUpdateTime(DateUtils.getNowDate());
                result = leaseInfoMapper.updateDevInfo(maLeaseInfo);
            }
        }
        if (result > 0) {
            list = leaseInfoMapper.leaseList(maLease);
        }
        if (CollectionUtils.isNotEmpty(list)) {
            for (MaLeaseVo maLeaseVo : list) {
                MaLeaseInfo maLeaseInfo = new MaLeaseInfo();
                maLeaseInfo.setId(maLeaseVo.getId());
                List<MaLeaseDetails> leaseDetailsList = leaseInfoMapper.selectDetailsById(maLeaseInfo);
                if (CollectionUtils.isNotEmpty(leaseDetailsList)) {
                    // 使用 StringBuilder 来拼接 firstGroupName，避免最后一个逗号
                    StringBuilder firstGroupNameBuilder = new StringBuilder();
                    for (MaLeaseDetails maLeaseDetails : leaseDetailsList) {
                        if (StringUtils.isNotBlank(maLeaseDetails.getGroupName())) {
                            // 截取 groupName 中第一个 / 之前的数据
                            String[] split = maLeaseDetails.getGroupName().split("/");
                            if (split.length > 0) {
                                maLeaseDetails.setFirstGroupName(split[0]);
                            }
                        }
                        // 拼接 firstGroupName，避免最后一个逗号
                        if (StringUtils.isNotBlank(maLeaseDetails.getFirstGroupName())) {
                            if (firstGroupNameBuilder.length() > 0) {
                                firstGroupNameBuilder.append("、");
                            }
                            firstGroupNameBuilder.append(maLeaseDetails.getFirstGroupName());
                        }
                    }
                    // 设置拼接后的 firstGroupName
                    maLeaseVo.setGroupName(firstGroupNameBuilder.toString());
                }
            }
        }
        return list;
    }

    @Override
    public List<MaLeaseInfo> getLeaseStatusCount(MaLeaseInfo info) {
        //true:出租方  false:承租方
        if (info.isFlag()) {
            info.setOrderCompany(String.valueOf(SecurityUtils.getLoginUser().getSysUser().getCompanyId()));
        } else {
            info.setPublishCompany(String.valueOf(SecurityUtils.getLoginUser().getSysUser().getCompanyId()));
        }
        return leaseInfoMapper.getLeaseStatusCount(info);
    }

    /**
     * 出租方立即接单
     *
     * @param maLeaseInfo
     * @return
     */
    @Override
    public AjaxResult accept(MaLeaseInfo maLeaseInfo) {
        if (maLeaseInfo.getId() == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        Long userId = SecurityUtils.getUserId();
        Long companyId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        maLeaseInfo.setOrderUser(String.valueOf(userId));
        maLeaseInfo.setOrderCompany(String.valueOf(companyId));
        maLeaseInfo.setOrderTime(DateUtils.getNowDate());
        maLeaseInfo.setLeaseStatus(LeaseInfoEnum.LEASE_ORDER_AUDIT.getStatus());
        int result = leaseInfoMapper.updateDevInfo(maLeaseInfo);
        MaLeaseInfo leaseInfo = leaseInfoMapper.getDevInfoById(maLeaseInfo.getId());
        try {
            BmMessage bmMessage = new BmMessage();
            bmMessage.setCreateTime(DateUtils.getNowDate());
            bmMessage.setMessageContent("您好，您的需求已被" + leaseInfo.getOrderCompanyName() + "接单，请及时查看");
            bmMessage.setMessageType(String.valueOf(MessageTypeEnum.DEMAND_MESSAGE.getType()));
            bmMessage.setUuid(String.valueOf(UUID.randomUUID()));
            bmMessage.setFromCompany(0L);
            bmMessage.setFromUser(0L);
            bmMessage.setFromCompanyName("系统");

            bmMessage.setToCompanyName(leaseInfo.getPublishCompanyName());
            bmMessage.setToUser(Long.parseLong(leaseInfo.getPublishUser()));
            bmMessage.setToCompany(Long.parseLong(leaseInfo.getPublishCompany()));
            bmMessage.setIsRead(0);

            String msgKey = MaterialConstants.CACHE_MATERIAL_MALL_MESSAGE + bmMessage.getFromCompany() + ":" + bmMessage.getToCompany();
            JSONArray arrayCache = SpringUtils.getBean(RedisService.class).getCacheObject(msgKey);
            if (arrayCache == null) {
                arrayCache = new JSONArray();
            }
            List<BmMessage> list = arrayCache.toList(BmMessage.class);
            list.add(bmMessage);
            (SpringUtils.getBean(RedisService.class)).setCacheObject(msgKey, list, MaterialConstants.CACHE_MATERIAL_MALL_MESSAGE_HOURS, TimeUnit.HOURS);
            bmMessageMapper.insertBmMessage(bmMessage);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
        return result > 0 ? AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg()) : AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult agreeOrReject(MaLeaseInfo maLeaseInfo) {
        int result = 0;
        if (maLeaseInfo.getId() == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        if (maLeaseInfo.getLeaseStatus() == 1) {
            maLeaseInfo.setAgreeUser(String.valueOf(SecurityUtils.getUserId()));
            result = leaseInfoMapper.updateDevInfo(maLeaseInfo);
            MaLeaseInfo leaseInfo = leaseInfoMapper.getDevInfoById(maLeaseInfo.getId());
            BmMessage bmMessage = new BmMessage();
            bmMessage.setCreateTime(DateUtils.getNowDate());
            bmMessage.setMessageContent("您好，您的接单需求" + leaseInfo.getPublishCompanyName() + "已同意");
            bmMessage.setMessageType(String.valueOf(MessageTypeEnum.DEMAND_MESSAGE.getType()));
            bmMessage.setUuid(String.valueOf(UUID.randomUUID()));
            bmMessage.setFromCompany(0L);
            bmMessage.setFromUser(0L);
            bmMessage.setFromCompanyName("系统");

            bmMessage.setToCompanyName(leaseInfo.getOrderCompanyName());
            bmMessage.setToUser(Long.parseLong(leaseInfo.getOrderUser()));
            bmMessage.setToCompany(Long.parseLong(leaseInfo.getOrderCompany()));
            bmMessage.setIsRead(0);

            String msgKey = MaterialConstants.CACHE_MATERIAL_MALL_MESSAGE + bmMessage.getFromCompany() + ":" + bmMessage.getToCompany();
            JSONArray arrayCache = SpringUtils.getBean(RedisService.class).getCacheObject(msgKey);
            if (arrayCache == null) {
                arrayCache = new JSONArray();
            }
            List<BmMessage> list = arrayCache.toList(BmMessage.class);
            list.add(bmMessage);
            (SpringUtils.getBean(RedisService.class)).setCacheObject(msgKey, list, MaterialConstants.CACHE_MATERIAL_MALL_MESSAGE_HOURS, TimeUnit.HOURS);
            bmMessageMapper.insertBmMessage(bmMessage);
        }
        if (maLeaseInfo.getLeaseStatus() == 4) {
            maLeaseInfo.setRejectUser(String.valueOf(SecurityUtils.getUserId()));
            MaLeaseInfo leaseInfo = leaseInfoMapper.getDevInfoById(maLeaseInfo.getId());
            BmMessage bmMessage = new BmMessage();
            bmMessage.setCreateTime(DateUtils.getNowDate());
            bmMessage.setMessageContent("您好，您的接单请求已被" + leaseInfo.getPublishCompanyName() + "驳回");
            bmMessage.setUuid(String.valueOf(UUID.randomUUID()));
            bmMessage.setFromCompany(0L);
            bmMessage.setFromUser(0L);
            bmMessage.setFromCompanyName("系统");

            bmMessage.setToCompanyName(leaseInfo.getOrderCompanyName());
            bmMessage.setToUser(Long.parseLong(leaseInfo.getOrderUser()));
            bmMessage.setToCompany(Long.parseLong(leaseInfo.getOrderCompany()));
            bmMessage.setIsRead(0);

            String msgKey = MaterialConstants.CACHE_MATERIAL_MALL_MESSAGE + bmMessage.getFromCompany() + ":" + bmMessage.getToCompany();
            JSONArray arrayCache = SpringUtils.getBean(RedisService.class).getCacheObject(msgKey);
            if (arrayCache == null) {
                arrayCache = new JSONArray();
            }
            List<BmMessage> list = arrayCache.toList(BmMessage.class);
            list.add(bmMessage);
            (SpringUtils.getBean(RedisService.class)).setCacheObject(msgKey, list, MaterialConstants.CACHE_MATERIAL_MALL_MESSAGE_HOURS, TimeUnit.HOURS);
            bmMessageMapper.insertBmMessage(bmMessage);
            result = leaseInfoMapper.updateRejectDevInfo(maLeaseInfo);
        }
        return result > 0 ? AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg()) : AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 最需装备二级页面
     *
     * @param dto
     * @return
     */
    @Override
    public List<MaLeaseOnlyInfo> getDetails(MaLeaseOnlyInfo dto) {
        List<MaLeaseOnlyInfo> list = leaseInfoMapper.getLeaseOnlyInfo(null);
        String topPopularTypeName = leaseInfoMapper.getTopPopularTypeName();
        // 从list集合中获取和topPopularTypeName相同名称的数据
        List<MaLeaseOnlyInfo> infos = list.stream().filter(item -> item.getDeviceName().equals(topPopularTypeName)).collect(Collectors.toList());
        if (StringUtils.isNotBlank(dto.getKeyWord())) {
            infos = infos.stream()
                    .filter(item -> containsKeyword(item, dto.getKeyWord()))
                    .collect(Collectors.toList());
        }
        return infos;
    }

    /**
     * 判断MaLeaseOnlyInfo对象是否包含关键字
     *
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(MaLeaseOnlyInfo item, String keyWord) {
        return (item.getDeviceName() != null && item.getDeviceName().contains(keyWord)) ||
                (item.getPublishCompany() != null && item.getPublishCompany().contains(keyWord)) ||
                (item.getPerson() != null && item.getPerson().contains(keyWord)) ||
                (item.getPhoneNumber() != null && item.getPhoneNumber().contains(keyWord));
    }

    /**
     * 查询出租方需求列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<MaLeaseVo> rentList(MaLeaseDto dto) {
        dto.setOrderCompany(String.valueOf(SecurityUtils.getLoginUser().getSysUser().getCompanyId()));
        return leaseInfoMapper.rentList(dto);
    }

    /**
     * 设置租赁需求的必要字段
     *
     * @param maLeaseInfo
     */
    private void populateLeaseInfoFields(MaLeaseInfo maLeaseInfo) {
        String code = getString();
        Long userId = SecurityUtils.getUserId();
        maLeaseInfo.setLeaseCode(code);
        maLeaseInfo.setCreateBy(String.valueOf(userId));
        maLeaseInfo.setCreateTime(DateUtils.getNowDate());
        maLeaseInfo.setLeaseStatus(LeaseInfoEnum.LEASE_PENDING_ORDER.getStatus());
        maLeaseInfo.setStartTime(DateUtils.getNowDate());
        maLeaseInfo.setPublishUser(String.valueOf(userId));
        maLeaseInfo.setPublishCompany(String.valueOf(SecurityUtils.getLoginUser().getSysUser().getDeptId()));
    }

    /**
     * 生成需求编号
     *
     * @return
     */
    private String getString() {
        //根据前台传过来的数据，生成需求编号
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String taskNum = leaseInfoMapper.selectTaskNumByMonth(nowDate);
        if (StringUtils.isNotBlank(taskNum)) {
            // 将字符串转换为整数
            int num = Integer.parseInt(taskNum);
            // 执行加一操作
            num++;
            // 将结果转换回字符串格式，并确保结果是4位数，不足4位则在前面补0
            taskNum = String.format("%04d", num);
        } else {
            taskNum = "0001";
        }
        return format + "-" + taskNum;
    }
}
