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.util.IOUtils;
import com.winsun.bean.HhrUser;
import com.winsun.bean.SalesOrder;
import com.winsun.bean.SysUser;
import com.winsun.mapper.HhrUserMapper;
import com.winsun.mapper.SalesOrderMapper;
import com.winsun.mapper.SchoolMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.utils.ExcelDealUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.text.SimpleDateFormat;
import java.util.*;

/**
 * 学子公司销量统计
 * @Author: pxl
 * @create 2020/5/18 18:04
 */
@Slf4j
@RestController
@RequestMapping("/saleCensus")
public class SaleCensusController extends BaseController{

    /**
     * 导入
     */
    private static final int HEADER_NUM = -1;
    private static final int SHEET_INDEX = 0;

	private static SalesOrderMapper salesOrderMapper;
	private static SysUserMapper sysUserMapper;
	private static SchoolMapper schoolMapper;
	private static HhrUserMapper hhrUserMapper;

	private List<Map<String, Object>> exportList = new ArrayList<Map<String,Object>>();
	private SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	public SaleCensusController(SalesOrderMapper salesOrderMapper, SysUserMapper sysUserMapper,
                                SchoolMapper schoolMapper, HhrUserMapper hhrUserMapper) {
		SaleCensusController.salesOrderMapper = salesOrderMapper;
		SaleCensusController.sysUserMapper = sysUserMapper;
		SaleCensusController.schoolMapper = schoolMapper;
		SaleCensusController.hhrUserMapper = hhrUserMapper;
	}

	@Permission(menuname = "获取学子公司销量统计列表", value ="/list", method = RequestMethod.POST)
	public ResponseData<Page<Map<String,Object>>> getList(
			@RequestParam("name") String name,@RequestParam("account") String account,
			@RequestParam("salesSubst") String salesSubst,@RequestParam("salesSchool") String salesSchool,
			@RequestParam("activateTime") String activateTime,@RequestParam("leader") String leader,
			@RequestParam("position") String position,
			@RequestParam(name = "pageNo", required = false) int pageNo,
			@RequestParam(name = "pageSize", required = false) int pageSize){
		Page<Map<String,Object>> page = new Page<>(pageNo, pageSize);
		List<Map<String,Object>> dataList0 = new LinkedList<>();

		Wrapper<SalesOrder> wrapper = new EntityWrapper();
		wrapper.like(StringUtils.isNotBlank(name), "name", name.trim(), SqlLike.DEFAULT);
		wrapper.eq(StringUtils.isNotBlank(account), "account", account.trim());
		wrapper.eq(StringUtils.isNotBlank(salesSubst), "sales_subst", salesSubst.trim());
		wrapper.eq(StringUtils.isNotBlank(salesSchool), "sales_school", salesSchool.trim());
		wrapper.ge("recently_amount", 50);
		wrapper.eq( "del_flag", 0);
		if(StringUtils.isNotBlank(activateTime)){
			String[] months = activateTime.split("\\,");
			if(!activateTime.equals(",") && StringUtils.isNotEmpty(activateTime)){
				String m1 = months[0].substring(0,7);
				String month1 = m1.substring(0,4) + m1.substring(5);
				String m2 = months[1].substring(0,7);
				String month2 = m2.substring(0,4) + m2.substring(5);
				wrapper.between("activate_time",month1,month2);
				/*wrapper.ge(StringUtils.isNotBlank(month1),"activate_time",month1);
				wrapper.le(StringUtils.isNotBlank(month2),"activate_time",month2);*/
			}
		}
		List<SalesOrder> salesOrderList = salesOrderMapper.selectList(wrapper);

		Wrapper<SalesOrder> wrapper0 = new EntityWrapper();
		wrapper0.setSqlSelect("user_id userId,COUNT(*) recentlyNum");
		wrapper0.like(StringUtils.isNotBlank(name), "name", name.trim(), SqlLike.DEFAULT);
		wrapper0.eq(StringUtils.isNotBlank(account), "account", account.trim());
		wrapper0.eq(StringUtils.isNotBlank(salesSubst), "sales_subst", salesSubst.trim());
		wrapper0.eq(StringUtils.isNotBlank(salesSchool), "sales_school", salesSchool.trim());
		wrapper0.ge("recently_amount", 50);
		wrapper0.eq( "del_flag", 0);
		wrapper0.groupBy("user_id");
		if(StringUtils.isNotBlank(activateTime)){
			String[] months = activateTime.split("\\,");
			if(!activateTime.equals(",") && StringUtils.isNotEmpty(activateTime)){
				String m1 = months[0].substring(0,7);
				String month1 = m1.substring(0,4) + m1.substring(5);
				String m2 = months[1].substring(0,7);
				String month2 = m2.substring(0,4) + m2.substring(5);
				wrapper0.between("activate_time",month1,month2);
			}
		}
		List<Map<String,Object>> list0 = salesOrderMapper.selectMaps(wrapper0);
		if(list0.size()==0){
			page.setTotal(0);
			return ResponseData.success(page, "没有数据！");
		}
		List<String> userIds = new ArrayList<>();
		for (Map<String,Object> map : list0) {
			userIds.add(map.get("userId").toString());
		}
		Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
		hhrUserWrapper.in("id",userIds);
		hhrUserWrapper.eq(StringUtils.isNotBlank(position), "position", position.trim());
		List<HhrUser> userList = hhrUserMapper.selectList(hhrUserWrapper);
		if(userList.size()==0){
			page.setTotal(0);
			return ResponseData.success(page, "没有数据！");
		}
		for (HhrUser hhrUser : userList) {
			for (SalesOrder salesOrder : salesOrderList) {
				if(hhrUser.getId().equals(salesOrder.getUserId())){
					Map<String,Object> objectMap = new HashMap<>();
					objectMap.put("id",salesOrder.getId());
					objectMap.put("userId",salesOrder.getUserId());
					objectMap.put("name",salesOrder.getName());
					objectMap.put("account",salesOrder.getAccount());
					objectMap.put("salesSubst",salesOrder.getSalesSubst());
					objectMap.put("salesSchool",salesOrder.getSalesSchool());
					objectMap.put("position",hhrUser.getPosition());
					if(StringUtils.isNotBlank(hhrUser.getParentId())){
						Wrapper<SysUser> wrapper01 = new EntityWrapper<>();
						wrapper01.eq("id",hhrUser.getParentId());
						wrapper01.like(StringUtils.isNotBlank(leader), "name", leader.trim(), SqlLike.DEFAULT);
						List<SysUser> list = sysUserMapper.selectList(wrapper01);
						if(list.size()>0){
							objectMap.put("leader",list.get(0).getName());
						}else {
							break;
						}
					}
					dataList0.add(objectMap);
				}
			}
		}
		List<Map<String,Object>> dataList = new LinkedList<>();
		for (Map<String, Object> objectMap : list0) {
			String userId = objectMap.get("userId").toString();
			for (Map<String, Object> map : dataList0) {
				if(userId.equals(map.get("userId").toString())){
					map.put("recentlyNum",objectMap.get("recentlyNum"));
					dataList.add(map);
					break;
				}
			}
		}
		if(dataList.size() < pageSize) {
			dataList = dataList;
		}else {
			dataList = dataList.subList((pageNo-1)*pageSize, pageNo*pageSize);
		}
		page.setRecords(dataList);
		return ResponseData.success(page, "查询完毕！");
	}

