package com.winsun.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
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.bean.Order;
import com.winsun.bean.YrymReport;
import com.winsun.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: chenhaojian
 * @Date: 2021/3/3 10:33
 */
@Slf4j
@RestController
@RequestMapping("/orderConversion")
public class OrderConversionController extends BaseController {

    @Autowired
    private OrderMapper orderMapper;

    // 获取订单通报数据
    // conversionType：
    //       00：移动通报学校
    //       01：移动通报县份
    //       10：宽带通报学校
    //       11：宽带通报学校
//    @RequestMapping(value = "getOrderConversionInfo",method = RequestMethod.POST)
    @Permission(menuname = "获取订单通报数据", value = "getOrderConversionInfo", method = RequestMethod.POST)
    public ResponseData<List<Map<String,Object>>> getOrderConversionInfo(@RequestParam("startTime")String startTime,
                                               @RequestParam("endTime")String endTime,
                                               @RequestParam("conversionType")String conversionType){
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "县分管理员（订单）"))) {
            ResponseData.error("无权限查询订单");
        }
        List<Map<String,Object>> list = null;
        if("".equals(startTime)&&"".equals(endTime)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 暂时计算2019年6月1号开始数据
            startTime = "2019-06-01";
            endTime = sdf.format(new Date());
        }
        try{
            switch (conversionType){
                case "00":
                    list = orderMapper.orderConversionXX(startTime,endTime);
                    break;
                case "01":
                    list = orderMapper.orderConversionXF(startTime,endTime);
                    break;
                case "10":
                    list = orderMapper.kdOrderConversionXX(startTime,endTime);
                    break;
                case "11":
                    list = orderMapper.kdOrderConversionXF(startTime,endTime);
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return ResponseData.success(list,"查询成功！");
    }
    // 下载订单通报数据
    // conversionType：
    //       00：移动通报学校
    //       01：移动通报县份
    //       10：宽带通报学校
    //       11：宽带通报学校
//    @RequestMapping(value = "getOrderConversionInfo",method = RequestMethod.POST)
    @Permission(menuname = "下载订单通报数据", value = "outOrderConversionInfo", method = RequestMethod.POST)
    public void outOrderConversionInfo(HttpServletResponse response,@RequestParam("startTime")String startTime,
                                                                         @RequestParam("endTime")String endTime,
                                                                         @RequestParam("conversionType")String conversionType){
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "县分管理员（订单）"))) {
            ResponseData.error("无权限查询订单");
        }
        List<Map<String,Object>> list = null;
        if("".equals(startTime)&&"".equals(endTime)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 暂时计算2019年6月1号开始数据
            startTime = "2019-06-01";
            endTime = sdf.format(new Date());
        }
        try{
            switch (conversionType){
                case "00":
                    list = orderMapper.orderConversionXX(startTime,endTime);
                    downloadHhrOrder(response,list,"/static/一人一码移动通报（学校）模板.xlsx");
                    break;
                case "01":
                    list = orderMapper.orderConversionXF(startTime,endTime);
                    downloadHhrOrder(response,list,"/static/一人一码移动通报（县份）模板.xlsx");
                    break;
                case "10":
                    list = orderMapper.kdOrderConversionXX(startTime,endTime);
                    downloadHhrOrder(response,list,"/static/一人一码宽带通报（学校）模板.xlsx");
                    break;
                case "11":
                    list = orderMapper.kdOrderConversionXF(startTime,endTime);
                    downloadHhrOrder(response,list,"/static/一人一码宽带通报（县份）模板.xlsx");
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    // excelUrl："/static/一人一码统计报表模板.xlsx"
    public void downloadHhrOrder(HttpServletResponse response,List<Map<String,Object>> list,String excelUrl){
        InputStream in = null;
        ExcelWriter excelWriter = null;
        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //防止中文乱码
            String fileName = URLEncoder.encode("一人一码订单通报", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            in = this.getClass().getResourceAsStream(excelUrl);
            outputStream = response.getOutputStream();
            excelWriter = EasyExcel.write(outputStream).withTemplate(in).excelType(ExcelTypeEnum.XLSX).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(list, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            LocalDate nowTime = LocalDate.now();
            map.put("month", nowTime.getMonthValue());
            map.put("date", nowTime.getDayOfMonth());
            excelWriter.fill(map, writeSheet);
            excelWriter.finish();
        } catch (Exception e) {
            log.error("一人一码下载文件失败", e.getMessage());
            e.printStackTrace();
        } finally {
            //关闭资源
            if (excelWriter != null) {
                try {
                    excelWriter.finish();
                }catch(Exception e) {
                }
            }
            if (outputStream != null) {
                try{
                    outputStream.flush();
                }catch(Exception e) {
                }
            }
            if (in != null) {
                try{
                    in.close();
                }catch(Exception e) {
                }
            }
        }
    }

}
