package com.liquidnet.client.admin.web.controller.zhengzai.tools;

import com.liquidnet.client.admin.common.core.controller.BaseController;
import com.liquidnet.client.admin.common.core.domain.AjaxResult;
import com.liquidnet.client.admin.common.utils.poi.ExcelUtil;
import com.liquidnet.client.admin.zhengzai.kylin.dto.*;
import com.liquidnet.client.admin.zhengzai.kylin.service.IExportService;
import com.liquidnet.service.kylin.dao.TestDao;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.ResponseBody;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Controller
@RequestMapping("tools/export")
public class ExportDataController extends BaseController {


    private static ExcelUtil<Object> excelUtil;
    @Autowired
    private IExportService exportService;

    private String prefix = "zhengzai/financial";

    @GetMapping()
    public String financial() {
        return prefix + "/export";
    }

    /**
     * 导出订单明细
     *
     * @param exportType
     * @param beginTime
     * @param endTime
     * @param showId
     * @return
     */
    @PostMapping("/export/orderInfo")
    @ResponseBody
    public AjaxResult exportOrderInfo(Integer exportType, String beginTime, String endTime, String showId) {
        if (null == exportType) {
            return error("导出类型有误！");
        }
        if (exportType == 1) {//按订单时间导出信息
            if (!timeIsNotNull(beginTime, endTime)) {
                return error("按时间类型导出，开始时间和结束时间不能为空！");
            }
            List<OrderDetailedExportVo> list = exportService.exportOrderByOrderTime(beginTime, endTime);
            if (list.size() > 0) {
                ExcelUtil<OrderDetailedExportVo> util = new ExcelUtil(OrderDetailedExportVo.class);
                return util.exportExcel(list, exportType + "");
            }
        } else if (exportType == 2) {//按演出时间导出信息
            if (!timeIsNotNull(beginTime, endTime)) {
                return error("按时间类型导出，开始时间和结束时间不能为空！");
            }
            List<OrderDetailedByShowDateExportVo> byShowTimeList = exportService.exportOrderByShowTime(beginTime, endTime);
            if (byShowTimeList.size() > 0) {
                ExcelUtil<OrderDetailedByShowDateExportVo> util = new ExcelUtil(OrderDetailedByShowDateExportVo.class);
                return util.exportExcel(byShowTimeList, exportType + "");
            }
        } else if (exportType == 3) {//按id导出信息
            if (!StringUtils.isNotBlank(showId)) {
                return error("演出id不能为空！");
            }
            List<OrderDetailedByShowIdExportVo> byShowIdList = exportService.exportOrderByShowId(showId);
            if (byShowIdList.size() > 0) {
                ExcelUtil<OrderDetailedByShowIdExportVo> util = new ExcelUtil(OrderDetailedByShowIdExportVo.class);
                return util.exportExcel(byShowIdList, exportType + "");
            }
        }
        return error("查无信息！");
    }