    /**
     * 导出订单清单
     * @param name
     * @param account
     * @param salesSubst
     * @param salesSchool
     * @param activateTime
     * @param leader
     * @param position
     * @throws IOException
     */
    @Permission(menuname = "导出学子公司销量统计清单", value = "exportList", method = RequestMethod.POST)
    public void downloadHhrOrder(
            @RequestParam(name = "name", required = false) String name,
			@RequestParam(name = "account", required = false) String account,
            @RequestParam(name = "salesSubst", required = false) String salesSubst,
			@RequestParam(name = "salesSchool", required = false) String salesSchool,
            @RequestParam(name = "activateTime", required = false) String activateTime,
			@RequestParam(name = "leader", required = false) String leader,
			@RequestParam(name = "position", required = false) String position) throws IOException {
        List<Map<String, Object>> dataList0 = new LinkedList<>();

		Wrapper<SalesOrder> wrapper = new EntityWrapper();
//		wrapper.like(StringUtils.isNotBlank(name), "name", name.trim(), SqlLike.DEFAULT);
//		wrapper.eq(StringUtils.isNotBlank(account), "account", account.trim());
//		wrapper.eq(StringUtils.isNotBlank(salesSubst), "sales_subst", salesSubst.trim());
//		wrapper.eq(StringUtils.isNotBlank(salesSchool), "sales_school", salesSchool.trim());
		wrapper.ge("recently_amount", 50);
		wrapper.eq( "del_flag", 0);
		/*if(StringUtils.isNotBlank(activateTime)){
			String[] months = activateTime.split("\\,");
			if(!activateTime.equals(",") && StringUtils.isNotEmpty(activateTime)){
				String m1 = months[0].substring(0,7);
				String month1 = m1.substring(0,4) + m1.substring(5);
				String m2 = months[1].substring(0,7);
				String month2 = m2.substring(0,4) + m2.substring(5);
				wrapper.between("activate_time",month1,month2);
				*//*wrapper.ge(StringUtils.isNotBlank(month1),"activate_time",month1);
				wrapper.le(StringUtils.isNotBlank(month2),"activate_time",month2);*//*
			}
		}*/
		List<SalesOrder> salesOrderList = salesOrderMapper.selectList(wrapper);

		Wrapper<SalesOrder> wrapper0 = new EntityWrapper();
		wrapper0.setSqlSelect("user_id userId,COUNT(*) recentlyNum");
		wrapper0.like(StringUtils.isNotBlank(name), "name", name.trim(), SqlLike.DEFAULT);
		wrapper0.eq(StringUtils.isNotBlank(account), "account", account.trim());
		wrapper0.eq(StringUtils.isNotBlank(salesSubst), "sales_subst", salesSubst.trim());
		wrapper0.eq(StringUtils.isNotBlank(salesSchool), "sales_school", salesSchool.trim());
		wrapper0.ge("recently_amount", 50);
		wrapper0.eq( "del_flag", 0);
		wrapper0.groupBy("user_id");
		if(StringUtils.isNotBlank(activateTime)){
			String[] months = activateTime.split("\\,");
			if(!activateTime.equals(",") && StringUtils.isNotEmpty(activateTime)){
				String m1 = months[0].substring(0,7);
				String month1 = m1.substring(0,4) + m1.substring(5);
				String m2 = months[1].substring(0,7);
				String month2 = m2.substring(0,4) + m2.substring(5);
				wrapper0.between("activate_time",month1,month2);
			}
		}
		List<Map<String,Object>> list0 = salesOrderMapper.selectMaps(wrapper0);
		if(list0.size()==0){
			log.info("没有数据");
		}
		List<String> userIds = new ArrayList<>();
		for (Map<String,Object> map : list0) {
			userIds.add(map.get("userId").toString());
		}
		Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
		hhrUserWrapper.in("id",userIds);
		//hhrUserWrapper.eq(StringUtils.isNotBlank(position), "position", position.trim());
		List<HhrUser> userList = hhrUserMapper.selectList(hhrUserWrapper);
		if(userList.size()==0){
			log.info("没有数据");
		}
		for (HhrUser hhrUser : userList) {
			for (SalesOrder salesOrder : salesOrderList) {
				if(hhrUser.getId().equals(salesOrder.getUserId())){
					Map<String,Object> objectMap = new HashMap<>();
					objectMap.put("id",salesOrder.getId());
					objectMap.put("userId",salesOrder.getUserId());
					objectMap.put("name",salesOrder.getName());
					objectMap.put("account",salesOrder.getAccount());
					objectMap.put("salesSubst",salesOrder.getSalesSubst());
					objectMap.put("salesSchool",salesOrder.getSalesSchool());
					objectMap.put("position",hhrUser.getPosition());
					if(StringUtils.isNotBlank(hhrUser.getParentId())){
						Wrapper<SysUser> wrapper01 = new EntityWrapper<>();
						wrapper01.eq("id",hhrUser.getParentId());
						//wrapper01.like(StringUtils.isNotBlank(leader), "name", leader.trim(), SqlLike.DEFAULT);
						List<SysUser> list = sysUserMapper.selectList(wrapper01);
						if(list.size()>0){
							objectMap.put("leader",list.get(0).getName());
						}else {
							break;
						}
					}
					dataList0.add(objectMap);
				}
			}
		}
		List<Map<String,Object>> dataList = new LinkedList<>();
		for (Map<String, Object> objectMap : list0) {
			String userId = objectMap.get("userId").toString();
			for (Map<String, Object> map : dataList0) {
				if(userId.equals(map.get("userId").toString())){
					map.put("recentlyNum",objectMap.get("recentlyNum"));
					dataList.add(map);
					break;
				}
			}
		}
        ServletOutputStream os = null;
		List<Integer> columnWidths = new ArrayList<>();
		columnWidths.add(4000);
		columnWidths.add(4000);
		columnWidths.add(3000);
		columnWidths.add(5000);
		columnWidths.add(4000);
		columnWidths.add(3000);
		columnWidths.add(3000);
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook2(ExcelDealUtils.salesCensusExcel("放号充值达标清单"), dataList,columnWidths);
        try {
            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);
        }
    }
}
