package com.hzs.report.member.controller.manage;/**
 * @Description:
 * @Author: yuhui
 * @Time: 2024/7/17 14:36
 * @Classname: ProductSalesStatController
 * @PackageName: com.hzs.report.member.controller.manage
 */

import com.github.pagehelper.PageInfo;
import com.hzs.common.core.constant.HttpStatus;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.report.member.service.MemberReportService;
import com.hzs.report.member.vo.ProductSaleProductVO;
import com.hzs.report.member.vo.ProductSaleStatVo;
import com.hzs.report.member.vo.ProductSaleWaresVO;
import com.hzs.report.member.vo.WaresInfoVO;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @BelongsProject: hzs_cloud
 * @BelongsPackage: com.hzs.report.member.controller.manage
 * @Author: yh
 * @CreateTime: 2024-07-17  14:36
 * @Description: TODO
 * @Version: 1.0
 */
@RequestMapping("/manager/product-sales")
@RestController
public class ProductSalesStatController extends BaseController {

    @Autowired
    private MemberReportService memberReportService;


    /**
     * 产品销量统计
     *
     * @param skuCode
     * @param productName
     * @param orderType
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("product-sales-stat")
    public TableDataInfo productSalesStat(String skuCode, String productName, Integer orderType, Date startTime, Date endTime) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (startTime != null) {
            startTime = DateUtils.getStartTime(startTime);
        }
        if (endTime != null) {
            endTime = DateUtils.getEndTime(endTime);
        }
        List<ProductSaleStatVo> productSaleStatList = memberReportService.productSaleStatList(skuCode, productName, orderType, startTime, endTime, pkCountry);
        for (ProductSaleStatVo productSaleStatVo : productSaleStatList) {
            // 产品+ 规格分组 计算小计
            productSaleStatVo.setGroupByInfo(productSaleStatVo.getPkProduct() + "-" + productSaleStatVo.getSpecsNameId());
            productSaleStatVo.setWaresSpecs(productSaleStatVo.getSpecsName() + "*" + (productSaleStatVo.getSpecsQuantity() == null ? "" : productSaleStatVo.getSpecsQuantity()));
        }

        // 计算小计
        LinkedHashMap<String, List<ProductSaleStatVo>> productMapList = productSaleStatList.stream().collect(Collectors.groupingBy(ProductSaleStatVo::getGroupByInfo, LinkedHashMap::new, Collectors.collectingAndThen(Collectors.toList(), list -> {
            list.sort(Comparator.comparing(ProductSaleStatVo::getSkuCode));
            return list;
        })));
        // 计算小计的最终list
        List<ProductSaleStatVo> subtotalList = new ArrayList<>();
        for (Map.Entry<String, List<ProductSaleStatVo>> str : productMapList.entrySet()) {
            Integer productQuantity = 0;
            Integer waresQuantity = 0;
            Collections.sort(str.getValue(), new Comparator<ProductSaleStatVo>() {
                @Override
                public int compare(ProductSaleStatVo o1, ProductSaleStatVo o2) {
                    return o1.getPkProduct().compareTo(o2.getPkProduct());
                }
            });
            List<ProductSaleStatVo> saleStatList = str.getValue();
            for (ProductSaleStatVo productSaleStatVo : str.getValue()) {
                productQuantity += productSaleStatVo.getProductQuantity();
                waresQuantity += productSaleStatVo.getWaresQuantity();
            }
            str.getValue().get(0);
            ProductSaleStatVo productSaleStatVo = new ProductSaleStatVo();
            productSaleStatVo.setWaresName("小计");
            productSaleStatVo.setPkWares(0);
            if (saleStatList.size() > 0) {
                ProductSaleStatVo pss = saleStatList.get(0);
                productSaleStatVo.setSkuCode(pss.getSkuCode());
                productSaleStatVo.setProductName(pss.getProductName());
                productSaleStatVo.setUnitStr(pss.getUnitStr());
                productSaleStatVo.setSpecsName(pss.getSpecsName());
                productSaleStatVo.setSpecsNameId(pss.getSpecsNameId());
                productSaleStatVo.setWaresCode(pss.getWaresCode());
            }

            productSaleStatVo.setGroupByInfo(str.getKey());
            productSaleStatVo.setPkProduct(Integer.parseInt(str.getKey().split("-")[0]));
            productSaleStatVo.setProductQuantity(productQuantity);
            productSaleStatVo.setWaresQuantity(waresQuantity);
            subtotalList.add(productSaleStatVo);
            subtotalList.addAll(str.getValue());
        }

        // 计算总计
        List<ProductSaleStatVo> resultList = new ArrayList<>();
        LinkedHashMap<Integer, List<ProductSaleStatVo>> waresMapList = subtotalList.stream().collect(Collectors.groupingBy(ProductSaleStatVo::getPkProduct, LinkedHashMap::new, Collectors.toList()));
        double sort = 0;
        for (Map.Entry<Integer, List<ProductSaleStatVo>> str : waresMapList.entrySet()) {
            Integer productQuantity = 0;
            Integer waresQuantity = 0;
            Collections.sort(str.getValue(), new Comparator<ProductSaleStatVo>() {
                @Override
                public int compare(ProductSaleStatVo o1, ProductSaleStatVo o2) {
                    if (o1.getSpecsNameId() != null && o2.getSpecsNameId() != null) {
                        return o1.getSpecsNameId().compareTo(o2.getSpecsNameId());
                    } else {
                        return -1;
                    }
                }
            });
            for (ProductSaleStatVo productSaleStatVo : str.getValue()) {
                // 判断是否是小计 是小计 则不计算入总计
                if (productSaleStatVo.getPkWares() == null || !productSaleStatVo.getPkWares().equals(0)) {
                    productQuantity += productSaleStatVo.getProductQuantity();
                    waresQuantity += productSaleStatVo.getWaresQuantity();
                }
                productSaleStatVo.setProductSort(sort);
            }
            ProductSaleStatVo productSaleStatVo = new ProductSaleStatVo();
            productSaleStatVo.setWaresName("总计");
            productSaleStatVo.setProductSort(sort + 0.1);
            //   productSaleStatVo.setGroupByInfo(str.getKey());
            productSaleStatVo.setProductQuantity(productQuantity);
            productSaleStatVo.setWaresQuantity(waresQuantity);
            resultList.add(productSaleStatVo);
            resultList.addAll(str.getValue());
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(resultList);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(productSaleStatList).getTotal());
        return rspData;
    }


    /**
     * 导出
     *
     * @param skuCode
     * @param productName
     * @param orderType
     * @param startTime
     * @param endTime
     * @param response
     */
    @PostMapping("product-sales-stat-export")
    public void productSalesStatExport1(String skuCode, String productName, Integer orderType, Date startTime, Date endTime, HttpServletResponse response) {
        //startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (startTime != null) {
            startTime = DateUtils.getStartTime(startTime);
        }
        if (endTime != null) {
            endTime = DateUtils.getEndTime(endTime);
        }
        List<ProductSaleStatVo> productSaleStatList = memberReportService.productSaleStatList(skuCode, productName, orderType, startTime, endTime, pkCountry);
        for (ProductSaleStatVo productSaleStatVo : productSaleStatList) {
            // 产品+ 规格分组 计算小计
            productSaleStatVo.setGroupByInfo(productSaleStatVo.getPkProduct() + "-" + productSaleStatVo.getSpecsNameId());
            productSaleStatVo.setWaresSpecs(productSaleStatVo.getSpecsName() + "*" + (productSaleStatVo.getSpecsQuantity() == null ? "" : productSaleStatVo.getSpecsQuantity()));
        }
        // 计算小计
        LinkedHashMap<String, List<ProductSaleStatVo>> productMapList = productSaleStatList.stream().collect(Collectors.groupingBy(ProductSaleStatVo::getGroupByInfo, LinkedHashMap::new, Collectors.collectingAndThen(Collectors.toList(), list -> {
            list.sort(Comparator.comparing(ProductSaleStatVo::getSkuCode));
            return list;
        })));
        // 计算小计的最终list
        List<ProductSaleStatVo> subtotalList = new ArrayList<>();
        for (Map.Entry<String, List<ProductSaleStatVo>> str : productMapList.entrySet()) {
            Integer productQuantity = 0;
            Integer waresQuantity = 0;
            Collections.sort(str.getValue(), new Comparator<ProductSaleStatVo>() {
                @Override
                public int compare(ProductSaleStatVo o1, ProductSaleStatVo o2) {
                    return o1.getPkProduct().compareTo(o2.getPkProduct());
                }
            });
            List<ProductSaleStatVo> saleStatList = str.getValue();
            for (ProductSaleStatVo productSaleStatVo : str.getValue()) {
                productQuantity += productSaleStatVo.getProductQuantity();
                waresQuantity += productSaleStatVo.getWaresQuantity();
            }
            str.getValue().get(0);
            ProductSaleStatVo productSaleStatVo = new ProductSaleStatVo();
            productSaleStatVo.setWaresName("小计");
            productSaleStatVo.setPkWares(0);
            if (saleStatList.size() > 0) {
                ProductSaleStatVo pss = saleStatList.get(0);
                productSaleStatVo.setSkuCode(pss.getSkuCode());
                productSaleStatVo.setProductName(pss.getProductName());
                productSaleStatVo.setUnitStr(pss.getUnitStr());
                productSaleStatVo.setSpecsName(pss.getSpecsName());
                productSaleStatVo.setSpecsNameId(pss.getSpecsNameId());
                productSaleStatVo.setWaresCode(pss.getWaresCode());
            }

            productSaleStatVo.setGroupByInfo(str.getKey());
            productSaleStatVo.setPkProduct(Integer.parseInt(str.getKey().split("-")[0]));
            productSaleStatVo.setProductQuantity(productQuantity);
            productSaleStatVo.setWaresQuantity(waresQuantity);
            subtotalList.add(productSaleStatVo);
            subtotalList.addAll(str.getValue());
        }

