package com.yd.csf.api.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.common.exception.BusinessException;
import com.yd.csf.api.service.ApiCommissionExpectedService;
import com.yd.csf.service.dto.CommissionExpectedQueryRequest;
import com.yd.csf.service.model.CommissionExpected;
import com.yd.csf.service.service.CommissionExpectedService;
import com.yd.csf.service.service.PolicyFollowService;
import com.yd.csf.service.vo.CommissionExpectedExportDTO;
import com.yd.csf.service.vo.CommissionExpectedExportNewDTO;
import com.yd.csf.service.vo.CommissionExpectedNewVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApiCommissionExpectedServiceImpl implements ApiCommissionExpectedService {

    @Resource
    private PolicyFollowService policyFollowService;
    @Resource
    private CommissionExpectedService commissionExpectedService;

    /**
     * 应收款导出（新）
     *
     * @param commissionExpectedQueryRequest
     * @return
     */
    @Override
    public void exportCommissionExpectedNew(CommissionExpectedQueryRequest commissionExpectedQueryRequest, HttpServletResponse response) throws UnsupportedEncodingException {
        if (commissionExpectedQueryRequest == null) {
            throw new RuntimeException("查询参数不能为空");
        }

        // 设置响应头
        String fileName = URLEncoder.encode("应收款管理数据", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        //保單持有人（中/英、繁简/大小写）、签单人、转介人名称（主）、受保人（中/英、繁简/大小写）、查询保单号列表
        List<String> queryPolicyNoList = policyFollowService.queryPolicyNoList(commissionExpectedQueryRequest.getPolicyHolder(),
                commissionExpectedQueryRequest.getSigner(),
                commissionExpectedQueryRequest.getBrokerName(),
                commissionExpectedQueryRequest.getInsured());
        // 构建查询条件
        commissionExpectedQueryRequest.setPolicyNoList(queryPolicyNoList);
        QueryWrapper<CommissionExpected> queryWrapper = commissionExpectedService.getQueryWrapper(commissionExpectedQueryRequest);
        // 先查询所有符合条件的记录列表
        List<CommissionExpected> allCommissionExpectedList = commissionExpectedService.list(queryWrapper);
        if (CollectionUtils.isEmpty(allCommissionExpectedList)) {
            throw new BusinessException("无导出数据");
        }
        commissionExpectedQueryRequest.setPageNo(1);
        commissionExpectedQueryRequest.setPageSize(99999999);
        Page<CommissionExpectedNewVO> page = commissionExpectedService.getCommissionExpectedVONewPage(commissionExpectedQueryRequest,allCommissionExpectedList);
        log.info("应收款导出=>查询所有符合条件的记录列表=>Page<CommissionExpectedNewVO>:{}", JSON.toJSONString(page));
        // 转换为导出DTO
        List<CommissionExpectedExportNewDTO> exportDataList = page.getRecords().stream()
                .map(CommissionExpectedExportNewDTO::convertToExportDTO)
                .collect(Collectors.toList());
        log.info("应收款导出=>转换为导出DTO=>exportDataList:{}", JSON.toJSONString(exportDataList));
        // 使用EasyExcel导出
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), CommissionExpectedExportNewDTO.class).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet("应收款数据").build();
            excelWriter.write(exportDataList, writeSheet);
        } catch (Exception e) {
            throw new RuntimeException("导出应收款数据失败", e);
        }

    }
}
