package org.jeecg.modules.system.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.domain.Person;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.app.form.CreateOrderForm;
import org.jeecg.modules.app.form.InsureOrderInfoForm;
import org.jeecg.modules.app.vo.AppGameScheduleVO;
import org.jeecg.modules.app.vo.AppOrderProInfoVerifyVO;
import org.jeecg.modules.app.vo.ScanCodeQueryOrderVO;
import org.jeecg.modules.quartz.vo.JobClassNoticeVo;
import org.jeecg.modules.quartz.vo.JobReservationSiteVo;
import org.jeecg.modules.system.app.dto.AppOrderDTO;
import org.jeecg.modules.system.app.dto.ExportConditionDTO;
import org.jeecg.modules.system.app.dto.IsinUserInfoDTO;
import org.jeecg.modules.system.app.dto.VerificationRecordDTO;
import org.jeecg.modules.system.app.entity.*;
import org.jeecg.modules.system.app.form.AppOrderPageForm;
import org.jeecg.modules.system.app.form.PriceChangeForm;
import org.jeecg.modules.system.app.form.RefundOrderPageForm;
import org.jeecg.modules.system.app.mapper.*;
import org.jeecg.modules.system.app.service.IAppOrderService;
import org.jeecg.modules.system.app.vo.*;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 订单表
 * @Author: jeecg-boot
 * @Date: 2025-07-03
 * @Version: V1.0
 */
@Service
public class AppOrderServiceImpl extends ServiceImpl<AppOrderMapper, AppOrder> implements IAppOrderService {

    @Resource
    private AppOrderProInfoMapper appOrderProInfoMapper;

    @Resource
    private AppOrderMapper appOrderMapper;

    @Resource
    private AppSiteMapper appSiteMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private AppIsinMapper appIsinMapper;

    @Resource
    private AppCoursesVerificationRecordMapper appCoursesVerificationRecordMapper;

    @Resource
    private AppSitePriceRulesMapper appSitePriceRulesMapper;

    @Resource
    private AppSitePlaceMapper appSitePlaceMapper;

    @Resource
    private AppGameMapper appGameMapper;

    @Resource
    private AppGameScheduleMapper appGameScheduleMapper;

    @Resource
    private AppGamePriceRulesMapper appGamePriceRulesMapper;

    @Resource
    private AppCoursesMapper appCoursesMapper;

    @Resource
    private AppCategoryMapper appCategoryMapper;
    @Resource
    private SysDepartMapper sysDepartMapper;

    @Resource
    private AppOrderRefundsInfoMapper appOrderRefundsInfoMapper;

    @Resource
    private InsureOrderInfoMapper insureOrderInfoMapper;

