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.BroadBandOrder;
import com.winsun.bean.OrderView;
import com.winsun.constant.OrderStatus;
import com.winsun.mapper.OrderMapper;
import com.winsun.mapper.OrderViewMapper;
import com.winsun.service.IHhrUserService;
import com.winsun.utils.ExcelTreeNodeHelper;
import com.winsun.utils.ExportExcel;
import com.winsun.utils.TreeNode;
import com.winsun.utils.TreeNodeData;
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.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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 {

    @Autowired
    private OrderViewMapper orderViewMapper;

    @Autowired
    private  OrderMapper orderMapper;

    @Autowired
    private IHhrUserService hhrUserService;

    /**
     * @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) {
        int i = 19;
        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 ResponseData<String> downloadOrderView(BroadBandOrder broadBandOrder){
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "系统管理员",  "县分管理员（订单）", "修改身份证", "合伙人"))) {
            return ResponseData.error("无权限查询订单");
        }

        List<Integer> userIds = hhrUserService.getUserIds(user.getId(), user.getRoleNames());
        if (userIds.size() != 0) {
            broadBandOrder.setHehuorenIds(userIds);
        };
        List<Map<String, Object>> broadBandOrders = orderMapper.selectBroadBandOrderList2(broadBandOrder);
        System.out.println(broadBandOrders.size());
        try {
            TreeNode treeNode = TreeNodeData.getBroadbandOrder("宽带订单清单");
            XSSFWorkbook workbook = ExcelTreeNodeHelper.getWorkbook(treeNode, broadBandOrders);
            ExportExcel.toDownLoad(workbook, getHttpServletRequest(), getHttpServletResponse(), "宽带订单清单");
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
            return ResponseData.error("导出失败");
        }
        return ResponseData.success("导出成功");
    }

}
