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.MemberDayReadMapper;
import com.slodon.b2b2c.dao.write.statistics.MemberDayWriteMapper;
import com.slodon.b2b2c.statistics.example.MemberDayExample;
import com.slodon.b2b2c.statistics.pojo.MemberDay;
import com.slodon.b2b2c.statistics.pojo.base.MemberBase;
import com.slodon.b2b2c.vo.statistics.MemberReportVO;
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 MemberDayModel {

    @Resource
    private MemberDayReadMapper memberDayReadMapper;
    @Resource
    private MemberDayWriteMapper memberDayWriteMapper;

    /**
     * 新增会员日统计表
     *
     * @param memberDay
     * @return
     */
    public Integer saveMemberDay(MemberDay memberDay) {
        int count = memberDayWriteMapper.insert(memberDay);
        if (count == 0) {
            throw new MallException("添加会员日统计表失败，请重试");
        }
        return count;
    }

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

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

    /**
     * 根据statsId获取会员日统计表详情
     *
     * @param statsId statsId
     * @return
     */
    public MemberDay getMemberDayByStatsId(Long statsId) {
        return memberDayReadMapper.getByPrimaryKey(statsId);
    }

    /**
     * 根据条件获取会员日统计表列表
     *
     * @param example 查询条件信息
     * @param pager   分页信息
     * @return
     */
    public List<MemberDay> getMemberDayList(MemberDayExample example, PagerInfo pager) {
        List<MemberDay> memberDayList;
        if (pager != null) {
            pager.setRowsCount(memberDayReadMapper.countByExample(example));
            memberDayList = memberDayReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            memberDayList = memberDayReadMapper.listByExample(example);
        }
        return memberDayList;
    }

    /**
     * 根据条件获取会员统计
     *
     * @param example 查询条件信息
     * @return
     */
    public List<MemberBase> getMemberList(MemberDayExample example, PagerInfo pager) {
        pager.setRowsCount(memberDayReadMapper.getMemberCount(example));
        return memberDayReadMapper.getMemberList(example, pager.getStart(), pager.getPageSize());
    }

    //region 会员报表导出

    /**
     * 会员报表导出
     *
     * @param request
     * @param response
     * @param example
     * @return
     */
    public boolean memberReportExport(HttpServletRequest request, HttpServletResponse response, MemberDayExample example) {
        List<MemberBase> memberList = memberDayReadMapper.getMemberList(example, null, null);
        List<MemberReportVO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(memberList)) {
            memberList.forEach(platformDay -> {
                list.add(new MemberReportVO(platformDay));
            });
        }
        // 用于存放生成的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<MemberReportVO> 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 会员报表导出
}