    @Resource
    private InsurePriceMapper insurePriceMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveWitchProduct(AppOrderDTO appOrderDTO) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        return Boolean.TRUE;
    }

    @Override
    public Boolean editWitchProduct(AppOrderDTO appOrderDTO) {
        return null;
    }

    @Override
    public Boolean deleteWitchProductById(String id) {
        return null;
    }

    @Override
    public AppOrderDTO queryWitchProductById(String id) {
        return null;
    }

    @Override
    public Page<OrderPageVO> queryPage(AppOrderPageForm appOrderPageForm) {
        Page<OrderPageVO> page = new Page<>(appOrderPageForm.getPageNo(), appOrderPageForm.getPageSize());

        Page<OrderPageVO> voPage = baseMapper.queryPage(page, appOrderPageForm);
        voPage.getRecords().forEach(vo -> {
            List<AppOrderProInfo> proInfoList = appOrderProInfoMapper.selectList(Wrappers.<AppOrderProInfo>lambdaQuery()
                    .eq(AppOrderProInfo::getOrderId, vo.getId()));
            vo.setOrderProInfoList(proInfoList);
            if(vo.getOrgCode().length() == 3){
                SysDepart sysDepart = sysDepartMapper.selectOne(Wrappers.<SysDepart>lambdaQuery()
                        .eq(SysDepart::getOrgCode, vo.getOrgCode()));
                vo.setDepartName(sysDepart.getDepartName());
            }
        });
        return voPage;
    }

    @Override
    public AppOrderInfoVO queryInfoById(String orderId) {
        //订单
        AppOrder appOrder = appOrderMapper.selectById(orderId);
        if (ObjectUtil.isEmpty(appOrder)){
            throw new JeecgBootException("当前订单不存在！");
        }
        AppSite site = appSiteMapper.selectOne(Wrappers.lambdaQuery(AppSite.class).eq(AppSite::getOrgCode, appOrder.getOrgCode()));
        //构建返回对象
        AppOrderInfoVO appOrderInfoVO = new AppOrderInfoVO();
        appOrderInfoVO.setId(appOrder.getId());
        //订单编号
        appOrderInfoVO.setOrderCode(appOrder.getOrderCode());
        //订单类型
        appOrderInfoVO.setOrderType(appOrder.getOrderType());
        //下单时间
        appOrderInfoVO.setCreateTime(appOrder.getCreateTime());
        //订单状态
        appOrderInfoVO.setOrderStatus(appOrder.getOrderStatus());
        //使用地信息
        if (appOrder.getType() == 1){
            AppGamePriceRules appGamePriceRules = appGamePriceRulesMapper.selectById(appOrder.getProductIds());
            if (ObjectUtil.isNotEmpty(appGamePriceRules)){
                AppGame appGame = appGameMapper.findByPriceRules(appGamePriceRules.getId());
                if (ObjectUtil.isNotEmpty(appGame)){
                    if (ObjectUtil.isNotEmpty(site) && appGame.getSiteType() == 0){
                        appOrderInfoVO.setSiteName(site.getName());
                        appOrderInfoVO.setAddress(appGame.getAddress());
                    }else {
                        appOrderInfoVO.setAddress(appGame.getSiteAddress());
                    }
                }
            }
        }else {
            String addressSiteId = appOrder.getAddressSiteId();
            AppSite appSite = appSiteMapper.selectById(addressSiteId);
            appOrderInfoVO.setSiteName(appSite.getName());
            appOrderInfoVO.setAddress(appSite.getAddress());
        }
        //付款信息
        if (appOrder.getOrderStatus() > 0) {
            appOrderInfoVO.setPayTime(appOrder.getPayTime());
            appOrderInfoVO.setPrice(appOrder.getPrice());
        }
        //子订单信息
        List<AppOrderProInfo> proInfoList = appOrderProInfoMapper.selectList(Wrappers.<AppOrderProInfo>lambdaQuery().eq(AppOrderProInfo::getOrderId, orderId));
        appOrderInfoVO.setProInfoList(proInfoList);
        //买家信息
        SysUser sysUser = sysUserMapper.selectById(appOrder.getUserId());
        appOrderInfoVO.setNikeName(sysUser.getUsername());
        appOrderInfoVO.setPhoneNumber(sysUser.getPhone());
        //费用信息
        appOrderInfoVO.setTotalPrice(appOrder.getPrice());
        appOrderInfoVO.setPrice(appOrder.getPrice());
        //使用记录
        List<AppIsinVO> appIsinVOList = new ArrayList<>();
        //核销记录
        List<VerificationRecordDTO> verificationRecordDTOList = new ArrayList<>();

        List<AppIsin> appIsinList = appIsinMapper.selectList(Wrappers.<AppIsin>lambdaQuery().eq(AppIsin::getOrderId, orderId).eq(AppIsin::getIsinStatus, CommonConstant.ISIN_STATUS_1));
        if (CollUtil.isNotEmpty(appIsinList)) {
            Map<IsinUserInfoDTO, List<AppIsin>> map =
                    appIsinList.stream()
                            .collect(Collectors.groupingBy(
                                    x -> new IsinUserInfoDTO(x.getFamilyId(), x.getFamilyUserName(), x.getUserPhone(), x.getTicketNo()),
                                    Collectors.mapping(AppIsin -> AppIsin, Collectors.toCollection(ArrayList::new))));
            map.keySet().forEach(p -> {
                AppIsinVO isinVO = new AppIsinVO();
                isinVO.setFamilyId(p.getFamilyId());
                isinVO.setFamilyUserName(p.getFamilyUserName());
                isinVO.setIsinCode(p.getIsinCode());
                isinVO.setIsinList(map.get(p));
                appIsinVOList.add(isinVO);
            });
            appOrderInfoVO.setIsinList(appIsinVOList);
        }
        //只有赛事有赛程和团队信息
        if (appOrder.getType() == 1) {
            AppGame appGame = appGameMapper.findByPriceRules(appOrder.getProductIds());
            List<AppGameScheduleVO> gameScheduleVOList = appGameScheduleMapper.getListVo(appGame.getId());
            appOrderInfoVO.setGameScheduleVOList(gameScheduleVOList);
            appOrderInfoVO.setGameCertification(appOrder.getGameCertification());
        }
        //无固定场团购优惠
        if (appOrder.getOrderType() == 2) {
            appOrderInfoVO.setTDiscounts(appOrder.getTDiscounts());
            appOrderInfoVO.setTotalPrice(appOrderInfoVO.getTotalPrice().add(appOrder.getTDiscounts()));
        }
        //课程才有核销记录和优惠信息
        if (appOrder.getType() == 2) {
            //优惠信息
            if (appOrder.getSDiscounts() != null){
                appOrderInfoVO.setSDiscounts(appOrder.getSDiscounts());
                appOrderInfoVO.setTotalPrice(appOrderInfoVO.getTotalPrice().add(appOrder.getSDiscounts()));
            }
            if (appOrder.getTDiscounts() != null){
                appOrderInfoVO.setTDiscounts(appOrder.getTDiscounts());
                appOrderInfoVO.setTotalPrice(appOrderInfoVO.getTotalPrice().add(appOrder.getTDiscounts()));
            }

            //核销记录
            List<AppCoursesVerificationRecord> verificationRecords =
                    appCoursesVerificationRecordMapper.selectList(Wrappers.<AppCoursesVerificationRecord>lambdaQuery().eq(AppCoursesVerificationRecord::getOrderId, orderId));
            if (CollUtil.isNotEmpty(verificationRecords)) {
                Map<Integer, List<AppCoursesVerificationRecord>> listMap = verificationRecords.stream().collect(Collectors.groupingBy(AppCoursesVerificationRecord::getCoursesType));
                listMap.keySet().forEach(p -> {
                    VerificationRecordDTO verificationRecordDTO = new VerificationRecordDTO();
                    verificationRecordDTO.setCoursesType(p).setVerificationRecordList(listMap.get(p));
                    verificationRecordDTOList.add(verificationRecordDTO);
                });
                appOrderInfoVO.setVerificationRecordDTOList(verificationRecordDTOList);
            }
        }
        return appOrderInfoVO;
    }

    @Override
    public ScanCodeQueryOrderVO scanCodeQueryOrder(String orderId) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        AppOrder appOrder = appOrderMapper.selectById(orderId);
        if (appOrder.getType() != 1){
            if(!appOrder.getOrgCode().equals(loginUser.getOrgCode())) {
                throw new JeecgBootException("当前券码不属于该商户，无权限操作！");
            }
        }
        AppSite site = appSiteMapper.selectOne(Wrappers.<AppSite>lambdaQuery().eq(AppSite::getOrgCode, appOrder.getOrgCode()));

        ScanCodeQueryOrderVO scanCodeQueryOrderVO = new ScanCodeQueryOrderVO();
        if (ObjectUtil.isNotEmpty(site)){
            scanCodeQueryOrderVO.setSiteName(site.getName());
        }
        scanCodeQueryOrderVO.setAmount(appOrder.getAmount());

        List<AppOrderProInfoVerifyVO> orderProInfoVOList = new ArrayList<>();
        List<AppOrderProInfo> proInfoList = appOrderProInfoMapper.selectList(Wrappers.<AppOrderProInfo>lambdaQuery().eq(AppOrderProInfo::getOrderId, orderId));

        for (AppOrderProInfo appOrderProInfo : proInfoList) {

            AppIsin appIsin = appIsinMapper.selectOne(Wrappers.<AppIsin>lambdaQuery().eq(AppIsin::getOrderProInfoId, appOrderProInfo.getId()));

            AppOrderProInfoVerifyVO appOrderProInfoVerifyVO = new AppOrderProInfoVerifyVO();
            if (ObjectUtil.isNotEmpty(appIsin)) {
                appOrderProInfoVerifyVO.setIsinId(appIsin.getId());
                appOrderProInfoVerifyVO.setIsinStatus(appIsin.getIsinStatus());
            }
            appOrderProInfoVerifyVO.setAppOrderProInfo(appOrderProInfo);

            orderProInfoVOList.add(appOrderProInfoVerifyVO);
        }
        scanCodeQueryOrderVO.setAppOrderProInfoVerifyVOS(orderProInfoVOList);

        //0-学校 1-包场 2-无固定场 3-个人赛 4-团队赛 5-课程    学校及包场即为商品不用查
        if (appOrder.getType() == 0){
            if (appOrder.getOrderType() == 2) {
                String productIds = appOrder.getProductIds();
                AppSitePriceRules appSitePriceRules = appSitePriceRulesMapper.selectById(productIds);
                AppSitePlace appSitePlace = appSitePlaceMapper.selectById(appSitePriceRules.getSitePlaceId());
                scanCodeQueryOrderVO.setProductName(appSitePlace.getName());
                scanCodeQueryOrderVO.setProductImage(appSitePlace.getCover());
                scanCodeQueryOrderVO.setPrice(appSitePriceRules.getSellingPrice());
            }
        }
        if (appOrder.getType() == 1){
            AppGamePriceRules appGamePriceRules = appGamePriceRulesMapper.selectById(appOrder.getProductIds());
            AppGame appGame = appGameMapper.findByPriceRules(appGamePriceRules.getId());

            scanCodeQueryOrderVO.setProductName(appGame.getName());
            scanCodeQueryOrderVO.setProductImage(appGame.getCover());
            scanCodeQueryOrderVO.setGameType(appGamePriceRules.getType());
            scanCodeQueryOrderVO.setPrice(appGamePriceRules.getSellingPrice());
            scanCodeQueryOrderVO.setSiteName(appGame.getSiteAddress());
        }

        if (appOrder.getType() == 2) {
            AppCourses appCourses = appCoursesMapper.selectById(appOrder.getProductIds());
            scanCodeQueryOrderVO.setProductName(appCourses.getName());
            scanCodeQueryOrderVO.setProductImage(appCourses.getCover());
            scanCodeQueryOrderVO.setPrice(appCourses.getSellingPrice());
        }
        return scanCodeQueryOrderVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean scanCodeVerification(List<String> isinIds) {

        LoginUser loginUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        boolean sable= true;
        for (String isinId : isinIds) {
            //查询对应券号
            AppIsin appIsin = appIsinMapper.selectById(isinId);
            //修改订单状态
            String orderProInfoId = appIsin.getOrderProInfoId();
            AppOrderProInfo appOrderProInfo = appOrderProInfoMapper.selectById(orderProInfoId);

            if (Objects.equals(appOrderProInfo.getType(), CommonConstant.ORDER_PRO_INFO_TYPE_3) || Objects.equals(appOrderProInfo.getType(), CommonConstant.ORDER_PRO_INFO_TYPE_4)) {
                //判断orgCode长度
                if (loginUser.getOrgCode().length() > 3) {
                    throw new JeecgBootException("当前账号无权限核销赛事券号，请切换平台账号进行核验！");
                }
            }
            //券号状态
            appIsin.setIsinStatus(CommonConstant.ISIN_STATUS_1);
            appIsin.setVerifyUserId(loginUser.getId());
            appIsin.setVerifyUserName(loginUser.getUsername());
            appIsin.setUseTime(DateUtils.getDate());
            appIsinMapper.updateById(appIsin);

            //修改订单状态
            if (!Objects.equals(appOrderProInfo.getType(), CommonConstant.ORDER_PRO_INFO_TYPE_5)){
                appOrderProInfo.setOrderStatus(CommonConstant.ORDER_STATUS_2);
                appOrderProInfoMapper.updateById(appOrderProInfo);
                //修改订单状态
                String orderId = appOrderProInfo.getOrderId();
                AppOrder appOrder = appOrderMapper.selectById(orderId);
                int x = appIsinMapper.selectList(Wrappers.<AppIsin>lambdaQuery().eq(AppIsin::getOrderId, appOrder.getId()).eq(AppIsin::getIsinStatus, 0)).size();
                int y = appOrderProInfoMapper.selectList(Wrappers.<AppOrderProInfo>lambdaQuery().eq(AppOrderProInfo::getOrderId, appOrder.getId()).eq(AppOrderProInfo::getOrderStatus, 0)).size();
                if (ObjectUtil.isNotEmpty(appOrder) && x == 0 && y == 0){
                    if(!Objects.equals(appOrder.getOrderStatus(), CommonConstant.ORDER_STATUS_2)){
                        appOrder.setOrderStatus(CommonConstant.ORDER_STATUS_2);
                        appOrderMapper.updateById(appOrder);
                    }
                }
            }
        }
        return Boolean.TRUE;
    }

    @Override
    public List<JobClassNoticeVo> findByJob(Integer hoursBefore,Date date, int maxRetry) {
        return appOrderMapper.findByJob(hoursBefore,date,maxRetry);
    }

    @Override
    public List<JobReservationSiteVo> findBySite(LocalDate currentDate, LocalTime localTime) {
        List<JobReservationSiteVo> jobReservationSiteVosOne= appOrderMapper.findByReservationSite();
        List<JobReservationSiteVo> jobReservationSiteVosTwe= appOrderMapper.findByReservationSiteTicket(currentDate,localTime);
        // 1. 构建查找Map（O(n)时间复杂度）
        Map<String, JobReservationSiteVo> aMap = jobReservationSiteVosOne.stream()
                .collect(Collectors.toMap(JobReservationSiteVo::getSiteId,  Function.identity()));

        // 2. 遍历并赋值（O(n)时间复杂度）
        jobReservationSiteVosTwe.forEach(b -> {
            JobReservationSiteVo matchedA = aMap.get(b.getSiteId());
            if (matchedA != null) {
                b.setUserOpenId(matchedA.getUserOpenId());
            }
        });
        return jobReservationSiteVosTwe;
    }

    @Override
    public List<ExportConditionVO> exportConditionByName(String name) {
        List<AppGame> appGames = null;
        if(null != name && !name.isEmpty()){
            appGames = appGameMapper.selectList(Wrappers.<AppGame>lambdaQuery().like(AppGame::getName, name).eq(AppGame::getDelFlag, 0));
        }else {
            appGames = appGameMapper.selectList(Wrappers.<AppGame>lambdaQuery().eq(AppGame::getDelFlag, 0));
        }
        List<ExportConditionVO> collect = appGames.stream()
                .map(game -> {
                    ExportConditionVO vo = new ExportConditionVO();
                    vo.setId(game.getId());
                    vo.setName(game.getName());
                    return vo;
                })
                .collect(Collectors.toList());
        collect.add(new ExportConditionVO().setId("ALL").setName("全部"));
        return collect;
    }

    @Override
    public List<ExportConditionVO> exportConditionByProjectName(String projectName, String gameId) {
        List<ExportConditionVO> collect = new ArrayList<>();
        collect.add(new ExportConditionVO().setId("ALL").setName("全部"));
        if(null != projectName && !projectName.isEmpty()){
            AppCategory appCategory = appCategoryMapper.selectOne(Wrappers.<AppCategory>lambdaQuery().like(AppCategory::getName, projectName)
                    .eq(AppCategory::getDelFlag, 0)
                    .eq(AppCategory::getStatus, 0).last("limit 1"));
            List<AppGamePriceRules> appGamePriceRules = appGamePriceRulesMapper.selectList(Wrappers.<AppGamePriceRules>lambdaQuery()
                    .eq(AppGamePriceRules::getGameId, gameId)
                    .eq(AppGamePriceRules::getCategoryId, appCategory.getId()));
            collect = appGamePriceRules.stream()
                    .map(priceRules -> {
                        ExportConditionVO vo = new ExportConditionVO();
                        vo.setId(priceRules.getId());
                        vo.setName((priceRules.getType() == 0 ? "个人-": "团队-") + appCategoryMapper.selectById(priceRules.getCategoryId()).getName());
                        return vo;
                    })
                    .collect(Collectors.toList());
        }else {
            List<AppGamePriceRules> appGamePriceRules = appGamePriceRulesMapper.selectList(Wrappers.<AppGamePriceRules>lambdaQuery()
                    .eq(AppGamePriceRules::getGameId, gameId));
            collect = appGamePriceRules.stream()
                    .map(priceRules -> {
                        ExportConditionVO vo = new ExportConditionVO();
                        vo.setId(priceRules.getId());
                        vo.setName((priceRules.getType() == 0 ? "个人-": "团队-") + appCategoryMapper.selectById(priceRules.getCategoryId()).getName());
                        return vo;
                    })
                    .collect(Collectors.toList());
            collect.add(new ExportConditionVO().setId("ALL").setName("全部"));
        }
        return collect;

    }

    @Override
    public byte[] exportCondition(ExportConditionDTO exportConditionDTO) throws IOException {
        List<ExportConditionOutVO> exportConditionOutVO = appGameMapper.exportCondition(exportConditionDTO);
        List<Map<String, Object>> list = new ArrayList<>();
        int index = 1;
        for (ExportConditionOutVO outVO : exportConditionOutVO){
            String gameCertification = outVO.getGameCertification();
            // 使用 FastJSON 解析 gameCertification 字段
            JSONObject certificationJson = JSONObject.parseObject(gameCertification);

            Map<String, Object> map = new HashMap<>();
            map.put("序号", index);
            map.put("赛事名称", outVO.getName());
            map.put("个人/团队赛", outVO.getType());
            map.put("报名项目", outVO.getProjectName());

            // 提取 teamName 放到 队名
            String teamName = "未填写";
            if(null != certificationJson && certificationJson.containsKey("teamName")) teamName = certificationJson.getString("teamName");
            map.put("队名", teamName != null ? teamName : "");

            // 提取 teamEmblemImg 放到 队徽
            String teamEmblemImg = "未填写";
            if(null != certificationJson && certificationJson.containsKey("teamEmblemImg")) teamEmblemImg = certificationJson.getString("teamEmblemImg");
            map.put("队徽", teamEmblemImg != null ? teamEmblemImg : "");

            // 提取 certificationDTOS 放到 社保证明
            if(null != certificationJson && certificationJson.containsKey("certificationDTOS")){
                JSONArray certificationDTOS = certificationJson.getJSONArray("certificationDTOS");
                if (certificationDTOS != null && !certificationDTOS.isEmpty()) {
                    StringBuilder certificationBuilder = new StringBuilder();
                    for (int i = 0; i < certificationDTOS.size(); i++) {
                        JSONObject cert = certificationDTOS.getJSONObject(i);
                        String name = "未填写";
                        String certificationImg = "未填写";
                        if(null != cert && cert.containsKey("name")) name = cert.getString("name");
                        if(null != cert && cert.containsKey("certificationImg")) certificationImg = cert.getString("certificationImg");
                        certificationBuilder.append(name).append(": ").append(certificationImg).append(";");
                    }
                    map.put("社保证明", certificationBuilder.toString());
                } else {
                    map.put("社保证明", "");
                }
            }

            map.put("报名人员", outVO.getUserName());
            map.put("联系电话", outVO.getUserPhone());
            list.add(map);
            index++;
        }

        // 生成 Excel 文件并返回字节数组
        return generateExcel(list);
    }

    @Override
    public IPage<RefundOrderPageVO> refundOrderPageList(RefundOrderPageForm refundOrderPageForm) {
        IPage<RefundOrderPageVO> page = new Page<>(refundOrderPageForm.getPageNo(), refundOrderPageForm.getPageSize());
        IPage<RefundOrderPageVO> pages = baseMapper.refundOrderPageList(page, refundOrderPageForm);
        List<RefundOrderPageVO> records = pages.getRecords();
        for (RefundOrderPageVO record : records) {
            List<AppOrderProInfo> orderProInfoList = appOrderProInfoMapper.selectList(Wrappers.<AppOrderProInfo>lambdaQuery().eq(AppOrderProInfo::getOrderId, record.getOrderId()).gt(AppOrderProInfo::getAfterSaleStatus, 0));
            List<RefundOrderProInfo> refundOrderProInfoList = new ArrayList<>();
            for (AppOrderProInfo appOrderProInfo : orderProInfoList) {
                RefundOrderProInfo refundOrderProInfo = new RefundOrderProInfo();
                BeanUtil.copyProperties(appOrderProInfo, refundOrderProInfo);

                //根据子订单查询退款记录，查询退款编号
                AppOrderRefundsInfo appOrderRefundsInfo = appOrderRefundsInfoMapper.selectOne(Wrappers.<AppOrderRefundsInfo>lambdaQuery().eq(AppOrderRefundsInfo::getOrderProInfoId,
                        appOrderProInfo.getId()));
                refundOrderProInfo.setAppOrderRefundsInfo(appOrderRefundsInfo);
                refundOrderProInfoList.add(refundOrderProInfo);
            }
            record.setRefundOrderProInfoList(refundOrderProInfoList);
        }
        return pages;
    }

    @Override
    public String priceChange(PriceChangeForm priceChangeForm) {





        //修改原订单为已取消

        return "订单改价成功！";
    }

    // 修改 generateExcel 方法返回字节数组
    private byte[] generateExcel(List<Map<String, Object>> dataList) throws IOException {
        Workbook workbook = null;

        try {
            // 创建工作簿和工作表
            workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("报名信息");

            // 设置列宽
            sheet.setColumnWidth(0, 3000);  // 序号
            sheet.setColumnWidth(1, 8000);  // 赛事名称
            sheet.setColumnWidth(2, 6000);  // 个人/团队赛
            sheet.setColumnWidth(3, 6000);  // 报名项目
            sheet.setColumnWidth(4, 6000);  // 队名
            sheet.setColumnWidth(5, 6000);  // 队徽
            sheet.setColumnWidth(6, 10000); // 社保证明
            sheet.setColumnWidth(7, 4000);  // 报名人员
            sheet.setColumnWidth(8, 4000);  // 联系电话

            // 创建标题样式
            CellStyle headerStyle = createHeaderStyle(workbook);

            // 创建内容样式
            CellStyle contentStyle = createContentStyle(workbook);

            // 写入表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"序号", "赛事名称", "个人/团队赛", "报名项目", "队名", "队徽", "社保证明", "报名人员", "联系电话"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 写入数据
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> rowMap = dataList.get(i);
                Row dataRow = sheet.createRow(i + 1);
                // 设置行高，为图片留出空间
                dataRow.setHeightInPoints(80);

                // 序号
                Cell cell0 = dataRow.createCell(0);
                cell0.setCellValue((Integer) rowMap.get("序号"));
                cell0.setCellStyle(contentStyle);

                // 赛事名称
                Cell cell1 = dataRow.createCell(1);
                cell1.setCellValue((String) rowMap.get("赛事名称"));
                cell1.setCellStyle(contentStyle);

                // 个人/团队赛
                Cell cell2 = dataRow.createCell(2);
                cell2.setCellValue((int) rowMap.get("个人/团队赛") == 3 ? "个人" : "团队");
                cell2.setCellStyle(contentStyle);

                // 报名项目
                Cell cell3 = dataRow.createCell(3);
                cell3.setCellValue((String) rowMap.get("报名项目"));
                cell3.setCellStyle(contentStyle);

                // 队名
                Cell cell4 = dataRow.createCell(4);
                cell4.setCellValue((String) rowMap.get("队名"));
                cell4.setCellStyle(contentStyle);

                // 队徽：插入图片（嵌入单元格）
                String teamEmblemImg = (String) rowMap.get("队徽");
                Cell cell5 = dataRow.createCell(5);
                cell5.setCellStyle(contentStyle);
                if (teamEmblemImg != null && !teamEmblemImg.isEmpty()) {
                    insertImageToCell(workbook, sheet, teamEmblemImg, 5, i + 1);
                }

                // 社保证明：多个图片，放在同一单元格内，按行排列
                String certificationStr = (String) rowMap.get("社保证明");
                Cell cell6 = dataRow.createCell(6);
                cell6.setCellStyle(contentStyle);

                if (certificationStr != null && !certificationStr.isEmpty()) {
                    List<String> allImageUrls = extractImageUrls(certificationStr);
                    if (!allImageUrls.isEmpty()) {
                        insertMultipleImagesToCell(workbook, sheet, allImageUrls, 6, i + 1);
                    }
                }

                // 报名人员
                Cell cell7 = dataRow.createCell(7);
                cell7.setCellValue((String) rowMap.get("报名人员"));
                cell7.setCellStyle(contentStyle);

                // 联系电话
                Cell cell8 = dataRow.createCell(8);
                cell8.setCellValue((String) rowMap.get("联系电话"));
                cell8.setCellStyle(contentStyle);
            }

            // 将工作簿写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();

        } finally {
            // 关闭工作簿
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    System.err.println("关闭工作簿时出错: " + e.getMessage());
                }
            }
        }
    }


    // 创建表头样式
    private CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle headerStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        return headerStyle;
    }

    // 创建内容样式
    private CellStyle createContentStyle(Workbook workbook) {
        CellStyle contentStyle = workbook.createCellStyle();
        contentStyle.setAlignment(HorizontalAlignment.CENTER);
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentStyle.setBorderTop(BorderStyle.THIN);
        contentStyle.setBorderBottom(BorderStyle.THIN);
        contentStyle.setBorderLeft(BorderStyle.THIN);
        contentStyle.setBorderRight(BorderStyle.THIN);
        return contentStyle;
    }

    // 提取图片URL
    private List<String> extractImageUrls(String certificationStr) {
        List<String> allImageUrls = new ArrayList<>();
        String[] certLines = certificationStr.split(";");

        for (String line : certLines) {
            line = line.trim();
            if (line.contains(":")) {
                String[] parts = line.split(": ", 2);
                if (parts.length > 1) {
                    String imgUrls = parts[1];
                    String[] urls = imgUrls.split(",");
                    for (String url : urls) {
                        String trimmedUrl = url.trim();
                        if (!trimmedUrl.isEmpty()) {
                            allImageUrls.add(trimmedUrl);
                        }
                    }
                }
            }
        }
        return allImageUrls;
    }

    // 在单元格中插入单张图片
    private void insertImageToCell(Workbook workbook, Sheet sheet, String imageUrl, int column, int row) {
        byte[] imageBytes = downloadImage(imageUrl);
        if (imageBytes != null) {
            int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
            Drawing<?> drawing = sheet.createDrawingPatriarch();
            CreationHelper helper = workbook.getCreationHelper();
            ClientAnchor anchor = helper.createClientAnchor();

            // 设置图片锚点
            anchor.setCol1(column);
            anchor.setCol2(column + 1);
            anchor.setRow1(row);
            anchor.setRow2(row + 1);
            anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

            drawing.createPicture(anchor, pictureIdx);
        }
    }

    // 在单元格中插入多张图片
    private void insertMultipleImagesToCell(Workbook workbook, Sheet sheet, List<String> imageUrls, int column, int row) {
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        CreationHelper helper = workbook.getCreationHelper();

        // 图片排列参数
        int maxPerRow = 4; // 每行最多3张图片
        int imageWidth = 800000;  // 图片宽度
        int imageHeight = 500000; // 图片高度
        int horizontalSpacing = 15000; // 水平间距
        int verticalSpacing = 15000;   // 垂直间距

        for (int i = 0; i < imageUrls.size(); i++) {
            String imageUrl = imageUrls.get(i);
            byte[] imageBytes = downloadImage(imageUrl);

            if (imageBytes != null) {
                int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);

                // 计算当前图片在网格中的位置
                int rowIndex = i / maxPerRow;
                int colIndex = i % maxPerRow;

                ClientAnchor anchor = helper.createClientAnchor();

                // 设置图片在单元格内的相对位置
                anchor.setCol1(column);
                anchor.setCol2(column);
                anchor.setRow1(row);
                anchor.setRow2(row);

                // 计算图片的精确位置
                int dx1 = colIndex * (imageWidth + horizontalSpacing) + 20000;
                int dy1 = rowIndex * (imageHeight + verticalSpacing) + 20000;
                int dx2 = dx1 + imageWidth;
                int dy2 = dy1 + imageHeight;

                anchor.setDx1(dx1);
                anchor.setDy1(dy1);
                anchor.setDx2(dx2);
                anchor.setDy2(dy2);

                drawing.createPicture(anchor, pictureIdx);
            }
        }
    }

    // 下载图片字节流
    private byte[] downloadImage(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) > 0) {
                bos.write(buffer, 0, len);
            }
            is.close();
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
