package com.winsun.service;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.bean.ExportExcel;
import com.winsun.bean.Order;
import com.winsun.constant.FilePath;
import com.winsun.mapper.ExportExcelMapper;
import com.winsun.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 导出
 * @Author: chancy
 * @Date: 2020/3/16 18:26
 */
@Slf4j
@Service
public class ExportService extends BaseController {

    private OrderMapper orderMapper;

    private ExportExcelMapper exportExcelMapper;

    @Autowired
    public ExportService(OrderMapper orderMapper,ExportExcelMapper exportExcelMapper){
        this.orderMapper = orderMapper;
        this.exportExcelMapper = exportExcelMapper;
    }

    public void ExportOrderView(Map<String, Object> map) {
        String createTimeStart = "";
        if(map.containsKey("createTimeStart")){
            createTimeStart = map.get("createTimeStart").toString();
        }
        String createTimeEnd = "";
        if(map.containsKey("createTimeEnd")){
            createTimeEnd = map.get("createTimeEnd").toString();
        }
        String successTimeStart = "";
        if(map.containsKey("successTimeStart")){
            successTimeStart = map.get("successTimeStart").toString();
        }
        String successTimeEnd =  "";
        if(map.containsKey("successTimeEnd")){
            successTimeEnd =  map.get("successTimeEnd").toString();
        }
        String userType = "";
        if(map.containsKey("userType")){
            userType = map.get("userType").toString();
        }
        String orderNumber = "";
        if(map.containsKey("orderNumber")){
            orderNumber = map.get("orderNumber").toString();
        }
        String customerName = "";
        if(map.containsKey("customerName")){
            customerName = map.get("customerName").toString();
        }
        String businessNumber = "";
        if(map.containsKey("businessNumber")){
            businessNumber = map.get("businessNumber").toString();
        }
        String contactNumber = "";
        if(map.containsKey("contactNumber")){
            contactNumber = map.get("contactNumber").toString();
        }
        String hehuorenSchool = "";
        if(map.containsKey("hehuorenSchool")){
            hehuorenSchool = map.get("hehuorenSchool").toString();
        }
        String hehuorenName = "";
        if(map.containsKey("hehuorenName")){
            hehuorenName = map.get("hehuorenName").toString();
        }
        String orderStatus = "";
        if(map.containsKey("orderStatus")){
            orderStatus = map.get("orderStatus").toString();
        }
        String hehuorenArea = "";
        if (map.containsKey("hehuorenArea")) {
            hehuorenArea = map.get("hehuorenArea").toString();
        }
        boolean isYzk = false;
        if (map.containsKey("isYzk")) {
            isYzk = true;
        }


        EntityWrapper<Order> wrapper = new EntityWrapper();
        wrapper.ge(StringUtils.isNotBlank(createTimeStart), "create_time", createTimeStart);
        wrapper.le(StringUtils.isNotBlank(createTimeEnd), "create_time", createTimeEnd);
        wrapper.ge(StringUtils.isNotBlank(successTimeStart), "success_time", successTimeStart);
        wrapper.le(StringUtils.isNotBlank(successTimeEnd), "success_time", successTimeEnd);
        wrapper.eq(StringUtils.isNotBlank(userType), "user_type", userType);
        wrapper.eq(StringUtils.isNotBlank(orderNumber), "order_number", orderNumber);
        //wrapper.eq(StringUtils.isNotBlank(kapin), "kapin", kapin);
        wrapper.isNotNull(isYzk, "order_id");
        wrapper.eq(StringUtils.isNotBlank(hehuorenArea), "hehuoren_area", hehuorenArea);
        wrapper.eq(StringUtils.isNotBlank(customerName), "customer_name", customerName);
        wrapper.eq(StringUtils.isNotBlank(businessNumber), "business_number", businessNumber);
        wrapper.eq(StringUtils.isNotBlank(contactNumber), "contact_number", contactNumber);
        wrapper.eq(StringUtils.isNotBlank(hehuorenSchool), "hehuoren_school", hehuorenSchool);
        wrapper.like(StringUtils.isNotBlank(hehuorenName), "hehuoren_name", hehuorenName, SqlLike.DEFAULT);
        wrapper.eq(StringUtils.isNotBlank(orderStatus), "order_status", orderStatus);
        List<Map<String, Object>> Orders = orderMapper.downloadOrder(wrapper);
        List<String> tops = new ArrayList<>();
        tops.add("客户姓名");
        tops.add("订单编号");
        tops.add("联系号码");
        tops.add("办理号码");
        tops.add("办理套餐");
        tops.add("合伙人姓名");
        tops.add("合伙人学校");
        tops.add("合伙人手机");
        tops.add("现有套餐");
        tops.add("升级套餐");
        tops.add("订单状态");
        tops.add("订单类型");
        tops.add("地区");
        tops.add("地址");
        tops.add("学生证审核状态");
        List<String> columns = new ArrayList<>();
        columns.add("customer_name");
        columns.add("order_number");
        columns.add("contact_number");
        columns.add("business_number");
        columns.add("business_package");
        columns.add("hehuoren_name");
        columns.add("hehuoren_school");
        columns.add("hehuoren_phone");
        columns.add("package_id");
        columns.add("business_package");
        columns.add("order_status");
        columns.add("user_type");
        columns.add("site");
        columns.add("address");
        columns.add("student_card_checkStatus");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String formatPath = format.format(new Date());
        String filePath = FilePath.IMPORTPATH.getValue()+formatPath;
        String fileName = "订单"+new Date().getTime()+".xls";
        String filePath1 = FilePath.IMPORTPATH.getValue()+formatPath+"/"+fileName;
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileOutputStream os = null;
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook();
            os = new FileOutputStream(filePath1);
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("订单清单");
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            //设置列宽度
            sheet.setColumnWidth(1, 6500);
            sheet.setColumnWidth(2, 4000);
            sheet.setColumnWidth(3, 4000);
            sheet.setColumnWidth(4, 4000);
            sheet.setColumnWidth(5, 7000);
            sheet.setColumnWidth(6, 7000);
            sheet.setColumnWidth(7, 4000);
            sheet.setColumnWidth(8, 4000);
            sheet.setColumnWidth(9, 6500);
            sheet.setColumnWidth(10, 6500);
            sheet.setColumnWidth(11, 6500);
            sheet.setColumnWidth(12, 6500);
            sheet.setColumnWidth(13, 6500);
            sheet.setColumnWidth(14, 6500);
            sheet.setColumnWidth(15, 6500);
            //第一行字段名称
            tops.forEach(column -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(column);
            });
            //数据
            int rowIndex = row.getRowNum();
            for (Map<String, Object> maps : Orders) {
                final XSSFRow rowdata = sheet.createRow(++rowIndex);
                for (String column : columns) {
                    XSSFCell cell = rowdata.createCell(Math.max(rowdata.getLastCellNum(), 0));
                    if (maps.get(column) != null) {
                        cell.setCellValue(maps.get(column).toString());
                    }
                }
            }
            workbook.write(os);
            ExportExcel exportExcel = new ExportExcel();
            exportExcel.setCreateTime(new Date());
            exportExcel.setCreateUser(Integer.parseInt(map.get("userId").toString()));
            exportExcel.setCreateName(map.get("userName").toString());
            exportExcel.setExportUrl(filePath1);
            exportExcel.setFileName(fileName);
            exportExcelMapper.insert(exportExcel);
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            if (workbook != null) {
                try{
                    workbook.close();
                }catch(Exception e) {}
            }
            if (os != null) {
                try{
                    os.close();
                }catch(Exception e) {}
            }
        }
    }
}
