package com.slodon.b2b2c.model.statistics;

import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.util.ExcelUtil;
import com.slodon.b2b2c.core.util.FileDownloadUtils;
import com.slodon.b2b2c.dao.read.statistics.ProvinceDayReadMapper;
import com.slodon.b2b2c.dao.write.statistics.ProvinceDayWriteMapper;
import com.slodon.b2b2c.statistics.example.ProvinceDayExample;
import com.slodon.b2b2c.statistics.pojo.ProvinceDay;
import com.slodon.b2b2c.statistics.pojo.base.ProvinceBase;
import com.slodon.b2b2c.vo.statistics.RegionReportVO;
import com.slodon.b2b2c.vo.statistics.SalesTrendVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 省份日统计表model
 */
@Component
@Slf4j
public class ProvinceDayModel {

    @Resource
    private ProvinceDayReadMapper provinceDayReadMapper;
    @Resource
    private ProvinceDayWriteMapper provinceDayWriteMapper;

    /**
     * 新增省份日统计表
     *
     * @param provinceDay
     * @return
     */
    public Integer saveProvinceDay(ProvinceDay provinceDay) {
        int count = provinceDayWriteMapper.insert(provinceDay);
        if (count == 0) {
            throw new MallException("添加省份日统计表失败，请重试");
        }
        return count;
    }

    /**
     * 根据statsId删除省份日统计表
     *
     * @param statsId statsId
     * @return
     */
    public Integer deleteProvinceDay(Long statsId) {
        if (StringUtils.isEmpty(statsId)) {
            throw new MallException("请选择要删除的数据");
        }
        int count = provinceDayWriteMapper.deleteByPrimaryKey(statsId);
        if (count == 0) {
            log.error("根据statsId：" + statsId + "删除省份日统计表失败");
            throw new MallException("删除省份日统计表失败,请重试");
        }
        return count;
    }

    /**
     * 根据statsId更新省份日统计表
     *
     * @param provinceDay
     * @return
     */
    public Integer updateProvinceDay(ProvinceDay provinceDay) {
        if (StringUtils.isEmpty(provinceDay.getStatsId())) {
            throw new MallException("请选择要修改的数据");
        }
        int count = provinceDayWriteMapper.updateByPrimaryKeySelective(provinceDay);
        if (count == 0) {
            log.error("根据statsId：" + provinceDay.getStatsId() + "更新省份日统计表失败");
            throw new MallException("更新省份日统计表失败,请重试");
        }
        return count;
    }

    /**
     * 根据statsId获取省份日统计表详情
     *
     * @param statsId statsId
     * @return
     */
    public ProvinceDay getProvinceDayByStatsId(Long statsId) {
        return provinceDayReadMapper.getByPrimaryKey(statsId);
    }

    /**
     * 根据条件获取省份日统计表列表
     *
     * @param example 查询条件信息
     * @param pager   分页信息
     * @return
     */
    public List<ProvinceDay> getProvinceDayList(ProvinceDayExample example, PagerInfo pager) {
        List<ProvinceDay> provinceDayList;
        if (pager != null) {
            pager.setRowsCount(provinceDayReadMapper.countByExample(example));
            provinceDayList = provinceDayReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            provinceDayList = provinceDayReadMapper.listByExample(example);
        }
        return provinceDayList;
    }

    /**
     * 根据条件获取省份统计
     *
     * @param example 查询条件信息
     * @return
     */
    public List<ProvinceBase> getProvinceList(ProvinceDayExample example) {
        return provinceDayReadMapper.getProvinceList(example);
    }

    /**
     * 根据条件获取省份趋势统计
     *
     * @param example 查询条件信息
     * @return
     */
    public List<SalesTrendVO> getProvinceTrendList(ProvinceDayExample example) {
        return provinceDayReadMapper.getProvinceTrendList(example);
    }

    /**
     * 根据条件获取各省份销售占比
     *
     * @param example 查询条件信息
     * @return
     */
    public List<ProvinceBase> getProvincePercentList(ProvinceDayExample example) {
        return provinceDayReadMapper.getProvincePercentList(example);
    }

    //region 地域概况报表导出

