package com.usky.fire.service.impl;

import com.ruoyi.common.core.utils.file.ImageUtils;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.fire.domain.*;
import com.usky.fire.mapper.*;
import com.usky.fire.service.*;
import com.usky.fire.service.vo.*;
import com.usky.system.model.LoginUser;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 巡检记录表 服务实现类
 * </p>
 *
 * @author JCB
 * @since 2022-07-21
 */
@Service
public class PatrolInspectionRecordServiceImpl extends AbstractCrudService<PatrolInspectionRecordMapper, PatrolInspectionRecord> implements PatrolInspectionRecordService {

    @Autowired
    private PatrolInspectionRecordPictureService patrolInspectionRecordPictureService;

    @Autowired
    private PatrolInspectionRecordOptionService patrolInspectionRecordOptionService;

    @Autowired
    private PatrolInspectionSiteContentService siteContentService;

    @Autowired
    private PatrolInspectionContentService patrolInspectionContentService;

    @Autowired
    private PatrolInspectionContentOptionService contentOptionService;

    @Autowired
    private PatrolInspectionPlanSonService patrolInspectionPlanSonService;

    @Autowired
    private PatrolInspectionPlanSiteSonService planSiteSonService;

    @Autowired
    private PatrolInspectionPlanMapper patrolInspectionPlanMapper;

    @Autowired
    private PatrolInspectionRecordPictureMapper orphansInspectionRecordPictureMapper;

    @Autowired
    private PatrolInspectionRecordOptionMapper patrolInspectionRecordOptionMapper;

    @Autowired
    private PatrolInspectionContentMapper patrolInspectionContentMapper;

    @Autowired
    private PatrolInspectionContentOptionMapper patrolInspectionContentOptionMapper;