    private boolean timeIsNotNull(String beginTime, String endTime) {
        return StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime) ? true : false;
    }

    /**
     * test
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    @PostMapping("/export/test")
    @ResponseBody
    public AjaxResult test(String beginTime, String endTime, Integer state, Integer mailType) {
        if (!timeIsNotNull(beginTime, endTime)) {
            return error("开始时间和结束时间不能为空！");
        }
        List<TestDao> voList = exportService.test(beginTime, endTime, state ,mailType);
        Map<String, List<String>> map = new HashMap<>();
        int max = 0;
        //将数据保存到list中
        if (voList != null && voList.size() > 0) {
            for (TestDao te : voList) {
                String orderCode = te.getOrderCode();
                if (map.get(orderCode) == null) {
                    List<String> list = new ArrayList<>();
                    list.add(te.getOrderCode());
                    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());
                    max = max > list.size() ? max : list.size();
                    map.put(orderCode, list);
                }
                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());
                    max = max > list.size() ? max : list.size();
                    map.put(orderCode, list);
                }
            }
            exportexcel(map, "表名test01", max);
        }
        if (voList.size() == 0) {
            return error("查无信息");
        }
        return AjaxResult.success("ok!");
    }

    private void 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 = header.createCell(0);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("订单编号");

        cell = header.createCell(1);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("购买人手机号");
        cell = header.createCell(2);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("快递费");
        cell = header.createCell(3);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("平台券优惠券金额");
        cell = header.createCell(4);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("店铺券优惠金额");
        cell = header.createCell(5);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("收货人");
        cell = header.createCell(6);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("收货人电话");
        cell = header.createCell(7);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("快递地址");
        cell = header.createCell(8);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("支付方式");
        cell = header.createCell(9);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("支付时间");
        cell = header.createCell(10);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("下单时间");
        cell = header.createCell(11);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("快递公司");
        cell = header.createCell(12);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("物流单号");

        int n = 12;
        while (n <= max) {
            int z = n / 20 + 1;
            n++;
            cell = header.createCell(n);
            cell.setCellStyle(cellStyle);
            cell.setCellValue("商品id" + z);
            n++;
            cell = header.createCell(n);
            cell.setCellStyle(cellStyle);
            cell.setCellValue("商品名" + z);
            n++;
            cell = header.createCell(n);
            cell.setCellStyle(cellStyle);
            cell.setCellValue("一级分类" + z);
            n++;
            cell = header.createCell(n);
            cell.setCellStyle(cellStyle);
            cell.setCellValue("二级分类" + z);
            n++;
            cell = header.createCell(n);
            cell.setCellStyle(cellStyle);
            cell.setCellValue("款式" + z);
            n++;
            cell = header.createCell(n);
            cell.setCellStyle(cellStyle);
            cell.setCellValue("数量" + z);
            n++;
            cell = header.createCell(n);
            cell.setCellStyle(cellStyle);
            cell.setCellValue("单价" + z);
            n++;
            cell = header.createCell(n);
            cell.setCellStyle(cellStyle);
            cell.setCellValue("价格" + z);
        }
        int z = 1;
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String orderCode = entry.getKey();
            List<String> list = entry.getValue();
            XSSFRow content = sheet.createRow(z);
            content.createCell(0).setCellValue(orderCode);
            //获取员工
            for (int i = 0; i < list.size(); i++) {
                //创建单元格并设置值
                content.createCell(i + 1).setCellValue(list.get(i));
            }
            z++;
        }
        OutputStream fileOutputStream = null;
        try {
            ExcelUtil<TestDao> util = new ExcelUtil(TestDao.class);
            String filename = util.encodingFilename(name);
            //写入文件
            fileOutputStream = new FileOutputStream(util.getAbsoluteFile(filename));
            workbook.write(fileOutputStream);
            System.out.println("导出成功！");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("导出失败！");
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导出会员订单
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    @PostMapping("/export/memberOrder")
    @ResponseBody
    public AjaxResult exportMemberOrder(String beginTime, String endTime) {
        if (!timeIsNotNull(beginTime, endTime)) {
            return error("开始时间和结束时间不能为空！");
        }
        List<OrderMemberExportVo> list = exportService.exportMemberOrder(beginTime, endTime);
        if (list.size() == 0) {
            return error("查无信息");
        }
        ExcelUtil<OrderMemberExportVo> util = new ExcelUtil(OrderMemberExportVo.class);
        return util.exportExcel(list, "会员订单");
    }

    /**
     * 导出商品订单
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    @PostMapping("/export/commodityOrder")
    @ResponseBody
    public AjaxResult exportCommodityOrder(String beginTime, String endTime) {
        if (!timeIsNotNull(beginTime, endTime)) {
            return error("开始时间和结束时间不能为空！");
        }
        List<OrderCommodityExportVo> list = exportService.exportCommodityOrder(beginTime, endTime);
        if (list.size() == 0) {
            return error("查无信息");
        }
        ExcelUtil<OrderCommodityExportVo> util = new ExcelUtil(OrderCommodityExportVo.class);
        return util.exportExcel(list, "商品订单");
    }

}
