package com.liquidnet.client.admin.web.controller.zhengzai.kylin;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.common.annotation.Log;
import com.liquidnet.client.admin.common.core.controller.BaseController;
import com.liquidnet.client.admin.common.core.domain.AjaxResult;
import com.liquidnet.client.admin.common.core.page.TableDataInfo;
import com.liquidnet.client.admin.common.enums.BusinessType;
import com.liquidnet.client.admin.common.utils.poi.ExcelUtil;
import com.liquidnet.client.admin.zhengzai.kylin.dto.KylinPerformanceSubscribeTicketStatisticalExportDao;
import com.liquidnet.client.admin.zhengzai.kylin.dto.PerformanceOrderStatisCountResp;
import com.liquidnet.client.admin.zhengzai.kylin.dto.PerformanceTicketSalesDto;
import com.liquidnet.client.admin.zhengzai.kylin.dto.PerformanceTicketSumDto;
import com.liquidnet.client.admin.zhengzai.kylin.service.IOpenDataService;
import com.liquidnet.client.admin.zhengzai.kylin.utils.DataSumUtils;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.dao.PerformanceAdminListDao;
import com.liquidnet.service.kylin.dao.PerformanceMemberAuditDao;
import com.liquidnet.service.kylin.dao.PerformanceOrderStatisticalDao;
import com.liquidnet.service.kylin.dao.report.KylinPerformanceSubscribeTicketStatisticalDao;
import com.liquidnet.service.kylin.dto.param.PerformanceAdminListParam;
import com.liquidnet.service.kylin.dto.param.PerformanceMemberAuditParam;
import com.liquidnet.service.kylin.dto.param.SysDamaiParam;
import com.liquidnet.service.kylin.dto.vo.admin.*;
import com.liquidnet.service.kylin.dto.vo.partner.KylinPerformanceMisVo;
import com.liquidnet.service.kylin.dto.vo.partner.KylinPerformancesVo;
import com.liquidnet.service.kylin.dto.vo.partner.TicketTimesTicketCreatePartnerVo;
import com.liquidnet.service.kylin.entity.KylinOrderImport;
import com.liquidnet.service.kylin.service.admin.IKylinPerformancesAdminService;
import com.liquidnet.service.kylin.service.other.DamaiService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFRow;
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.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


/**
 * 演出Controller
 *
 * @author anjiabin
 * @date 2021-05-24
 */
@Controller
@RequestMapping("/kylin/performances")
public class KylinPerformancesController extends BaseController {
    private String prefix = "zhengzai/kylin/performances";

    @Autowired
    private IKylinPerformancesAdminService kylinPerformancesService;

    @Autowired
    private DamaiService damaiService;
    @Autowired
    private IOpenDataService openDataService;

    //@RequiresPermissions("kylin:performances:view")
    @GetMapping()
    public String performances() {
        return prefix + "/performances";
    }

    @GetMapping(value = "/test")
    public void test() {
        kylinPerformancesService.test();
    }

    @Log(title = "同步票务平台-演出", businessType = BusinessType.OTHER)
    @PostMapping(value = "/syncTicketSysPerformance")
    @ResponseBody
    public AjaxResult syncTicketSysPerformance(@RequestParam("performancesId") String performancesId) {
        boolean result = kylinPerformancesService.syncTicketSysPerformance(performancesId);
        return toAjax(result);
    }

    @Log(title = "同步票务平台-订单", businessType = BusinessType.OTHER)
    @PostMapping(value = "/syncTicketSysOrder")
    @ResponseBody
    public AjaxResult syncTicketSysOrder(@RequestParam("performancesId") String performancesId) {
        boolean result = kylinPerformancesService.syncTicketSysOrder(performancesId);
        return toAjax(result);
    }