        // 计算总计
        List<ProductSaleStatVo> resultList = new ArrayList<>();
        LinkedHashMap<Integer, List<ProductSaleStatVo>> waresMapList = subtotalList.stream().collect(Collectors.groupingBy(ProductSaleStatVo::getPkProduct, LinkedHashMap::new, Collectors.toList()));
        double sort = 0;
        for (Map.Entry<Integer, List<ProductSaleStatVo>> str : waresMapList.entrySet()) {
            Integer productQuantity = 0;
            Integer waresQuantity = 0;
            Collections.sort(str.getValue(), new Comparator<ProductSaleStatVo>() {
                @Override
                public int compare(ProductSaleStatVo o1, ProductSaleStatVo o2) {
                    if (o1.getSpecsNameId() != null && o2.getSpecsNameId() != null) {
                        return o1.getSpecsNameId().compareTo(o2.getSpecsNameId());
                    } else {
                        return -1;
                    }
                }
            });
            for (ProductSaleStatVo productSaleStatVo : str.getValue()) {
                // 判断是否是小计 是小计 则不计算入总计
                if (productSaleStatVo.getPkWares() == null || !productSaleStatVo.getPkWares().equals(0)) {
                    productQuantity += productSaleStatVo.getProductQuantity();
                    waresQuantity += productSaleStatVo.getWaresQuantity();
                }
                productSaleStatVo.setProductSort(sort);
            }
            ProductSaleStatVo productSaleStatVo = new ProductSaleStatVo();
            productSaleStatVo.setWaresName("总计");
            productSaleStatVo.setProductSort(sort + 0.1);
            //   productSaleStatVo.setGroupByInfo(str.getKey());
            productSaleStatVo.setProductQuantity(productQuantity);
            productSaleStatVo.setWaresQuantity(waresQuantity);
            resultList.add(productSaleStatVo);
            resultList.addAll(str.getValue());
        }
        //导出
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        //    sheet.setColumnWidth(0,25 * 256);

        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        createRowTitle(sheet, style);
        Integer num = 0;
        Map<String, Integer> countMap = new HashMap<>();
        for (int i = 0; i < resultList.size(); i++) {
            ProductSaleStatVo productSaleStatVo = resultList.get(i);
            if (productSaleStatVo.getSpecsNameId() != null) {
                //为空表示总计  合并数量
                Boolean isMerge = false;
                if (countMap.get(productSaleStatVo.getSkuCode()) == null) {
                    // 表示第一层 需要合并行列
                    isMerge = true;
                }
                Integer number = 0;
                for (ProductSaleStatVo saleStatVo : resultList) {
                    if (saleStatVo.getSkuCode() != null) {
                        if (saleStatVo.getSkuCode().equals(productSaleStatVo.getSkuCode())) {
                            number += 1;
                        }
                    }
                }
                countMap.put(productSaleStatVo.getSkuCode(), number);
                //List<ProductSaleWaresVO> productSaleWaresList = resultList.get(i).getProductSaleWaresVOList();
                if (isMerge) {

                    // 加入判断 单个单元格无法合并
                    CellRangeAddress region = new CellRangeAddress(num + 1, num + number, 0, 0);
                    sheet.addMergedRegion(region);
                    CellRangeAddress region1 = new CellRangeAddress(num + 1, num + number, 1, 1);
                    sheet.addMergedRegion(region1);
                    CellRangeAddress region2 = new CellRangeAddress(num + 1, num + number, 2, 2);
                    sheet.addMergedRegion(region2);
                    CellRangeAddress region3 = new CellRangeAddress(num + 1, num + number, 3, 3);
                    sheet.addMergedRegion(region3);

                }
            }
            Row dataRow = sheet.createRow(num + 1);
            Cell cell0 = dataRow.createCell(0);
            cell0.setCellValue(productSaleStatVo.getSkuCode());
            cell0.setCellStyle(style);

            Cell cell1 = dataRow.createCell(1);
            cell1.setCellValue(productSaleStatVo.getProductName());
            cell1.setCellStyle(style);
            Cell cell2 = dataRow.createCell(2);
            cell2.setCellValue(productSaleStatVo.getUnitStr());
            cell2.setCellStyle(style);
            Cell cell3 = dataRow.createCell(3);
            cell3.setCellValue(productSaleStatVo.getSpecsName());
            cell3.setCellStyle(style);
            Cell cell4 = dataRow.createCell(4);
            cell4.setCellValue(productSaleStatVo.getWaresCode());
            cell4.setCellStyle(style);
            Cell cell5 = dataRow.createCell(5);
            cell5.setCellValue(productSaleStatVo.getWaresName());
            cell5.setCellStyle(style);
            Cell cell6 = dataRow.createCell(6);
            cell6.setCellValue(productSaleStatVo.getWaresSpecs());
            cell6.setCellStyle(style);
            Cell cell7 = dataRow.createCell(7);
            cell7.setCellValue(productSaleStatVo.getProductQuantity());
            cell7.setCellStyle(style);
            Cell cell8 = dataRow.createCell(8);
            cell8.setCellValue(productSaleStatVo.getWaresQuantity());
            cell8.setCellStyle(style);
            num += 1;


        }