    @Override
    public CommonPage<PatrolInspectionRecord> patrolInspectionRecordLsit(String areaName, String siteName, String name,
                                                                         Integer planType, Integer routeId,
                                                                         String startDateTime, String endDateTime,
                                                                         Integer pageNum, Integer pageSize) {
        IPage<PatrolInspectionRecord> page = new Page<>(pageNum, pageSize);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionRecord::getTenantId, SecurityUtils.getTenantId())
                .like(StringUtils.isNotBlank(areaName), PatrolInspectionRecord::getAreaName, areaName)
                .like(StringUtils.isNotBlank(siteName), PatrolInspectionRecord::getSiteName, siteName)
                .like(StringUtils.isNotBlank(name), PatrolInspectionRecord::getName, name)
                .eq(planType != null && planType != 0, PatrolInspectionRecord::getPlanType, planType)
                .eq(routeId != null, PatrolInspectionRecord::getRouteId, routeId)
                .between(StringUtils.isNotBlank(startDateTime) && StringUtils.isNotBlank(endDateTime), PatrolInspectionRecord::getCreateTime, startDateTime, endDateTime)
                .eq("00".equals(userType), PatrolInspectionRecord::getCreator, SecurityUtils.getUsername());
        queryWrapper.orderByDesc(PatrolInspectionRecord::getId);
        page = this.page(page, queryWrapper);
        return new CommonPage<>(page.getRecords(), page.getTotal(), pageSize, pageNum);
    }


    @Override
    public List<PatrolInspectionRecordVo> patrolInspectionRecordDetails(Integer id) {
        //记录查询
        LambdaQueryWrapper<PatrolInspectionRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionRecord::getTenantId, SecurityUtils.getTenantId())
                .eq(PatrolInspectionRecord::getId, id);
        List<PatrolInspectionRecord> patrolInspectionRecordList = this.list(queryWrapper);
        if (patrolInspectionRecordList.isEmpty()) {
            throw new BusinessException("巡检记录不存在");
        }
        //上传图片查询
        LambdaQueryWrapper<PatrolInspectionRecordPicture> queryWrapperOne = Wrappers.lambdaQuery();
        queryWrapperOne.eq(PatrolInspectionRecordPicture::getRecordId, id);
        List<PatrolInspectionRecordPicture> patrolInspectionRecordPictureList = patrolInspectionRecordPictureService.list(queryWrapperOne);

        //内容选中项查询
        List<Integer> contentOptionIdList = new ArrayList<>();
        LambdaQueryWrapper<PatrolInspectionRecordOption> queryWrapperTwo = Wrappers.lambdaQuery();
        queryWrapperTwo.eq(PatrolInspectionRecordOption::getRecordId, id);
        List<PatrolInspectionRecordOption> patrolInspectionRecordOptionList = patrolInspectionRecordOptionService.list(queryWrapperTwo);
        for (int i = 0; i < patrolInspectionRecordOptionList.size(); i++) {
            if (patrolInspectionRecordOptionList.get(i).getContentOptionId() != null) {
                contentOptionIdList.add(patrolInspectionRecordOptionList.get(i).getContentOptionId());
            }
        }

        //地点内容ID查询
        LambdaQueryWrapper<PatrolInspectionSiteContent> queryWrapperThree = Wrappers.lambdaQuery();
        queryWrapperThree.in(PatrolInspectionSiteContent::getSiteId, patrolInspectionRecordList.get(0).getSiteId());
        List<PatrolInspectionSiteContent> siteContentList = siteContentService.list(queryWrapperThree);

        //内容ID重组
        List<Integer> contentIdList = new ArrayList<>();
        for (int i = 0; i < siteContentList.size(); i++) {
            contentIdList.add(siteContentList.get(i).getContentId());
        }

        //内容查询
        LambdaQueryWrapper<PatrolInspectionContent> queryWrapperFour = Wrappers.lambdaQuery();
        queryWrapperFour.in(PatrolInspectionContent::getId, contentIdList)
                .eq(PatrolInspectionContent::getEnable, 1);
        List<PatrolInspectionContent> patrolInspectionContentList = patrolInspectionContentService.list(queryWrapperFour);

        //内容选择项查询
        LambdaQueryWrapper<PatrolInspectionContentOption> queryWrapperFive = Wrappers.lambdaQuery();
        queryWrapperFive.in(PatrolInspectionContentOption::getContentId, contentIdList)
                .eq(PatrolInspectionContentOption::getEnable, 1);
        List<PatrolInspectionContentOption> contentOptionList = contentOptionService.list(queryWrapperFive);

        //重组内容选项
        List<ContentOptionVo> contentOptionVoList = new ArrayList<>();
        for (int i = 0; i < contentOptionList.size(); i++) {
            ContentOptionVo contentOptionVo = new ContentOptionVo();
            contentOptionVo.setId(contentOptionList.get(i).getId());
            contentOptionVo.setContentId(contentOptionList.get(i).getContentId());
            contentOptionVo.setOptionName(contentOptionList.get(i).getOptionName());
            contentOptionVo.setEnable(contentOptionList.get(i).getEnable());
            contentOptionVo.setCreator(contentOptionList.get(i).getCreator());
            contentOptionVo.setCreateTime(contentOptionList.get(i).getCreateTime());
            contentOptionVo.setSelectStatus(false);
            for (int j = 0; j < patrolInspectionRecordOptionList.size(); j++) {
                if (contentOptionList.get(i).getContentId() == patrolInspectionContentList.get(j).getId()) {
                    contentOptionVo.setRemarks(patrolInspectionRecordOptionList.get(j).getRemarks());
                }
                if (contentOptionList.get(i).getId() == patrolInspectionRecordOptionList.get(j).getContentOptionId()) {
                    contentOptionVo.setSelectStatus(true);
                }
            }
            contentOptionVoList.add(contentOptionVo);
        }

        //重组内容
        List<PatrolInspectionContentVo> patrolInspectionContentVoList = new ArrayList<>();
        for (int i = 0; i < patrolInspectionContentList.size(); i++) {
            PatrolInspectionContentVo patrolInspectionContentVo = new PatrolInspectionContentVo();
            patrolInspectionContentVo.setId(patrolInspectionContentList.get(i).getId());
            patrolInspectionContentVo.setContentTitle(patrolInspectionContentList.get(i).getContentTitle());
            patrolInspectionContentVo.setContentDescribe(patrolInspectionContentList.get(i).getContentDescribe());
            patrolInspectionContentVo.setSubmissionMethod(patrolInspectionContentList.get(i).getSubmissionMethod());
            patrolInspectionContentVo.setTenantId(patrolInspectionContentList.get(i).getTenantId());
            patrolInspectionContentVo.setCreateTime(patrolInspectionContentList.get(i).getCreateTime());
            patrolInspectionContentVo.setCreator(patrolInspectionContentList.get(i).getCreator());
            patrolInspectionContentVo.setEnable(patrolInspectionContentList.get(i).getEnable());
            patrolInspectionContentVo.setCompanyId(patrolInspectionContentList.get(i).getCompanyId());
            List<ContentOptionVo> contentOptionVoListOne = new ArrayList<>();

            if (patrolInspectionContentList.get(i).getSubmissionMethod() == 3) {
                for (int j = 0; j < patrolInspectionRecordOptionList.size(); j++) {
                    if (patrolInspectionRecordOptionList.get(j).getContentOptionId() == null || patrolInspectionRecordOptionList.get(j).getContentOptionId() == 0) {
                        int id11 = patrolInspectionContentList.get(i).getId();
                        int id22 = patrolInspectionRecordOptionList.get(j).getContentId();
                        if (id11 == id22) {
                            if (patrolInspectionRecordOptionList.get(j).getRemarks() != null && !"".equals(patrolInspectionRecordOptionList.get(j).getRemarks())) {
                                patrolInspectionContentVo.setRemarks(patrolInspectionRecordOptionList.get(j).getRemarks());
                            }
                            patrolInspectionContentVo.setContent(patrolInspectionRecordOptionList.get(j).getContent());
                        }
                    }
                }
            } else {
                for (int j = 0; j < contentOptionVoList.size(); j++) {
                    int id1 = patrolInspectionContentList.get(i).getId();
                    int id2 = contentOptionVoList.get(j).getContentId();
                    if (id1 == id2) {
                        if (contentOptionVoList.get(j).getRemarks() != null && !"".equals(contentOptionVoList.get(j).getRemarks())) {
                            patrolInspectionContentVo.setRemarks(contentOptionVoList.get(j).getRemarks());
                        }
                        contentOptionVoListOne.add(contentOptionVoList.get(j));
                        patrolInspectionContentVo.setContentOptionVoList(contentOptionVoListOne);
                    }
                }
            }

            patrolInspectionContentVo.setContentOptionValue(contentOptionIdList);
            patrolInspectionContentVoList.add(patrolInspectionContentVo);
        }

        //重组巡检记录
        List<PatrolInspectionRecordVo> list = new ArrayList<>();
        for (int i = 0; i < patrolInspectionRecordList.size(); i++) {
            PatrolInspectionRecordVo patrolInspectionRecordVo = new PatrolInspectionRecordVo();
            patrolInspectionRecordVo.setId(patrolInspectionRecordList.get(i).getId());
            patrolInspectionRecordVo.setSiteNubmber(patrolInspectionRecordList.get(i).getSiteNubmber());
            patrolInspectionRecordVo.setSiteType(patrolInspectionRecordList.get(i).getSiteType());
            patrolInspectionRecordVo.setAreaName(patrolInspectionRecordList.get(i).getAreaName());
            patrolInspectionRecordVo.setSiteName(patrolInspectionRecordList.get(i).getSiteName());
            patrolInspectionRecordVo.setName(patrolInspectionRecordList.get(i).getName());
            patrolInspectionRecordVo.setPhone(patrolInspectionRecordList.get(i).getPhone());
            patrolInspectionRecordVo.setPlanType(patrolInspectionRecordList.get(i).getPlanType());
            patrolInspectionRecordVo.setSiteStatus(patrolInspectionRecordList.get(i).getSiteStatus());
            patrolInspectionRecordVo.setLongitude(patrolInspectionRecordList.get(i).getLongitude());
            patrolInspectionRecordVo.setLatitude(patrolInspectionRecordList.get(i).getLatitude());
            patrolInspectionRecordVo.setStartDate(patrolInspectionRecordList.get(i).getStartDate());
            patrolInspectionRecordVo.setEndDate(patrolInspectionRecordList.get(i).getEndDate());
            patrolInspectionRecordVo.setCreateTime(patrolInspectionRecordList.get(i).getCreateTime());
            patrolInspectionRecordVo.setPlanId(patrolInspectionRecordList.get(i).getPlanId());
            patrolInspectionRecordVo.setPlanSonId(patrolInspectionRecordList.get(i).getPlanSonId());
            patrolInspectionRecordVo.setSiteId(patrolInspectionRecordList.get(i).getSiteId());
            patrolInspectionRecordVo.setTenantId(patrolInspectionRecordList.get(i).getTenantId());
            patrolInspectionRecordVo.setCompanyId(patrolInspectionRecordList.get(i).getCompanyId());
            patrolInspectionRecordVo.setCreator(patrolInspectionRecordList.get(i).getCreator());
            patrolInspectionRecordVo.setRemarks(patrolInspectionRecordList.get(i).getRemarks());
            patrolInspectionRecordVo.setRecordPictureList(patrolInspectionRecordPictureList);
            patrolInspectionRecordVo.setContentVoList(patrolInspectionContentVoList);
            list.add(patrolInspectionRecordVo);
        }
        return list;
    }

    @Override
    public RecordStatisticsVo recordStatistics(String startDate, String endDate) {
        List<Integer> planSonidListOne = this.getPlanSon(startDate, endDate);
        Integer taskCount = 0;
        Integer taskCountLeak = 0;
        Integer taskCountComplete = 0;
        Integer siteCount = 0;
        Integer siteCountLeak = 0;
        Integer planCount = 0;
        if (planSonidListOne.size() > 0) {
            planCount = planSonidListOne.size();
            taskCount = this.getPlanSiteSonCount(planSonidListOne, 0);
            taskCountLeak = this.getPlanSiteSonCount(planSonidListOne, 1);
            taskCountComplete = this.getPlanSiteSonCount(planSonidListOne, 2);
        }
        List<Integer> planSonidListTwo = this.getPlanSon(null, null);
        if (planSonidListTwo.size() > 0) {
            siteCount = this.getPlanSiteSonCount(planSonidListTwo, 2);
            siteCountLeak = this.getPlanSiteSonCount(planSonidListTwo, 1);
        }
        RecordStatisticsVo recordStatisticsVo = new RecordStatisticsVo();
        recordStatisticsVo.setTaskCount(taskCount);
        recordStatisticsVo.setTaskCountLeak(taskCountLeak);
        recordStatisticsVo.setTaskCountComplete(taskCountComplete);
        recordStatisticsVo.setSiteCount(siteCount);
        recordStatisticsVo.setSiteCountLeak(siteCountLeak);
        recordStatisticsVo.setPlanCount(planCount);
        return recordStatisticsVo;
    }

    /**
     * 子计划点位表总数统计
     *
     * @param planSonidList    子计划ID
     * @param inspectionStatus 巡检状态（1 未巡检，2 已巡检）
     * @return
     */
    @Override
    public Integer getPlanSiteSonCount(List<Integer> planSonidList, Integer inspectionStatus) {
        LambdaQueryWrapper<PatrolInspectionPlanSiteSon> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(PatrolInspectionPlanSiteSon::getPlanId, planSonidList);
        if (inspectionStatus.equals(1)||inspectionStatus.equals(2)){
            queryWrapper.eq(PatrolInspectionPlanSiteSon::getInspectionStatus, inspectionStatus);
        }
        Integer taskCount = planSiteSonService.count(queryWrapper);
        return taskCount;
    }

    /**
     * 子计划数据查询
     *
     * @param startDate 开始时间 yyyy-MM-dd
     * @param endDate   结束时间 yyyy-MM-dd
     * @return
     */
    @Override
    public List<Integer> getPlanSon(String startDate, String endDate) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionPlan> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.select(PatrolInspectionPlan::getId)
                .eq(PatrolInspectionPlan::getEnable, 1)
                .eq(PatrolInspectionPlan::getTenantId, SecurityUtils.getTenantId());
        if ("00".equals(userType)) {
            queryWrapper1.eq(PatrolInspectionPlan::getCreator, SecurityUtils.getUsername());
        }
        List<PatrolInspectionPlan> list1 = patrolInspectionPlanMapper.selectList(queryWrapper1);
        List<Integer> planSonidListOne = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list1)) {
            List<Integer> planIdList = new ArrayList<>();
            for (int i = 0; i < list1.size(); i++) {
                planIdList.add(list1.get(i).getId());
            }
            LambdaQueryWrapper<PatrolInspectionPlanSon> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.select(PatrolInspectionPlanSon::getId)
                    .eq(PatrolInspectionPlanSon::getPlanType, 1)
                    .in(PatrolInspectionPlanSon::getPlanId, planIdList)
                    .eq(PatrolInspectionPlanSon::getTenantId, SecurityUtils.getTenantId());
            if ("00".equals(userType)) {
                queryWrapper.eq(PatrolInspectionPlanSon::getCreator, SecurityUtils.getUsername());
            }
            if (!"".equals(startDate) && startDate != null && !"".equals(endDate) && endDate != null) {
                queryWrapper.between(PatrolInspectionPlanSon::getInspectionDate, startDate, endDate);
            }

            List<PatrolInspectionPlanSon> planCountListOne = patrolInspectionPlanSonService.list(queryWrapper);
            for (int i = 0; i < planCountListOne.size(); i++) {
                planSonidListOne.add(planCountListOne.get(i).getId());
            }
            LambdaQueryWrapper<PatrolInspectionPlanSon> queryWrapperOne = Wrappers.lambdaQuery();
            queryWrapperOne.select(PatrolInspectionPlanSon::getId)
                    .eq(PatrolInspectionPlanSon::getPlanType, 2)
                    .in(PatrolInspectionPlanSon::getPlanId, planIdList)
                    .eq(PatrolInspectionPlanSon::getTenantId, SecurityUtils.getTenantId());
            if ("00".equals(userType)) {
                queryWrapperOne.eq(PatrolInspectionPlanSon::getCreator, SecurityUtils.getUsername());
            }
            if (!"".equals(startDate) && startDate != null && !"".equals(endDate) && endDate != null) {
                queryWrapperOne.and(wq -> wq
                        .between(PatrolInspectionPlanSon::getStartDate, startDate, endDate)
                        .or()
                        .between(PatrolInspectionPlanSon::getEndDate, startDate, endDate)
                ).groupBy(PatrolInspectionPlanSon::getId);
            }
            List<PatrolInspectionPlanSon> planCountListTwo = patrolInspectionPlanSonService.list(queryWrapperOne);
            for (int i = 0; i < planCountListTwo.size(); i++) {
                planSonidListOne.add(planCountListTwo.get(i).getId());
            }
        }
        return planSonidListOne;
    }


    @Override
    public List<PatrolInspectionRecordExportVo> recordLsitExport(String areaName, String siteName, String name,
                                                                 Integer planType, String startDateTime,
                                                                 String endDateTime, String idList) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionRecord::getTenantId, SecurityUtils.getTenantId())
                .like(StringUtils.isNotBlank(areaName), PatrolInspectionRecord::getAreaName, areaName)
                .like(StringUtils.isNotBlank(siteName), PatrolInspectionRecord::getSiteName, siteName)
                .like(StringUtils.isNotBlank(name), PatrolInspectionRecord::getName, name)
                .eq(planType != null && planType != 0, PatrolInspectionRecord::getPlanType, planType)
                .between(StringUtils.isNotBlank(startDateTime) && StringUtils.isNotBlank(endDateTime), PatrolInspectionRecord::getCreateTime, startDateTime, endDateTime)
                .eq("00".equals(userType), PatrolInspectionRecord::getCreator, SecurityUtils.getUsername());
        if (StringUtils.isNotBlank(idList)) {
            List<Integer> listId = new ArrayList<>();
            String[] idArray = idList.split(",");
            for (int i = 0; i < idArray.length; i++) {
                listId.add(Integer.parseInt(idArray[i]));
            }
            queryWrapper.in(PatrolInspectionRecord::getId, listId);
        }
        queryWrapper.orderByDesc(PatrolInspectionRecord::getId);
        List<PatrolInspectionRecord> patrolInspectionRecordList = this.list(queryWrapper);
        List<PatrolInspectionRecordExportVo> list = new ArrayList<>();
        for (int i = 0; i < patrolInspectionRecordList.size(); i++) {
            PatrolInspectionRecordExportVo patrolInspectionRecordExportVo = new PatrolInspectionRecordExportVo();
            patrolInspectionRecordExportVo.setXh(i + 1);
            patrolInspectionRecordExportVo.setId(patrolInspectionRecordList.get(i).getId());
            patrolInspectionRecordExportVo.setSiteNubmber(patrolInspectionRecordList.get(i).getSiteNubmber());
            patrolInspectionRecordExportVo.setSiteType(patrolInspectionRecordList.get(i).getSiteType());
            patrolInspectionRecordExportVo.setAreaName(patrolInspectionRecordList.get(i).getAreaName());
            patrolInspectionRecordExportVo.setSiteName(patrolInspectionRecordList.get(i).getSiteName());
            patrolInspectionRecordExportVo.setName(patrolInspectionRecordList.get(i).getName());
            patrolInspectionRecordExportVo.setPhone(patrolInspectionRecordList.get(i).getPhone());
            patrolInspectionRecordExportVo.setPlanType(patrolInspectionRecordList.get(i).getPlanType());
            patrolInspectionRecordExportVo.setLongitude(patrolInspectionRecordList.get(i).getLongitude());
            patrolInspectionRecordExportVo.setLatitude(patrolInspectionRecordList.get(i).getLatitude());
            patrolInspectionRecordExportVo.setStartDate(patrolInspectionRecordList.get(i).getStartDate().format(df));
            patrolInspectionRecordExportVo.setEndDate(patrolInspectionRecordList.get(i).getEndDate().format(df));
            patrolInspectionRecordExportVo.setCreateTime(patrolInspectionRecordList.get(i).getCreateTime().format(df));
            list.add(patrolInspectionRecordExportVo);
        }
        return list;
    }

    /**
     * 导出巡检记录（优化版：使用批量查询避免N+1问题）
     * @param areaName
     * @param siteName
     * @param name
     * @param planType
     * @param startDateTime
     * @param endDateTime
     * @param idList
     * @return
     */
    @Override
    public List<PatrolInspectionRecordExportVo> exportImage(String areaName, String siteName, String name,
                                                            Integer planType, String startDateTime,
                                                            String endDateTime, String idList) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionRecord::getTenantId, SecurityUtils.getTenantId())
                .like(StringUtils.isNotBlank(areaName), PatrolInspectionRecord::getAreaName, areaName)
                .like(StringUtils.isNotBlank(siteName), PatrolInspectionRecord::getSiteName, siteName)
                .like(StringUtils.isNotBlank(name), PatrolInspectionRecord::getName, name)
                .eq(planType != null && planType != 0, PatrolInspectionRecord::getPlanType, planType)
                .between(StringUtils.isNotBlank(startDateTime) && StringUtils.isNotBlank(endDateTime), PatrolInspectionRecord::getCreateTime, startDateTime, endDateTime)
                .eq("00".equals(userType), PatrolInspectionRecord::getCreator, SecurityUtils.getUsername());
        if (StringUtils.isNotBlank(idList)) {
            List<Integer> listId = new ArrayList<>();
            String[] idArray = idList.split(",");
            for (int i = 0; i < idArray.length; i++) {
                listId.add(Integer.parseInt(idArray[i]));
            }
            if (!listId.isEmpty()) {
                queryWrapper.in(PatrolInspectionRecord::getId, listId);
            }
        }
        queryWrapper.orderByDesc(PatrolInspectionRecord::getId);
        List<PatrolInspectionRecord> patrolInspectionRecordList = this.list(queryWrapper);
        
        if (patrolInspectionRecordList.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 提取所有记录ID
        List<Integer> recordIds = new ArrayList<>();
        for (PatrolInspectionRecord record : patrolInspectionRecordList) {
            recordIds.add(record.getId());
        }
        
        // 批量查询所有相关数据，避免N+1查询问题
        // 1. 批量查询所有记录选项
        LambdaQueryWrapper<PatrolInspectionRecordOption> recordOptionWrapper = Wrappers.lambdaQuery();
        recordOptionWrapper.in(PatrolInspectionRecordOption::getRecordId, recordIds)
                .orderByAsc(PatrolInspectionRecordOption::getRecordId)
                .orderByAsc(PatrolInspectionRecordOption::getId);
        List<PatrolInspectionRecordOption> allRecordOptions = patrolInspectionRecordOptionMapper.selectList(recordOptionWrapper);
        
        // 2. 批量查询所有图片
        LambdaQueryWrapper<PatrolInspectionRecordPicture> pictureWrapper = Wrappers.lambdaQuery();
        pictureWrapper.select(PatrolInspectionRecordPicture::getPictureUrl, PatrolInspectionRecordPicture::getRecordId)
                .in(PatrolInspectionRecordPicture::getRecordId, recordIds)
                .orderByAsc(PatrolInspectionRecordPicture::getRecordId);
        List<PatrolInspectionRecordPicture> allPictures = orphansInspectionRecordPictureMapper.selectList(pictureWrapper);
        
        // 构建缓存Map：recordId -> List<PatrolInspectionRecordOption>
        Map<Integer, List<PatrolInspectionRecordOption>> recordOptionMap = new HashMap<>();
        for (PatrolInspectionRecordOption option : allRecordOptions) {
            recordOptionMap.computeIfAbsent(option.getRecordId(), k -> new ArrayList<>()).add(option);
        }
        
        // 构建缓存Map：recordId -> List<PatrolInspectionRecordPicture>
        Map<Integer, List<PatrolInspectionRecordPicture>> pictureMap = new HashMap<>();
        for (PatrolInspectionRecordPicture picture : allPictures) {
            pictureMap.computeIfAbsent(picture.getRecordId(), k -> new ArrayList<>()).add(picture);
        }
        
        // 收集所有需要查询的contentId和contentOptionId
        List<Integer> allContentIds = new ArrayList<>();
        List<Integer> allContentOptionIds = new ArrayList<>();
        for (PatrolInspectionRecordOption option : allRecordOptions) {
            if (option.getContentId() != null) {
                allContentIds.add(option.getContentId());
            }
            if (option.getContentOptionId() != null && !" ".equals(option.getContentOptionId())) {
                allContentOptionIds.add(option.getContentOptionId());
            }
        }
        
        // 3. 批量查询所有内容
        Map<Integer, PatrolInspectionContent> contentMap = new HashMap<>();
        if (!allContentIds.isEmpty()) {
            LambdaQueryWrapper<PatrolInspectionContent> contentWrapper = Wrappers.lambdaQuery();
            contentWrapper.in(PatrolInspectionContent::getId, allContentIds)
                    .orderByAsc(PatrolInspectionContent::getId);
            List<PatrolInspectionContent> allContents = patrolInspectionContentMapper.selectList(contentWrapper);
            for (PatrolInspectionContent content : allContents) {
                contentMap.put(content.getId(), content);
            }
        }
        
        // 4. 批量查询所有内容选项
        Map<Integer, PatrolInspectionContentOption> contentOptionMap = new HashMap<>();
        if (!allContentOptionIds.isEmpty()) {
            LambdaQueryWrapper<PatrolInspectionContentOption> contentOptionWrapper = Wrappers.lambdaQuery();
            contentOptionWrapper.in(PatrolInspectionContentOption::getId, allContentOptionIds)
                    .orderByAsc(PatrolInspectionContentOption::getId);
            List<PatrolInspectionContentOption> allContentOptions = patrolInspectionContentOptionMapper.selectList(contentOptionWrapper);
            for (PatrolInspectionContentOption option : allContentOptions) {
                contentOptionMap.put(option.getId(), option);
            }
        }
        
        // 构建结果列表
        List<PatrolInspectionRecordExportVo> list = new ArrayList<>();
        for (int i = 0; i < patrolInspectionRecordList.size(); i++) {
            PatrolInspectionRecord record = patrolInspectionRecordList.get(i);
            Integer recordId = record.getId();
            
            PatrolInspectionRecordExportVo patrolInspectionRecordExportVo = new PatrolInspectionRecordExportVo();
            patrolInspectionRecordExportVo.setXh(i + 1);
            patrolInspectionRecordExportVo.setId(record.getId());
            patrolInspectionRecordExportVo.setSiteNubmber(record.getSiteNubmber());
            patrolInspectionRecordExportVo.setSiteType(record.getSiteType());
            patrolInspectionRecordExportVo.setAreaName(record.getAreaName());
            patrolInspectionRecordExportVo.setSiteName(record.getSiteName());
            patrolInspectionRecordExportVo.setName(record.getName());
            patrolInspectionRecordExportVo.setPhone(record.getPhone());
            patrolInspectionRecordExportVo.setPlanType(record.getPlanType());
            patrolInspectionRecordExportVo.setLongitude(record.getLongitude());
            patrolInspectionRecordExportVo.setLatitude(record.getLatitude());
            patrolInspectionRecordExportVo.setStartDate(record.getStartDate().format(df));
            patrolInspectionRecordExportVo.setEndDate(record.getEndDate().format(df));
            patrolInspectionRecordExportVo.setCreateTime(record.getCreateTime().format(df));
            patrolInspectionRecordExportVo.setRemarks(record.getRemarks());

            // 从缓存中获取数据，而不是单独查询
            List<PatrolInspectionRecordOption> recordOptions = recordOptionMap.getOrDefault(recordId, new ArrayList<>());
            
            // 获取内容标题和提交方法
            List<String> contentTitleList = new ArrayList<>();
            List<String> submissionMethodList = new ArrayList<>();
            List<String> optionNameList = new ArrayList<>();
            List<String> remarksList = new ArrayList<>();
            
            for (PatrolInspectionRecordOption option : recordOptions) {
                // 获取备注
                if (option.getRemarks() != null) {
                    remarksList.add(option.getRemarks());
                } else {
                    remarksList.add("");
                }
                
                // 获取内容标题和提交方法
                if (option.getContentId() != null) {
                    PatrolInspectionContent content = contentMap.get(option.getContentId());
                    if (content != null) {
                        contentTitleList.add(content.getContentTitle());
                        switch (content.getSubmissionMethod()) {
                            case 1:
                                submissionMethodList.add("多选");
                                break;
                            case 2:
                                submissionMethodList.add("单选");
                                break;
                            default:
                                submissionMethodList.add("输入框");
                        }
                    }
                }
                
                // 获取选项名称
                if (option.getContentOptionId() == null || " ".equals(option.getContentOptionId())) {
                    optionNameList.add(option.getContent());
                } else {
                    PatrolInspectionContentOption contentOption = contentOptionMap.get(option.getContentOptionId());
                    if (contentOption != null) {
                        optionNameList.add(contentOption.getOptionName());
                    }
                }
            }
            
            patrolInspectionRecordExportVo.setContentTitle(contentTitleList);
            patrolInspectionRecordExportVo.setSubmissionMethod(submissionMethodList);
            patrolInspectionRecordExportVo.setOptionName(optionNameList);
            patrolInspectionRecordExportVo.setContentRemarks(remarksList);
            
            // 从缓存中获取图片
            List<PatrolInspectionRecordPicture> pictures = pictureMap.getOrDefault(recordId, new ArrayList<>());
            if (!pictures.isEmpty()) {
                for (int j = 0; j < pictures.size() && j < 5; j++) {
                    String pictureUrl = pictures.get(j).getPictureUrl();
                    switch (j) {
                        case 0:
                            patrolInspectionRecordExportVo.setImagePath1(pictureUrl);
                            break;
                        case 1:
                            patrolInspectionRecordExportVo.setImagePath2(pictureUrl);
                            break;
                        case 2:
                            patrolInspectionRecordExportVo.setImagePath3(pictureUrl);
                            break;
                        case 3:
                            patrolInspectionRecordExportVo.setImagePath4(pictureUrl);
                            break;
                        case 4:
                            patrolInspectionRecordExportVo.setImagePath5(pictureUrl);
                            break;
                        default:
                            break;
                    }
                }
            }
            list.add(patrolInspectionRecordExportVo);
        }
        return list;
    }


    /**
     * 获取内容选项备注
     *
     * @param recordId 巡检记录id
     * @return
     */
    public List<String> getRemarks(int recordId) {
        LambdaQueryWrapper<PatrolInspectionRecordOption> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionRecordOption::getRecordId, recordId)
                .orderByAsc(PatrolInspectionRecordOption::getId);
        List<PatrolInspectionRecordOption> recordOptions = patrolInspectionRecordOptionMapper.selectList(queryWrapper);
        List<String> remarksList = new ArrayList<>();
        for (PatrolInspectionRecordOption recordOption : recordOptions) {
            if (recordOption.getRemarks() != null) {
                remarksList.add(recordOption.getRemarks());
            } else {
                remarksList.add(""); // 如果Remarks为空，则添加空字符串
            }
        }
        return remarksList;
    }

    /**
     * 获取检查项ID
     *
     * @param recordId 巡检记录id
     * @return
     */
    public List<Integer> getContentId(int recordId) {
        LambdaQueryWrapper<PatrolInspectionRecordOption> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(PatrolInspectionRecordOption::getContentId)
                .eq(PatrolInspectionRecordOption::getRecordId, recordId)
                .orderByAsc(PatrolInspectionRecordOption::getId);
        List<PatrolInspectionRecordOption> recordOptions = patrolInspectionRecordOptionMapper.selectList(queryWrapper);
        List<Integer> ContentIdList = new ArrayList<>();
        for (PatrolInspectionRecordOption recordOption : recordOptions) {
            ContentIdList.add(recordOption.getContentId());
        }
        return ContentIdList;
    }

    /**
     * 获取内容标题
     *
     * @param recordId 巡检记录id
     * @return
     */
    public List<String> getContentTitle(int recordId) {
        List<Integer> list = getContentId(recordId);
        LambdaQueryWrapper<PatrolInspectionContent> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(PatrolInspectionContent::getContentTitle)
                .in(PatrolInspectionContent::getId, list)
                .orderByAsc(PatrolInspectionContent::getId);
        List<PatrolInspectionContent> contentList = patrolInspectionContentMapper.selectList(queryWrapper);
        List<String> contentTitle = new ArrayList<>();
        for (PatrolInspectionContent content : contentList) {
            contentTitle.add(content.getContentTitle());
        }
        return contentTitle;
    }

    /**
     * 获取提交方法
     *
     * @param recordId 巡检记录id
     * @return
     */
    public List<String> getSubmissionMethod(int recordId) {
        List<Integer> list = getContentId(recordId);
        LambdaQueryWrapper<PatrolInspectionContent> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(PatrolInspectionContent::getSubmissionMethod)
                .in(PatrolInspectionContent::getId, list)
                .orderByAsc(PatrolInspectionContent::getId);
        List<PatrolInspectionContent> contentList = patrolInspectionContentMapper.selectList(queryWrapper);
        List<String> contentTitle = new ArrayList<>();
        for (PatrolInspectionContent content : contentList) {
            switch (content.getSubmissionMethod()) {
                case 1:
                    contentTitle.add("多选");
                    break;
                case 2:
                    contentTitle.add("单选");
                    break;
                default:
                    contentTitle.add("输入框");
            }
        }
        return contentTitle;
    }

    /**
     * 获取内容选项ID
     *
     * @param recordId 巡检记录id
     * @return
     */
    public List<Integer> getContentOptionId(int recordId) {
        LambdaQueryWrapper<PatrolInspectionRecordOption> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionRecordOption::getRecordId, recordId)
                .orderByAsc(PatrolInspectionRecordOption::getId);
        List<PatrolInspectionRecordOption> contentOptionIds = patrolInspectionRecordOptionMapper.selectList(queryWrapper);
        List<Integer> contentOptionIdList = new ArrayList<>();
        for (PatrolInspectionRecordOption recordOption : contentOptionIds) {
            contentOptionIdList.add(recordOption.getContentId());
        }
        return contentOptionIdList;
    }

    /**
     * 获取选项内容
     *
     * @param recordId 巡检记录id
     * @return
     */
    public List<String> getOptionName(int recordId) {
        List<Integer> list = getContentOptionId(recordId);
        System.out.println(list);
        LambdaQueryWrapper<PatrolInspectionRecordOption> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.eq(PatrolInspectionRecordOption::getRecordId, recordId)
                .in(PatrolInspectionRecordOption::getContentId, list)
                .orderByAsc(PatrolInspectionRecordOption::getId);
        List<PatrolInspectionRecordOption> list2 = patrolInspectionRecordOptionMapper.selectList(queryWrapper1);
        List<String> optionNameList = new ArrayList<>();
        for (int i = 0; i < list2.size(); i++) {
            if (list2.get(i).getContentOptionId() == null || " ".equals(list2.get(i).getContentOptionId())) {
                optionNameList.add(list2.get(i).getContent());
            } else {
                LambdaQueryWrapper<PatrolInspectionContentOption> queryWrapper2 = Wrappers.lambdaQuery();
                queryWrapper2.select(PatrolInspectionContentOption::getOptionName)
                        .eq(PatrolInspectionContentOption::getId, list2.get(i).getContentOptionId())
                        .orderByAsc(PatrolInspectionContentOption::getId);
                PatrolInspectionContentOption optionName1 = patrolInspectionContentOptionMapper.selectOne(queryWrapper2);
                optionNameList.add(optionName1.getOptionName());
            }
        }
        return optionNameList;
    }


}
