package com.liquidnet.client.admin.zhengzai.goblin.service.impl;

import com.liquidnet.client.admin.common.core.domain.AjaxResult;
import com.liquidnet.client.admin.common.exception.BusinessException;
import com.liquidnet.client.admin.common.utils.poi.ExcelUtil;
import com.liquidnet.client.admin.zhengzai.goblin.service.IGoblinExportService;
import com.liquidnet.service.goblin.dto.MallOrdertDao;
import com.liquidnet.service.goblin.mapper.GoblinStoreOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class GoblinExportServiceImpl implements IGoblinExportService {

    @Autowired
    GoblinStoreOrderMapper goblinStoreOrderMapper;

    @Override
    public AjaxResult exportMallOrder(String beginTime, String endTime, String state, Integer mailType) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date beginDate = sdf.parse(beginTime);
            Date endDate = sdf.parse(endTime);
            List<String> states = null;
            if (StringUtils.isNotBlank(state)) {
                states = Arrays.asList(state.split(","));
            }
            List<MallOrdertDao> voList = goblinStoreOrderMapper.exportMallOrder(beginDate, endDate, states ,mailType);
            AjaxResult ajaxResult = null;
            Map<String, List<String>> map = new HashMap<>();
            int max = 0;
            //将数据保存到list中
            if (voList != null && voList.size() > 0) {
                for (MallOrdertDao te : voList) {
                    String orderCode = te.getOrderCode();
                    if (map.get(orderCode) == null) {
                        List<String> list = new ArrayList<>();
                        list.add(te.getOrderCode());
                        list.add(te.getUserMobile());
                        list.add(te.getPriceExpress());
                        list.add(te.getPriceCoupon());
                        list.add(te.getStorePriceCoupon());
                        list.add(te.getExpressContacts());
                        list.add(te.getExpressPhone());
                        list.add(te.getExpressDetailAddress());
                        list.add(te.getPayType());
                        list.add(te.getPayTime());
                        list.add(te.getCreatedAt());
                        list.add(te.getLogisticsCompany());
                        list.add(te.getMailNo());
                        list.add(te.getSpuId());
                        list.add(te.getName());
                        list.add(te.getCate1Name());
                        list.add(te.getCate2Name());
                        list.add(te.getSkuName());
                        list.add(te.getNum());
                        list.add(te.getSkuPrice());
                        list.add(te.getSkuPriceActual());
                        list.add(te.getOrderSkuId());
                        max = Math.max(max, list.size());
                        map.put(orderCode, list);
                        continue;
                    }
                    if (map.get(orderCode) != null) {
                        List<String> list = map.get(orderCode);
                        list.add(te.getSpuId());
                        list.add(te.getName());
                        list.add(te.getCate1Name());
                        list.add(te.getCate2Name());
                        list.add(te.getSkuName());
                        list.add(te.getNum());
                        list.add(te.getSkuPrice());
                        list.add(te.getSkuPriceActual());
                        list.add(te.getOrderSkuId());
                        max = Math.max(max, list.size());
                        map.put(orderCode, list);
                    }
                }
                return exportexcel(map, "order", max);
            }
            return AjaxResult.error("查无信息！");
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BusinessException("导出Excel失败，请联系网站管理员！");
        }
    }

    //导出Excel
    private AjaxResult exportexcel(Map<String, List<String>> map, String name, int max) {
        //实例化XSSFWorkbook对象，相当于新建一个Excel文件
        XSSFWorkbook workbook = new XSSFWorkbook();
        //根据XSSFWorkbook获取Sheet
        XSSFSheet sheet = workbook.createSheet();
        //添加一行作为表格头
        XSSFRow header = sheet.createRow(0);

        //创建表格样式
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        //cellStyle.setAlignment(CellStyle.ALIGN_CENTER);//内容居中显示

        //创建头部表格
        XSSFCell cell = null;
        int index = 0;
        //固定表头
        List<String> fixedCells = fixedCells();
        for (String cname : fixedCells) {
            cell = header.createCell(index);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(cname);
            index++;
        }

        int n = 13; //固定表头13个
        int indext = 0;
        //追加表头
        List<String> cells = appendCells();
        while (n < max) {
            indext++;
            for (String cname : cells) {
                cell = header.createCell(n);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(cname + indext);
                n++;
            }
        }
        int z = 1;
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            List<String> list = entry.getValue();
            //获取每行
            XSSFRow content = sheet.createRow(z);
            for (int i = 0; i < list.size(); i++) {
                //创建单元格并设置值
                content.createCell(i).setCellValue(list.get(i));
            }
            z++;
        }
        OutputStream fileOutputStream = null;
        try {
            ExcelUtil<MallOrdertDao> util = new ExcelUtil(MallOrdertDao.class);
            String filename = util.encodingFilename(name);
            //写入文件
            fileOutputStream = new FileOutputStream(util.getAbsoluteFile(filename));
            workbook.write(fileOutputStream);
            return AjaxResult.success("导出成功！",filename);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("导出Excel失败，请联系网站管理员！");
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //固定表头
    private List<String> fixedCells() {
        List<String> cells = new ArrayList<>();
        cells.add("订单编号");
        cells.add("购买人手机号");
        cells.add("快递费");
        cells.add("平台券优惠券金额");
        cells.add("店铺券优惠金额");
        cells.add("收货人");
        cells.add("收货人电话");
        cells.add("快递地址");
        cells.add("支付方式");
        cells.add("支付时间");
        cells.add("下单时间");
        cells.add("快递公司");
        cells.add("物流单号");
        return cells;
    }

    //追加表头
    private List<String> appendCells() {
        List<String> cells = new ArrayList<>();
        cells.add("商品id");
        cells.add("商品名");
        cells.add("一级分类");
        cells.add("二级分类");
        cells.add("款式");
        cells.add("数量");
        cells.add("单价");
        cells.add("价格");
        cells.add("订单skuId");
        return cells;
    }

}