        try {
            File file = new File("产品销量排行.xls");

            FileOutputStream fos = new FileOutputStream(file);
            workbook.write(fos);
            fos.close();
            String fileName = file.getName();

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

            FileInputStream fis = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = fis.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            fis.close();
            out.close();


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


    }

    /**
     * 创建表头
     *
     * @param sheet
     * @param style
     */
    private void createRowTitle(Sheet sheet, CellStyle style) {
        // 创建表头
        Row headerRow = sheet.createRow(0);
        Cell headerCell0 = headerRow.createCell(0);
        headerCell0.setCellValue("SKU编码");
        headerCell0.setCellStyle(style);

        Cell headerCell1 = headerRow.createCell(1);
        headerCell1.setCellValue("产品名称");
        headerCell1.setCellStyle(style);
        Cell headerCell2 = headerRow.createCell(2);
        headerCell2.setCellValue("产品单位");
        headerCell2.setCellStyle(style);

        Cell headerCell3 = headerRow.createCell(3);
        headerCell3.setCellValue("产品规格");
        headerCell3.setCellStyle(style);

        Cell headerCell4 = headerRow.createCell(4);
        headerCell4.setCellValue("商品编码");
        headerCell4.setCellStyle(style);
        Cell headerCell5 = headerRow.createCell(5);
        headerCell5.setCellValue("商品名称");
        headerCell5.setCellStyle(style);
        Cell headerCell6 = headerRow.createCell(6);
        headerCell6.setCellValue("商品规格(产品规格*数量)");
        headerCell6.setCellStyle(style);
        Cell headerCell7 = headerRow.createCell(7);
        headerCell7.setCellValue("产品数量");
        headerCell7.setCellStyle(style);
        Cell headerCell8 = headerRow.createCell(8);
        headerCell8.setCellValue("商品数量");
        headerCell8.setCellStyle(style);
    }


}
