package com.wms_main.excel.easypoi.service.serviceImpl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms_main.dao.ITAppDbsService;
import com.wms_main.dao.ITAppProductExtendService;
import com.wms_main.dao.ITAppProductService;
import com.wms_main.dao.ITAppSingleProductService;
import com.wms_main.excel.easypoi.excelTemplate.DbsExcelTemplate;
import com.wms_main.excel.easypoi.excelTemplate.ProductExcelTemplate;
import com.wms_main.excel.easypoi.excelTemplate.ProductExtendExcelTemplate;
import com.wms_main.excel.easypoi.excelTemplate.SingleProductExcelTemplate;
import com.wms_main.excel.easypoi.service.IExportExcelEasyPoi;
import com.wms_main.model.dto.query.KittingBomQuery;
import com.wms_main.model.dto.query.KittingBomRelationQuery;
import com.wms_main.model.po.TAppDbs;
import com.wms_main.model.dto.query.DbsQuery;
import com.wms_main.model.po.TAppProduct;
import com.wms_main.model.po.TAppProductExtend;
import com.wms_main.model.po.TAppSingleProduct;
import com.wms_main.repository.utils.StringUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ExportExcelEasyPoi implements IExportExcelEasyPoi {
    private final ITAppDbsService tAppDbsService;// DBS服务
    private final ITAppProductService tAppProductService;// 总成服务
    private final ITAppProductExtendService tAppProductExtendService;// 配对关系服务
    private final ITAppSingleProductService tAppSingleProductService;// 单片服务

    /**
     * 导出DBS计划实现
     * @param dbsQuery 查询条件
     * @param response 响应
     * @throws IOException 异常
     */
    @Override
    public void doExportDbs(DbsQuery dbsQuery, HttpServletResponse response) throws IOException {
        if (dbsQuery == null) {
            throw new IOException("参数不能为空");
        }
        // DBS列表
        List<TAppDbs> dbsList = tAppDbsService.selectList(BeanUtil.copyProperties(dbsQuery, TAppDbs.class));
        // excel模版列表
        List<DbsExcelTemplate> resultList = new ArrayList<>();
        if (!dbsList.isEmpty()) {
            for (TAppDbs dbs : dbsList) {
                resultList.add(new DbsExcelTemplate(
                        dbs.getWorkOrder(),
                        dbs.getProductIdOrigin(),
                        dbs.getTestPlanStartDate(),
                        dbs.getTestPlanFinishDate(),
                        dbs.getPntPlanStartDate(),
                        dbs.getPntPlanFinishDate(),
                        dbs.getPlanProduction(),
                        dbs.getEquipmentName(),
                        dbs.getWorkShift(),
                        dbs.getFamily(),
                        dbs.getTestNo(),
                        dbs.getKittingRemark(),
                        dbs.getRemark()
                ));
            }
        } else {
            resultList.add(new DbsExcelTemplate());
        }
        doWriteExcel("DBS计划", response, resultList, DbsExcelTemplate.class);
    }

    /**
     * 导出配料单
     * @param kittingBomQuery 查询条件
     * @param response 响应
     * @throws IOException 异常
     */
    @Override
    public void doExportKittingBom(KittingBomQuery kittingBomQuery, HttpServletResponse response) throws IOException {
        if (kittingBomQuery == null || kittingBomQuery.getBomType() == null) {
            throw new IOException("参数不能为空");
        }
        // 1. 查询总成
        if (kittingBomQuery.getBomType() == 1) {
            List<TAppProduct> productList = tAppProductService.list(new LambdaQueryWrapper<TAppProduct>()
                    .like(StringUtils.isNotEmpty(kittingBomQuery.getModel()), TAppProduct::getModel, kittingBomQuery.getModel())
                    .like(StringUtils.isNotEmpty(kittingBomQuery.getProductId()), TAppProduct::getProductId, kittingBomQuery.getProductId())
                    .like(StringUtils.isNotEmpty(kittingBomQuery.getGoodsId()), TAppProduct::getGoodsId, kittingBomQuery.getGoodsId())
                    .like(StringUtils.isNotEmpty(kittingBomQuery.getBoxNo()), TAppProduct::getBoxNo, kittingBomQuery.getBoxNo()));
            // excel模版列表
            List<ProductExcelTemplate> resultList = new ArrayList<>();
            if (!productList.isEmpty()) {
                for (TAppProduct product : productList) {
                    resultList.add(new ProductExcelTemplate(
                            product.getModel(),
                            product.getProductId(),
                            product.getGoodsId(),
                            product.getGoodsDescription(),
                            product.getQuantity1Pair(),
                            product.getBoxNo(),
                            product.getQuantityOfPair()
                    ));
                }
            } else {
                resultList.add(new ProductExcelTemplate());
            }
            doWriteExcel("总成配料单", response, resultList, ProductExcelTemplate.class);
        } else if (kittingBomQuery.getBomType() == 2) {
            // 单片配料单
            List<TAppSingleProduct> singleProductList = tAppSingleProductService.list(new LambdaQueryWrapper<TAppSingleProduct>()
                    .like(StringUtils.isNotEmpty(kittingBomQuery.getModel()), TAppSingleProduct::getModel, kittingBomQuery.getModel())
                    .like(StringUtils.isNotEmpty(kittingBomQuery.getProductId()), TAppSingleProduct::getProductId, kittingBomQuery.getProductId())
                    .like(StringUtils.isNotEmpty(kittingBomQuery.getGoodsId()), TAppSingleProduct::getGoodsId, kittingBomQuery.getGoodsId())
                    .like(StringUtils.isNotEmpty(kittingBomQuery.getBoxNo()), TAppSingleProduct::getBoxNo, kittingBomQuery.getBoxNo()));
            // excel模版列表
            List<SingleProductExcelTemplate> resultList = new ArrayList<>();
            if (!singleProductList.isEmpty()) {
                for (TAppSingleProduct singleProduct : singleProductList) {
                    resultList.add(new SingleProductExcelTemplate(
                            singleProduct.getModel(),
                            singleProduct.getProductId(),
                            singleProduct.getGoodsId(),
                            singleProduct.getGoodsDescription(),
                            singleProduct.getQuantity1Pair(),
                            singleProduct.getBoxNo(),
                            singleProduct.getQuantityOfPair()
                    ));
                }
            } else {
                resultList.add(new SingleProductExcelTemplate());
            }
            doWriteExcel("单片配料单", response, resultList, SingleProductExcelTemplate.class);
        } else {
            throw new IOException("配料单类型不在设定值范围内。");
        }
    }

    /**
     * 导出配对关系实现
     * @param kittingBomRelationQuery 查询条件
     * @param response 响应
     * @throws IOException 异常
     */
    @Override
    public void doExportKittingBomRelations(KittingBomRelationQuery kittingBomRelationQuery, HttpServletResponse response) throws IOException {
        if (kittingBomRelationQuery == null) {
            throw new IOException("参数不能为空");
        }
        // DBS列表
        List<TAppProductExtend> extendList = tAppProductExtendService.list(new LambdaQueryWrapper<TAppProductExtend>()
                .like(StringUtils.isNotEmpty(kittingBomRelationQuery.getModel()), TAppProductExtend::getModel, kittingBomRelationQuery.getModel())
                .like(StringUtils.isNotEmpty(kittingBomRelationQuery.getProductId()), TAppProductExtend::getProductId, kittingBomRelationQuery.getProductId())
                .like(StringUtils.isNotEmpty(kittingBomRelationQuery.getSingleProductId()), TAppProductExtend::getSingleProductId, kittingBomRelationQuery.getSingleProductId()));
        // excel模版列表
        List<ProductExtendExcelTemplate> resultList = new ArrayList<>();
        if (!extendList.isEmpty()) {
            for (TAppProductExtend bomRelation : extendList) {
                resultList.add(new ProductExtendExcelTemplate(
                        bomRelation.getModel(),
                        bomRelation.getProductId(),
                        bomRelation.getSingleProductId()
                ));
            }
        } else {
            resultList.add(new ProductExtendExcelTemplate());
        }
        doWriteExcel("配对关系", response, resultList, ProductExtendExcelTemplate.class);
    }

    /**
     * 写入excel
     * @param fileDesc 文件描述
     * @param response 响应
     * @param list 数据列表
     * @param clazz 泛型类
     * @param <T> 泛型
     * @throws IOException 异常
     */
    private <T> void doWriteExcel(String fileDesc, HttpServletResponse response, List<T> list, Class<T> clazz) throws IOException {
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName(fileDesc);
        exportParams.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
        setResponseHeaderOfExcel(fileDesc, response);
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    /**
     * 设置统一的excel头部文件
     * @param fileDesc 文件名描述
     * @param response 响应
     */
    private void setResponseHeaderOfExcel(String fileDesc, HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(fileDesc, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}