    /**
     * 地域概况报表导出
     *
     * @param request
     * @param response
     * @param example
     * @return
     */
    public boolean reportExport(HttpServletRequest request, HttpServletResponse response, ProvinceDayExample example) {
        List<ProvinceBase> provinceDayList = provinceDayReadMapper.getProvincePercentList(example);
        List<RegionReportVO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(provinceDayList)) {
            provinceDayList.forEach(provinceBase -> {
                list.add(new RegionReportVO(provinceBase));
            });
        }
        // 用于存放生成的excel文件名称
        List<File> fileNames = new ArrayList<>();
        // 每次导出的excel的文件名
        String fileNameS = "";
        // 将excel导出的文件位置
        String filePath = "/upload/";
        File files = new File(filePath);
        // 如果文件夹不存在则创建
        if (!files.exists() && !files.isDirectory()) {
            files.mkdirs();
        }

        //excel标题
        String titles = "省份编码,省份名称,支付金额,下单金额,支付订单数,下单数,新增会员数,新增店铺数,退单数,退单金额";
        String[] titleArray = titles.split(",");

        // 创建Excel文件,每个excel限制2000条数据,超过则打包zip
        int count = list.size();
        int max = 2000;
        int num = count % max;
        int num1;
        if (num == 0) {
            num1 = count / max;
        } else {
            num1 = count / max + 1;
        }

        try {
            if (list.size() <= max) {
                // 导出的excel的文件名
                fileNameS = "地域概况报表-" + ExcelUtil.getSystemDate() + "-" + list.size() + ".xls";

                //下载单个excle
                byte b[] = ExcelUtil.export("地域概况报表", titleArray, list);

                File f = new File(filePath + fileNameS);
                FileUtils.writeByteArrayToFile(f, b, true);

                // 下载
                FileDownloadUtils.setExcelHeadInfo(response, request, fileNameS);

                ServletOutputStream out = response.getOutputStream();

                String path = "/upload/" + fileNameS; //Excel在服务器上的路径

                File file = new File(path);

                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(4096);

                byte[] cache = new byte[4096];
                for (int offset = fis.read(cache); offset != -1; offset = fis.read(cache)) {
                    byteOutputStream.write(cache, 0, offset);
                }

                byte[] bt = byteOutputStream.toByteArray();

                out.write(bt);
                out.flush();
                out.close();
                fis.close();
                if (file.exists()) {
                    file.delete();
                }

            } else {
                for (int i = 1; i <= num1; i++) {
                    fileNameS = "地域概况报表-" + ExcelUtil.getSystemDate() + "-" + i + ".xls";

                    List<RegionReportVO> exportDatas = new ArrayList<>();
                    if (i == num1) {
                        for (int j = max * (i - 1); j < list.size(); j++) {
                            exportDatas.add(list.get(j));
                        }
                    } else {
                        for (int j = max * (i - 1); j < 2000 * i; j++) {
                            exportDatas.add(list.get(j));
                        }
                    }

                    //下载单个excle
                    byte b[] = ExcelUtil.export("地域概况报表", titleArray, exportDatas);

                    File f = new File(filePath + fileNameS);
                    FileUtils.writeByteArrayToFile(f, b, true);

                    fileNames.add(new File(filePath + fileNameS));
                }

                String zipName = "地域概况报表-" + ExcelUtil.getSystemDate() + ".zip";
                // 导出压缩文件的全路径
                String zipFilePath = filePath + zipName;
                System.out.println(zipFilePath);
                // 导出zip
                File zip = new File(zipFilePath);

                // 下载
                FileDownloadUtils.setZipDownLoadHeadInfo(response, request, zipName);

                // 将excel文件生成压缩文件
                File srcFile[] = new File[fileNames.size()];
                for (int j = 0, n1 = fileNames.size(); j < n1; j++) {
                    srcFile[j] = new File(String.valueOf(fileNames.get(j)));
                }
                FileDownloadUtils.ZipFiles(srcFile, zip);

                OutputStream outputStream = response.getOutputStream();
                InputStream inputStream = new FileInputStream(zipFilePath);
                byte[] buffer = new byte[8192];
                int i = -1;
                while ((i = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, i);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();

                FileDownloadUtils.deleteDir(new File(filePath));
            }

        } catch (Exception e) {
            try {
                if (!response.isCommitted()) {
                    response.setContentType("text/html;charset=utf-8");
                    response.setHeader("Content-Disposition", "");
                    String html = FileDownloadUtils.getErrorHtml("下载失败");
                    response.getOutputStream().write(html.getBytes(StandardCharsets.UTF_8));
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return true;
    }
    //endregion 地域概况报表导出
}