package com.winsun.controller;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.auth.core.util.IOUtils;
import com.winsun.bean.OrderView;
import com.winsun.constant.OrderStatus;
import com.winsun.mapper.OrderViewMapper;
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.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 宽带订单管理
 * @Author: chancy
 * @Date: 2020/2/12 17:26
 */
@Slf4j
@RestController
@RequestMapping("/orderView")
public class OrderViewController extends BaseController {

    private static OrderViewMapper orderViewMapper;

    @Autowired
    public OrderViewController(OrderViewMapper orderViewMapper) {
        OrderViewController.orderViewMapper = orderViewMapper;
    }

    /**
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param orderseq 订单号码
     * @param orderUniversityName 学校
     * @param status 状态
     * @param ordername  姓名
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Permission(menuname = "查询宽带订单（列表）", value = "list", method = RequestMethod.POST)
    public ResponseData<Page<OrderView>> listOrderView(@RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime,
                                                            @RequestParam("orderseq") String orderseq, @RequestParam("orderUniversityName") String orderUniversityName,
                                                            @RequestParam("status") String status, @RequestParam("ordername") String ordername,
                                                            @RequestParam(name = "pageNo") int pageIndex, @RequestParam(name = "pageSize") int pageSize) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        String dateFormat = "YYYY-MM-DD";
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            startTime = startTime.substring(0, dateFormat.length()) + " 00:00:00";
            endTime = endTime.substring(0, dateFormat.length()) + " 23:59:59";
        } else {
            startTime = null;
            endTime = null;
        }
        String state=null;
        if(StringUtils.isNotBlank(status)){
            state = OrderStatus.findById(status).getId();
        }
        Wrapper<OrderView> wrapper = new EntityWrapper();
        wrapper.like(StringUtils.isNotBlank(orderseq), "orderSeq", orderseq, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(ordername), "orderName", ordername, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(orderUniversityName), "order_university_name", orderUniversityName, SqlLike.DEFAULT);
        wrapper.eq(StringUtils.isNotBlank(status), "status",state);
        wrapper.ge(StringUtils.isNotBlank(startTime),"orderDate",startTime);
        wrapper.le(StringUtils.isNotBlank(endTime),"orderDate",endTime);
        Page<OrderView> page = new Page<>(pageIndex, pageSize);
        List<OrderView> OrderViews = orderViewMapper.selectPage(page, wrapper);
        page.setRecords(OrderViews);
        return ResponseData.success(page, "查询成功！");
    }

    @Permission(menuname = "导出宽带订单", value = "download", method = RequestMethod.POST)
    public void downloadOrderView(@RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime,
                                                       @RequestParam("orderseq") String orderseq, @RequestParam("orderUniversityName") String orderUniversityName,
                                                       @RequestParam("status") String status, @RequestParam("ordername") String ordername) {
        String dateFormat = "YYYY-MM-DD";
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            startTime = startTime.substring(0, dateFormat.length()) + " 00:00:00";
            endTime = endTime.substring(0, dateFormat.length()) + " 23:59:59";
        } else {
            startTime = null;
            endTime = null;
        }
        String state=null;
        if(StringUtils.isNotBlank(status)){
            state = OrderStatus.findById(status).getId();
        }
        Wrapper<OrderView> wrapper = new EntityWrapper();
        wrapper.like(StringUtils.isNotBlank(orderseq), "orderSeq", orderseq, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(ordername), "orderName", ordername, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(orderUniversityName), "order_university_name", orderUniversityName, SqlLike.DEFAULT);
        wrapper.eq(StringUtils.isNotBlank(status), "status",state);
        wrapper.ge(StringUtils.isNotBlank(startTime),"orderDate",startTime);
        wrapper.le(StringUtils.isNotBlank(endTime),"orderDate",endTime);
        List<Map<String, Object>> OrderViews = orderViewMapper.downloadOrderView(wrapper);
       List<String> tops = new ArrayList<>();
        tops.add("订单id");
        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("智能平台订单号");
        List<String> columns = new ArrayList<>();
        columns.add("order_id");
        columns.add("orderSeq");
        columns.add("productName");
        columns.add("webOrderAmount");
        columns.add("order_set_meal");
        columns.add("order_university_name");
        columns.add("order_region");
        columns.add("orderName");
        columns.add("orderPhone");
        columns.add("status");
        columns.add("order_customer_remarks");
        columns.add("orderDate");
        columns.add("ipay");
        columns.add("payType");
        columns.add("order_payment_time");
        columns.add("orderReqtranSeq");
        columns.add("customeRid");
        columns.add("uptranseq");
        columns.add("orderSeqTHD");
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("宽带订单清单");
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            //设置列宽度
            sheet.setColumnWidth(1, 6500);
            sheet.setColumnWidth(2, 6500);
            sheet.setColumnWidth(5, 7000);
            sheet.setColumnWidth(8, 4000);
            sheet.setColumnWidth(10, 6500);
            sheet.setColumnWidth(11, 6500);
            sheet.setColumnWidth(14, 6500);
            sheet.setColumnWidth(15, 7000);
            sheet.setColumnWidth(17, 7500);
            sheet.setColumnWidth(18, 600);
            //第一行字段名称
            tops.forEach(column -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(column);
            });
            //数据
            int rowIndex = row.getRowNum();
            for (Map<String, Object> maps: OrderViews) {
                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());
                    }
                }
            }

            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
    }
}
