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>> dataList = new LinkedList<>();

		List<String> userIds = new ArrayList<>();
		if(StringUtils.isNotBlank(leader)){
			Wrapper<SysUser> sysUserWrapper = new EntityWrapper<>();
			sysUserWrapper.like( "name", leader.trim(), SqlLike.DEFAULT);
			List<SysUser> sysUserList = sysUserMapper.selectList(sysUserWrapper);
			if(sysUserList.size()==0){
				page.setTotal(0);
				return ResponseData.success(page, "没有数据！");
			}
			for (SysUser sysUser : sysUserList) {
				userIds.add(sysUser.getId());
			}
		}
		List<String> userIdst = new ArrayList<>();
		if(StringUtils.isNotBlank(position)){
			Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
			if(userIds.size()>0){
				hhrUserWrapper.in("id",userIds);
			}
			hhrUserWrapper.eq( "position", position.trim());
			List<HhrUser> hhrUserList = hhrUserMapper.selectList(hhrUserWrapper);
			if(hhrUserList.size()==0){
				page.setTotal(0);
				return ResponseData.success(page, "没有数据！");
			}
			for (HhrUser hhrUser : hhrUserList) {
				userIdst.add(hhrUser.getId());
			}
		}
		Wrapper<SalesOrder> wrapper0 = new EntityWrapper();
		wrapper0.setSqlSelect("user_id userId,COUNT(*) recentlyNum");
		if(userIdst.size()>0){
			wrapper0.in("user_id",userIdst);
		}
		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);
			}
		}
		dataList = salesOrderMapper.selectMaps(wrapper0);
		if(dataList.size()==0){
			page.setTotal(0);
			return ResponseData.success(page, "没有数据！");
		}
		page.setTotal(dataList.size());
		if(dataList.size() >= pageSize) {
			Integer endpageSize = (pageNo-1) == dataList.size()/pageSize?(pageNo-1)*pageSize+dataList.size()%pageSize:pageNo*pageSize;
			dataList = dataList.subList((pageNo-1)*pageSize, endpageSize);
		}
		List<String> ids = new ArrayList<>();
		for (Map<String, Object> objectMap : dataList) {
			ids.add(objectMap.get("userId").toString());
		}
		Wrapper<HhrUser> hhrUserWrapper1 = new EntityWrapper<>();
		hhrUserWrapper1.in("id",ids);
		List<HhrUser> hhrUsers = hhrUserMapper.selectList(hhrUserWrapper1);

		for (Map<String, Object> objectMap : dataList) {
			String userId = objectMap.get("userId").toString();
			Wrapper<SalesOrder> salesOrderWrapper = new EntityWrapper();
			salesOrderWrapper.eq("user_id",userId);
			List<SalesOrder> salesOrderList = salesOrderMapper.selectList(salesOrderWrapper);
			SalesOrder salesOrder = salesOrderList.get(0);
			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());
			for (HhrUser hhrUser : hhrUsers) {
				if(hhrUser.getId().equals(userId)){
					objectMap.put("position",hhrUser.getPosition());
					if(StringUtils.isNotBlank(hhrUser.getParentId())){
						SysUser sysUser = sysUserMapper.selectById(hhrUser.getParentId());
						if(sysUser != null){
							objectMap.put("leader",sysUser.getName());
						}
					}
					break;
				}
			}
		}
		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>> dataList = new LinkedList<>();

		List<String> userIds = new ArrayList<>();
		if(StringUtils.isNotBlank(leader)){
			Wrapper<SysUser> sysUserWrapper = new EntityWrapper<>();
			sysUserWrapper.like( "name", leader.trim(), SqlLike.DEFAULT);
			List<SysUser> sysUserList = sysUserMapper.selectList(sysUserWrapper);
			if(sysUserList.size()==0){
				log.info("没有数据");
			}
			for (SysUser sysUser : sysUserList) {
				userIds.add(sysUser.getId());
			}
		}
		List<String> userIdst = new ArrayList<>();
		if(StringUtils.isNotBlank(position)){
			Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
			if(userIds.size()>0){
				hhrUserWrapper.in("id",userIds);
			}
			hhrUserWrapper.eq( "position", position.trim());
			List<HhrUser> hhrUserList = hhrUserMapper.selectList(hhrUserWrapper);
			if(hhrUserList.size()==0){
				log.info("没有数据");
			}
			for (HhrUser hhrUser : hhrUserList) {
				userIdst.add(hhrUser.getId());
			}
		}
		Wrapper<SalesOrder> wrapper0 = new EntityWrapper();
		wrapper0.setSqlSelect("user_id userId,COUNT(*) recentlyNum");
		if(userIdst.size()>0){
			wrapper0.in("user_id",userIdst);
		}
		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);
			}
		}
		dataList = salesOrderMapper.selectMaps(wrapper0);
		if(dataList.size()==0){
			log.info("没有数据");
		}
		List<String> ids = new ArrayList<>();
		for (Map<String, Object> objectMap : dataList) {
			ids.add(objectMap.get("userId").toString());
		}
		Wrapper<HhrUser> hhrUserWrapper1 = new EntityWrapper<>();
		hhrUserWrapper1.in("id",ids);
		List<HhrUser> hhrUsers = hhrUserMapper.selectList(hhrUserWrapper1);

		for (Map<String, Object> objectMap : dataList) {
			String userId = objectMap.get("userId").toString();
			Wrapper<SalesOrder> salesOrderWrapper = new EntityWrapper();
			salesOrderWrapper.eq("user_id",userId);
			List<SalesOrder> salesOrderList = salesOrderMapper.selectList(salesOrderWrapper);
			SalesOrder salesOrder = salesOrderList.get(0);
			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());
			for (HhrUser hhrUser : hhrUsers) {
				if(hhrUser.getId().equals(userId)){
					objectMap.put("position",hhrUser.getPosition());
					if(StringUtils.isNotBlank(hhrUser.getParentId())){
						SysUser sysUser = sysUserMapper.selectById(hhrUser.getParentId());
						if(sysUser != null){
							objectMap.put("leader",sysUser.getName());
						}
					}
					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);
        }
    }
}