    /**
     * 查询演出列表
     */
    //@RequiresPermissions("kylin:performances:view")
    @Log(title = "演出列表", businessType = BusinessType.LIST)
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PerformanceAdminListParam performanceAdminListParam) {
        PageInfo<PerformanceAdminListDao> result = kylinPerformancesService.getList(performanceAdminListParam);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(result.getList());
        rspData.setTotal(result.getTotal());
        return rspData;
    }

    //@RequiresPermissions("kylin:performances:view")
    @Log(title = "演出列表", businessType = BusinessType.DETAIL)
    @GetMapping(value = "/details/{performancesId}")
    public String performanceDetails(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        KylinPerformanceMisVo result = null;
        result = kylinPerformancesService.performanceDetails(performancesId);
        mmap.put("kylinPerformanceMisVo", result);
        return prefix + "/details";
    }

    @Log(title = "演出审核", businessType = BusinessType.AUDIT)
    @PostMapping(value = "/audit")
    //@RequiresPermissions("kylin:performances:view")
    @ResponseBody
    public AjaxResult performanceAudit(@RequestParam("performancesId") String performancesId, @RequestParam("status") int status, @RequestParam(value = "rejectTxt", required = false) String rejectTxt) {
        boolean result = kylinPerformancesService.performanceAudit(performancesId, status, rejectTxt);
        return toAjax(result);
    }

    //@RequiresPermissions("kylin:performances:view")
    @PostMapping(value = "/isShow")
    @ResponseBody
    @Log(title = "演出管理：是否显示", businessType = BusinessType.PERFORMANCE_SAVE)
    public AjaxResult setIsShow(String performancesId, Integer isShow) {
        return toAjax(kylinPerformancesService.setIsShow(performancesId, isShow));
    }

    //    @Log(title = "演出列表", businessType = BusinessType.DETAIL)
    //@RequiresPermissions("kylin:performances:view")
    @GetMapping(value = "/memberInfo/{performancesId}")
    public String memberInfo(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        PerformanceMemberAuditDao result = kylinPerformancesService.performanceMemberInfo(performancesId);
        mmap.put("performanceMemberAuditDao", result);
        return prefix + "/memberInfo";
    }

    @Log(title = "演出管理：提交会员信息", businessType = BusinessType.PERFORMANCE_SAVE)
    //@RequiresPermissions("kylin:performances:view")
    @PostMapping(value = "/memberInfo/submit")
    @ResponseBody
    public AjaxResult memberInfo(PerformanceMemberAuditParam performanceMemberAuditParam) {
        boolean result = kylinPerformancesService.performanceMemberChange(performanceMemberAuditParam);
        return toAjax(result);
    }

    //    @Log(title = "演出列表-演出数据", businessType = BusinessType.LIST)
    //@RequiresPermissions("kylin:performances:view")
    @GetMapping(value = "/performanceStatic/{performancesId}")
    public String performanceStatic(@PathVariable("performancesId") String performancesId, ModelMap mmap) {

        PerformanceOrderStatisCountResp perCountResp = new PerformanceOrderStatisCountResp();
        List<PerformanceOrderStatisticalDao> result = new ArrayList<>();

        PerformanceTicketSalesDto ticketSalesInfo = openDataService.getPerformanceTicketSalesInfo(performancesId);
        if (ticketSalesInfo != null) {
            perCountResp.setPerformanceTitle(ticketSalesInfo.getPerformanceTitle());
            perCountResp.setTotalSalePrice(new BigDecimal(ticketSalesInfo.getFullSalesAmountTotal()));
            perCountResp.setSaleGeneral(new BigDecimal(ticketSalesInfo.getFullAudienceTicketTotal()));
            perCountResp.setTotalGeneral(new BigDecimal(ticketSalesInfo.getFullTotalGeneral()));
            perCountResp.setTotalRefundGeneral(new BigDecimal(ticketSalesInfo.getFullRefundTicketTotal()));
            perCountResp.setTotalBuyUsers(new BigDecimal(ticketSalesInfo.getFullBuyTotal()));

            List<PerformanceTicketSalesDto.TicketSales> fullTicketDataList = ticketSalesInfo.getFullTicketDataList();
            if (!fullTicketDataList.isEmpty()) {
                for (PerformanceTicketSalesDto.TicketSales ticketSales : fullTicketDataList) {
                    PerformanceOrderStatisticalDao statisticalDao = new PerformanceOrderStatisticalDao();
                    statisticalDao.setPerformancesId(ticketSalesInfo.getPerformanceId());
                    statisticalDao.setTicketsId(ticketSales.getTicketId());
                    statisticalDao.setTitle(ticketSales.getTicketTitle());
                    statisticalDao.setPrice(new BigDecimal(ticketSales.getTicketPrice()));
                    statisticalDao.setType(ticketSales.getTicketType());
                    statisticalDao.setTotalGeneral(new BigDecimal(ticketSales.getTotalGeneral()));
                    statisticalDao.setSaleGeneral(new BigDecimal(ticketSales.getAudienceTicketTotal()));
                    statisticalDao.setTotalRefundGeneral(new BigDecimal(ticketSales.getRefundTicketTotal()));
                    statisticalDao.setTotalPayingNumber(new BigDecimal(ticketSales.getPayingTotal()));
                    statisticalDao.setTimeId(ticketSales.getTimeId());
                    statisticalDao.setTimeTitle(ticketSales.getTimeTitle());
                    statisticalDao.setVipBuyTotal(ticketSales.getVipBuyTotal());
                    statisticalDao.setFullRefundTicketTotal(ticketSales.getFullRefundTicketTotal());
                    statisticalDao.setHandlingFeeRefundTicketTotal(ticketSales.getHandlingFeeRefundTicketTotal());
                    statisticalDao.setRefundFeeRevenueTotal(new BigDecimal(ticketSales.getRefundFeeRevenueTotal()));
                    statisticalDao.setAudienceSalesAmountTotal(new BigDecimal(ticketSales.getAudienceSalesAmountTotal()));
                    statisticalDao.setSurplusGeneral(new BigDecimal(ticketSales.getSurplusGeneral()));
                    result.add(statisticalDao);
                }
            }
        }else {
            //获取演出详情
            KylinPerformanceMisVo performanceMisVo = kylinPerformancesService.performanceDetails(performancesId);

            result = kylinPerformancesService.getPerformanceOrderStatisticalList(performancesId);
            perCountResp.setPerformanceTitle(performanceMisVo.getTitle());
            if (result.size() >= 2) {
                PerformanceOrderStatisticalDao resdao = result.get(result.size() - 1);
                perCountResp.setTotalSalePrice(resdao.getTotalSalePrice());
                perCountResp.setSaleGeneral(resdao.getSaleGeneral());
                perCountResp.setTotalGeneral(resdao.getTotalGeneral());
                perCountResp.setTotalExchange(resdao.getTotalExchange());
                perCountResp.setSurplusExchange(resdao.getSurplusGeneral());
                perCountResp.setTotalBuyUsers(resdao.getTotalBuyUsers());
                perCountResp.setTotalDisPrice(BigDecimal.ONE);
                perCountResp.setTotalRefundGeneral(resdao.getTotalRefundGeneral());
            }
        }

        mmap.put("perCountResp", perCountResp);
        mmap.put("perOrderStaticList", result);
        mmap.put("sumResp", DataSumUtils.sumStatistics(result));
        return prefix + "/performancesStatic";
    }

    //@RequiresPermissions("kylin:performances:view")
    @GetMapping(value = "/damai/{performancesId}")
    public String damai(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        KylinPerformanceDamaiVo result = kylinPerformancesService.getPerformanceDamai(performancesId);
        mmap.put("kylinPerformanceDamaiVo", result);
        return prefix + "/damai";
    }

    //@RequiresPermissions("kylin:performances:view")
    @GetMapping(value = "/agent/{performancesId}")
    public String agent(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        KylinPerformanceAgentVo result = kylinPerformancesService.getPerformanceAgent(performancesId);
        mmap.put("kylinPerformanceAgentVo", result);
        return prefix + "/agent";
    }

    @GetMapping(value = "/payTxt/{performancesId}")
    public String payTxt(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        KylinPerformancePayTxtVo result = kylinPerformancesService.getPerformancePayTxt(performancesId);
        mmap.put("kylinPerformancePayTxtVo", result);
        return prefix + "/payTxt";
    }
    
    /*
     * @description: 预约统计
     * @author: zjp
     * @date: 2024/9/11 17:03
     * @param: [performancesId, mmap]
     * @return: java.lang.String
     **/
    @GetMapping(value = "/subscribe/{performancesId}")
    public String subscribe(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        List<KylinPerformanceSubscribeTicketStatisticalDao> result = kylinPerformancesService.getPerformanceSubscribe(performancesId);
        mmap.put("subscribeStaticList", result);
        mmap.put("performancesId",performancesId);
        return prefix + "/subscribe";
    }

    /**
     * 演出阵容页面
     */
    @GetMapping(value = "/artistLineup/{performancesId}")
    public String artistLineup(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        try {
            // 获取演出信息
            KylinPerformanceMisVo performance = kylinPerformancesService.performanceDetails(performancesId);
            if (performance == null) {
                mmap.put("errorMsg", "演出不存在");
                return prefix + "/artistLineup";
            }

            // 将场次数据转换为JSON
            List<TicketTimesTicketCreatePartnerVo> ticketTimes = performance.getTicketTimes();
            String ticketTimesJson = "[]";
            if (ticketTimes != null && !ticketTimes.isEmpty()) {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                ticketTimesJson = mapper.writeValueAsString(ticketTimes);
            }

            mmap.put("performancesId", performancesId);
            mmap.put("performanceTitle", performance.getTitle());
            mmap.put("ticketTimesJson", ticketTimesJson);
            
            return prefix + "/artistLineup";
        } catch (Exception e) {
            mmap.put("errorMsg", "加载演出阵容失败: " + e.getMessage());
            return prefix + "/artistLineup";
        }
    }

    @Log(title = "预约统计:导出列表")
    @PostMapping("/subscribe/export")
    @ResponseBody
    public AjaxResult subscribeExport(@RequestParam("performancesId") String performancesId) {
        List<KylinPerformanceSubscribeTicketStatisticalDao> list = kylinPerformancesService.getPerformanceSubscribe(performancesId);
        ArrayList<KylinPerformanceSubscribeTicketStatisticalExportDao> listExport = new ArrayList<>();
        for (KylinPerformanceSubscribeTicketStatisticalDao kylinPerformanceSubscribeTicketStatisticalDao : list) {
            KylinPerformanceSubscribeTicketStatisticalExportDao kylinPerformanceSubscribeTicketStatisticalExportDao = new KylinPerformanceSubscribeTicketStatisticalExportDao();
            kylinPerformanceSubscribeTicketStatisticalExportDao.setTimeTitle(kylinPerformanceSubscribeTicketStatisticalDao.getTimeTitle());
            kylinPerformanceSubscribeTicketStatisticalExportDao.setTicketTimesTitle(kylinPerformanceSubscribeTicketStatisticalDao.getTicketTimesTitle());
            kylinPerformanceSubscribeTicketStatisticalExportDao.setSubscribeTotal(kylinPerformanceSubscribeTicketStatisticalDao.getSubscribeTotal());
            listExport.add(kylinPerformanceSubscribeTicketStatisticalExportDao);
        }
        ExcelUtil<KylinPerformanceSubscribeTicketStatisticalExportDao>  util = new ExcelUtil(KylinPerformanceSubscribeTicketStatisticalExportDao.class);
        return util.exportExcel(listExport, "预约统计");
    }
    //@RequiresPermissions("kylin:performances:view")
    @PostMapping(value = "/agent/change")
    @ResponseBody
    @Log(title = "演出管理：票种代理", businessType = BusinessType.PERFORMANCE_SAVE)
    public AjaxResult changeTicketAgent(@RequestParam("performancesId") String performancesId, @RequestParam("ticketsId") String ticketsId, @RequestParam("status") Integer status) {
        boolean result = kylinPerformancesService.changeTicketAgent(performancesId, ticketsId, status);
        return toAjax(result);
    }

    @PostMapping(value = "/payTxt/change")
    @ResponseBody
    @Log(title = "演出管理：支付文案", businessType = BusinessType.PERFORMANCE_SAVE)
    public AjaxResult changeTicketPayTxt(@RequestParam("performancesId") String performancesId, @RequestParam("ticketsId") String ticketsId, @RequestParam("payTxt") String payTxt) {
        boolean result = kylinPerformancesService.changeTicketPayTxt(performancesId, ticketsId, payTxt);
        return toAjax(result);
    }

    //@RequiresPermissions("kylin:performances:view")
    @PostMapping(value = "/damai/change")
    @ResponseBody
    public AjaxResult changeSysDamai(@RequestParam("params") String params) {
        List<SysDamaiParam> data = JsonUtils.fromJson(params, new TypeReference<List<SysDamaiParam>>() {
        });
        boolean result = kylinPerformancesService.changeSysDamai(data);
        return toAjax(result);
    }

    //@RequiresPermissions("kylin:performances:view")
    @PostMapping(value = "/sync/damai")
    @ResponseBody
    public AjaxResult syncDamai(@RequestParam("performancesId") String performancesId) {
        boolean result = damaiService.sycPerformance(performancesId);
        return toAjax(result);
    }

    //@RequiresPermissions("kylin:performances:view")
    @GetMapping(value = "/refundConfig/{performancesId}")
    public String getRefundConfig(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        PerformanceRefundConfigVo result = kylinPerformancesService.getRefundConfig(performancesId);
        mmap.put("performanceRefundConfigVo", result);
        return prefix + "/refundConfig";
    }

    @GetMapping(value = "/refundPoundage/{performancesId}")
    public String getRefundPoundage(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        ArrayList<OrderRefundPoundage> refundPoundageList = kylinPerformancesService.getRefundPoundageAll(performancesId);
        String refundPoundageExplain = kylinPerformancesService.getPoundageExplain(performancesId);
        mmap.put("performancesId", performancesId);
        mmap.put("refundPoundageList", refundPoundageList);
        mmap.put("refundPoundageExplain", refundPoundageExplain);
        return prefix + "/refundPoundage";
    }

    //
    @PostMapping(value = "/refundConfig/explain") //todo 阶梯退票
    @ApiOperation(value = "设置注意事项")
    @ResponseBody
    public AjaxResult setPoundageExplain(@RequestParam("explain") String explain,
                                         @RequestParam("performancesId") String performancesId) {
        String result = kylinPerformancesService.setPoundageExplain(explain, performancesId);
        return AjaxResult.success(result);
    }

    @GetMapping(value = "/refundConfig/explain") //todo 阶梯退票
    @ApiOperation(value = "获取注意事项")
    @ResponseBody
    public AjaxResult getPoundageExplain(@RequestParam("performancesId") String performancesId) {
        String result = kylinPerformancesService.getPoundageExplain(performancesId);
        return AjaxResult.success(result);
    }

    //阶梯退票
    @GetMapping(value = "/refundConfig/poundage") //todo 阶梯退票
    @ApiOperation(value = "获取阶梯退票")
    @ResponseBody
    public AjaxResult getRefundPoundageAll(@RequestParam("performancesId") String performancesId) {
        ArrayList<OrderRefundPoundage> result = kylinPerformancesService.getRefundPoundageAll(performancesId);
        return AjaxResult.success(result);
    }

    //
    @PostMapping(value = "/refundConfig/poundage") //todo 阶梯退票
    @ApiOperation(value = "设置阶梯退票")
    @ResponseBody
    public AjaxResult setRefundPoundageAll(@RequestBody OrderRefundPoundageF param) {
        String result = kylinPerformancesService.setRefundPoundageAll(param.getOrderRefundPoundage(), param.getPerformanceId());
        if (null != result && result.equals("操作成功")) {
            return AjaxResult.success(result);
        } else {
            return AjaxResult.error(result);
        }
    }

    //@RequiresPermissions("kylin:performances:view")
    @PostMapping(value = "/refundConfig/change")
    @ResponseBody
    @Log(title = "演出管理：退款配置", businessType = BusinessType.PERFORMANCE_SAVE)
    public AjaxResult changeRefundConfig(@RequestParam("performancesId") String performancesId,
                                         @RequestParam("isCanRefund") Integer isCanRefund,
                                         @RequestParam("refundOpenTime") String refundOpenTime,
                                         @RequestParam("refundCloseTime") String refundCloseTime,
                                         @RequestParam("isRefundPoundage") Integer isRefundPoundage,
                                         @RequestParam("isRefundVoucher") Integer isRefundVoucher,
                                         @RequestParam("isRefundExpress") Integer isRefundExpress,
                                         @RequestParam("isBackPaperTicket") Integer isBackPaperTicket,
                                         @RequestParam("isRefundExpressNew") Integer isRefundExpressNew) {
        String result = kylinPerformancesService.changeRefundConfig(performancesId, isCanRefund, refundOpenTime, refundCloseTime, isRefundPoundage, isRefundVoucher, isRefundExpress, isBackPaperTicket, isRefundExpressNew);
        return this.success(result);
    }

    @GetMapping(value = "/transferConfig/{performancesId}")
    public String getTransferConfig(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        PerformanceTransferConfigVo result = kylinPerformancesService.getTransferConfig(performancesId);
        mmap.put("performanceTransferConfigVo", result);
        return prefix + "/transferConfig";
    }

    @GetMapping(value = "/orderImport/{performancesId}")
    public String getOrderImport(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        mmap.put("performancesId", performancesId);
        return prefix + "/orderImport";
    }

    @PostMapping(value = "/orderImport/list/{performancesId}")
    @ResponseBody
    public TableDataInfo getOrderImportList(@PathVariable("performancesId") String performancesId, ModelMap mmap) {
        startPage();
        List<KylinOrderImport> result = kylinPerformancesService.getOrderImport(performancesId);
        return getDataTable(result);
    }

    @PostMapping(value = "/transferConfig/change")
    @ResponseBody
    @Log(title = "演出管理：转赠配置", businessType = BusinessType.PERFORMANCE_SAVE)
    public AjaxResult changeTransferConfig(@RequestParam("performancesId") String performancesId,
                                           @RequestParam("isCanTransfer") Integer isCanTransfer,
                                           @RequestParam("transferStartTime") String transferStartTime,
                                           @RequestParam("transferEndTime") String transferEndTime) {
        String result = kylinPerformancesService.changeTransferConfig(performancesId, isCanTransfer, transferStartTime, transferEndTime);
        return this.success(result);
    }

    @GetMapping(value = "/search")
    @ResponseBody
    public ResponseDto<List<KylinPerformancesVo>> searchPerformanceByTitle(@RequestParam(value = "title") String title) {
        List<KylinPerformancesVo> kylinPerformancesVoList = kylinPerformancesService.searchPerformanceByTitle(title);
        return ResponseDto.success(kylinPerformancesVoList);
    }

    @GetMapping("/performance/export")
    public void exportPerformance(@RequestParam(value = "performanceId") String performanceId, HttpServletResponse response) {
        try {
            PerformanceOrderStatisCountResp perCountResp = new PerformanceOrderStatisCountResp();
            List<PerformanceOrderStatisticalDao> result = new ArrayList<>();

            PerformanceTicketSalesDto ticketSalesInfo = openDataService.getPerformanceTicketSalesInfo(performanceId);
            if (ticketSalesInfo != null) {
                perCountResp.setPerformanceTitle(ticketSalesInfo.getPerformanceTitle());
                perCountResp.setTotalSalePrice(new BigDecimal(ticketSalesInfo.getFullSalesAmountTotal()));
                perCountResp.setSaleGeneral(new BigDecimal(ticketSalesInfo.getFullAudienceTicketTotal()));
                perCountResp.setTotalGeneral(new BigDecimal(ticketSalesInfo.getFullTotalGeneral()));
                perCountResp.setTotalRefundGeneral(new BigDecimal(ticketSalesInfo.getFullRefundTicketTotal()));
                perCountResp.setTotalBuyUsers(new BigDecimal(ticketSalesInfo.getFullBuyTotal()));

                List<PerformanceTicketSalesDto.TicketSales> fullTicketDataList = ticketSalesInfo.getFullTicketDataList();
                if (!fullTicketDataList.isEmpty()) {
                    for (PerformanceTicketSalesDto.TicketSales ticketSales : fullTicketDataList) {
                        PerformanceOrderStatisticalDao statisticalDao = new PerformanceOrderStatisticalDao();
                        statisticalDao.setPerformancesId(ticketSalesInfo.getPerformanceId());
                        statisticalDao.setTicketsId(ticketSales.getTicketId());
                        statisticalDao.setTitle(ticketSales.getTicketTitle());
                        statisticalDao.setPrice(new BigDecimal(ticketSales.getTicketPrice()));
                        statisticalDao.setType(ticketSales.getTicketType());
                        statisticalDao.setTotalGeneral(new BigDecimal(ticketSales.getTotalGeneral()));
                        statisticalDao.setSaleGeneral(new BigDecimal(ticketSales.getAudienceTicketTotal()));
                        statisticalDao.setTotalRefundGeneral(new BigDecimal(ticketSales.getRefundTicketTotal()));
                        statisticalDao.setTotalPayingNumber(new BigDecimal(ticketSales.getPayingTotal()));
                        statisticalDao.setTimeId(ticketSales.getTimeId());
                        statisticalDao.setTimeTitle(ticketSales.getTimeTitle());
                        statisticalDao.setVipBuyTotal(ticketSales.getVipBuyTotal());
                        statisticalDao.setFullRefundTicketTotal(ticketSales.getFullRefundTicketTotal());
                        statisticalDao.setHandlingFeeRefundTicketTotal(ticketSales.getHandlingFeeRefundTicketTotal());
                        statisticalDao.setRefundFeeRevenueTotal(new BigDecimal(ticketSales.getRefundFeeRevenueTotal()));
                        statisticalDao.setAudienceSalesAmountTotal(new BigDecimal(ticketSales.getAudienceSalesAmountTotal()));
                        statisticalDao.setSurplusGeneral(new BigDecimal(ticketSales.getSurplusGeneral()));
                        result.add(statisticalDao);
                    }
                }
            }
            // 汇总数据
            PerformanceTicketSumDto sumResp = DataSumUtils.sumStatistics(result);

            // 创建 Excel
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("演出数据");

            // 表头
            String[] headers = {
                    "场次", "票种类型", "票种名称", "票种价格", "库存数量", "销售数量", "余票数量",
                    "登登登VIP购票数量", "正在支付数量", "退票总数量", "全额退票数量",
                    "手续费退票数量", "退票手续费收益", "票面销售金额"
            };

            XSSFRow headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                headerRow.createCell(i).setCellValue(headers[i]);
            }

            // 数据行
            int rowNum = 1;
            for (PerformanceOrderStatisticalDao item : result) {
                XSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(item.getTimeTitle());
                row.createCell(1).setCellValue(item.getType().equals(1) ? "单日票" : "通票"); // 记得在后端先做字典翻译
                row.createCell(2).setCellValue(item.getTitle());
                row.createCell(3).setCellValue(item.getPrice().toPlainString());
                row.createCell(4).setCellValue(item.getTotalGeneral().toPlainString());
                row.createCell(5).setCellValue(item.getSaleGeneral().toPlainString());
                row.createCell(6).setCellValue(item.getSurplusGeneral().toPlainString());
                row.createCell(7).setCellValue(item.getVipBuyTotal());
                row.createCell(8).setCellValue(item.getTotalPayingNumber().toPlainString());
                row.createCell(9).setCellValue(item.getTotalRefundGeneral().toPlainString());
                row.createCell(10).setCellValue(item.getFullRefundTicketTotal());
                row.createCell(11).setCellValue(item.getHandlingFeeRefundTicketTotal());
                row.createCell(12).setCellValue(item.getRefundFeeRevenueTotal().toPlainString());
                row.createCell(13).setCellValue(item.getAudienceSalesAmountTotal().toPlainString());
            }

            // 合计行
            XSSFRow totalRow = sheet.createRow(rowNum);
            totalRow.createCell(0).setCellValue("总计");
            totalRow.createCell(4).setCellValue(sumResp.getTotalGeneralSum().toPlainString());
            totalRow.createCell(5).setCellValue(sumResp.getSaleGeneralSum().toPlainString());
            totalRow.createCell(6).setCellValue(sumResp.getSurplusGeneralSum().toPlainString());
            totalRow.createCell(7).setCellValue(sumResp.getVipBuyTotalSum().toPlainString());
            totalRow.createCell(8).setCellValue(sumResp.getTotalPayingNumberSum().toPlainString());
            totalRow.createCell(9).setCellValue(sumResp.getTotalRefundGeneralSum().toPlainString());
            totalRow.createCell(10).setCellValue(sumResp.getFullRefundTicketTotalSum().toPlainString());
            totalRow.createCell(11).setCellValue(sumResp.getHandlingFeeRefundTicketTotalSum().toPlainString());
            totalRow.createCell(12).setCellValue(sumResp.getRefundFeeRevenueTotalSum().toPlainString());
            totalRow.createCell(13).setCellValue(sumResp.getAudienceSalesAmountTotalSum().toPlainString());

            // 响应头
            String fileName = URLEncoder.encode("演出统计数据.xlsx", StandardCharsets.UTF_8.name());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 写出文件
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
