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.bean.School;
import com.winsun.bean.Schools;
import com.winsun.constant.DeliveryType;
import com.winsun.constant.ExamineType;
import com.winsun.constant.FilePath;
import com.winsun.constant.UserType;
import com.winsun.mapper.ExportExcelMapper;
import com.winsun.mapper.OrderMapper;
import com.winsun.mapper.SchoolMapper;
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.*;

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

    private OrderMapper orderMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    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 kuaidiTimeStart = "";
        if(map.containsKey("kuaidiTimeStart")){
            kuaidiTimeStart = map.get("kuaidiTimeStart").toString();
        }
        String kuaidiTimeEnd =  "";
        if(map.containsKey("kuaidiTimeEnd")) {
            kuaidiTimeEnd = map.get("kuaidiTimeEnd").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();
        }
        String businessPackage = "";
        if (map.containsKey("businessPackage")) {
            businessPackage = map.get("businessPackage").toString();
        }
        boolean isYzk = false;
        if (map.containsKey("isYzk")) {
            isYzk = true;
        }
        String isDelivery = "";
        if (map.containsKey("isDelivery")) {
            isDelivery = map.get("isDelivery").toString();
        }

        Integer userId = null;
        if (map.containsKey("userId")){
            userId = Integer.parseInt(map.get("userId").toString());
        }

        List<Integer> userIds = (List<Integer>) map.get("userIds");

        EntityWrapper<Order> wrapper = new EntityWrapper();
        wrapper.setSqlSelect("customer_name, business_number, order_status, create_time, " +
                "hehuoren_id,hehuoren_area, hehuoren_school, hehuoren_name, hehuoren_phone, " +
                "supervisor_name, user_type, kapin, business_package, contact_number, order_number, xb_order_id, order_id, site, address, " +
                "is_delivery, company, kuaidi_order, business_iccid, kuaidi_time, success_time, userSchool, student_card_check_status, " +
                "parent_name, student_number, class_number");
        wrapper.notIn( "user_type", "3,5,9,10");
        if (userIds.size() != 0) {
            wrapper.in("hehuoren_id", userIds);
        }
        wrapper.isNull("kd_order_id");
        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.ge(StringUtils.isNotBlank(kuaidiTimeStart), "kuaidi_time", kuaidiTimeStart);
        wrapper.le(StringUtils.isNotBlank(kuaidiTimeEnd), "kuaidi_time", kuaidiTimeEnd);
        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.like(StringUtils.isNotBlank(businessPackage), "business_package", businessPackage, SqlLike.DEFAULT);
        wrapper.eq(StringUtils.isNotBlank(orderStatus), "order_status", orderStatus);
        wrapper.eq(StringUtils.isNotBlank(isDelivery), "is_delivery", isDelivery);
        wrapper.orderBy("create_time",false);
        List<Map<String, Object>> Orders = orderMapper.selectMaps(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("小白卡单号");
        tops.add("预制卡单号");
        tops.add("收货地区");
        tops.add("详细地址");
        tops.add("配送方式");
        tops.add("快递公司");
        tops.add("快递单号");
        tops.add("白卡ICCID");
        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("business_number");
        columns.add("order_status");
        columns.add("create_time");
        columns.add("hehuoren_area");
        columns.add("hehuoren_school");
        columns.add("hehuoren_name");
        columns.add("hehuoren_phone");
        columns.add("supervisor_name");
        columns.add("user_type");
        columns.add("kapin");
        columns.add("business_package");
        columns.add("contact_number");
        columns.add("order_number");
        columns.add("xb_order_id");
        columns.add("order_id");
        columns.add("site");
        columns.add("address");
        columns.add("is_delivery");
        columns.add("company");
        columns.add("kuaidi_order");
        columns.add("business_iccid");
        columns.add("kuaidi_time");
        columns.add("success_time");
        columns.add("userSchool");
        columns.add("student_card_check_status");
        columns.add("parent_name");
        columns.add("student_number");
        columns.add("class_number");

        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);
            sheet.setColumnWidth(16, 6500);
            sheet.setColumnWidth(17, 6500);
            sheet.setColumnWidth(18, 6500);
            sheet.setColumnWidth(19, 4000);
            sheet.setColumnWidth(20, 6500);
            sheet.setColumnWidth(21, 6500);
            sheet.setColumnWidth(22, 6500);
            sheet.setColumnWidth(23, 6500);
            sheet.setColumnWidth(24, 6500);
            sheet.setColumnWidth(25, 6500);
            sheet.setColumnWidth(26, 6500);
            sheet.setColumnWidth(27, 6500);
            sheet.setColumnWidth(28, 6500);
            sheet.setColumnWidth(29, 6500);
            //第一行字段名称
            tops.forEach(column -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(column);
            });
            //数据
            School school = new School();
            List<Schools> school1 = schoolMapper.selectHhrSchool();
            HashMap<String, Schools> schools = new HashMap<>();
            for (Schools school2 : school1) {
                schools.put(school2.getUserId(), school2);
            }
            int rowIndex = row.getRowNum();
            for (Map<String, Object> maps : Orders) {
                /*String schoolId = schoolMapper.selectSchoolIdByUserId(maps.get("hehuoren_id").toString());
                school = schoolMapper.selectById(schoolId);*/
                Schools sc = schools.get(maps.get("hehuoren_id").toString());
                maps.put("lz_user",sc.getLzUser());
                maps.put("lzgh",sc.getLzgh());
                String userTypeSrt = UserType.findById(maps.get("user_type").toString()).getName();
                maps.put("user_type",userTypeSrt);
                if(maps.get("is_delivery") != null && StringUtils.isNotBlank(maps.get("is_delivery").toString())){
                    String isDeliveryStr = DeliveryType.findById(maps.get("is_delivery").toString()).getName();
                    maps.put("is_delivery",isDeliveryStr);
                }
                if(maps.get("student_card_check_status") != null && StringUtils.isNotBlank(maps.get("student_card_check_status").toString())) {
                    String studentCardCheckStatusStr = ExamineType.findById(maps.get("student_card_check_status").toString()).getName();
                    maps.put("student_card_check_status",studentCardCheckStatusStr);
                }

                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) {}
            }
        }
    }
}
