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<>();
		List<String> parentId = new ArrayList<>();
		if(StringUtils.isNotBlank(position)) {
			Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
			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) {
				userIds.add(hhrUser.getId());
				if (StringUtils.isNotBlank(hhrUser.getParentId())) {
					parentId.add(hhrUser.getParentId());
				}
			}
		}
		if(StringUtils.isNotBlank(leader)){
			Wrapper<SysUser> sysUserWrapper = new EntityWrapper<>();
			if (parentId.size() > 0) {
				sysUserWrapper.in("id", parentId);
			}
			sysUserWrapper.eq( "name", leader.trim());
			List<SysUser> sysUserList = sysUserMapper.selectList(sysUserWrapper);
			if(sysUserList.size()==0){
				log.info("没有数据");
			}
			Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
			hhrUserWrapper.eq("parent_id",sysUserList.get(0).getId());
			List<HhrUser> hhrUserList = hhrUserMapper.selectList(hhrUserWrapper);
			if(hhrUserList.size()==0){
				log.info("没有数据");
			}
			userIds.removeAll(userIds);
			for (HhrUser hhrUser : hhrUserList) {
				userIds.add(hhrUser.getId());
			}
		}
		Wrapper<SalesOrder> wrapper0 = new EntityWrapper();
		wrapper0.setSqlSelect("user_id userId,COUNT(*) recentlyNum");
		if(userIds.size()>0){
			wrapper0.in("user_id",userIds);
		}
		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[] dates = activateTime.split("\\,");
			if(!activateTime.equals(",")){
				wrapper0.between("activate_time",dates[0],dates[1]);
			}
		}
		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);
		}
		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());
			HhrUser hhrUser = hhrUserMapper.selectById(salesOrder.getUserId());
			if(hhrUser != null){
				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());
						}
					}
				}
			}
		}
		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<>();
		List<String> parentId = new ArrayList<>();
		if(StringUtils.isNotBlank(position)) {
			Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
			hhrUserWrapper.eq("position", position.trim());
			List<HhrUser> hhrUserList = hhrUserMapper.selectList(hhrUserWrapper);
			if (hhrUserList.size() == 0) {
				log.info("没有数据");
			}
			for (HhrUser hhrUser : hhrUserList) {
				userIds.add(hhrUser.getId());
				if (StringUtils.isNotBlank(hhrUser.getParentId())) {
					parentId.add(hhrUser.getParentId());
				}
			}
		}
		if(StringUtils.isNotBlank(leader)){
			Wrapper<SysUser> sysUserWrapper = new EntityWrapper<>();
			if (parentId.size() > 0) {
				sysUserWrapper.in("id", parentId);
			}
			sysUserWrapper.eq( "name", leader.trim());
			List<SysUser> sysUserList = sysUserMapper.selectList(sysUserWrapper);
			if(sysUserList.size()==0){
				log.info("没有数据");
			}
			for (SysUser sysUser : sysUserList) {
				parentId.add(sysUser.getId());
			}
			Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
			hhrUserWrapper.eq("parent_id",sysUserList.get(0).getId());
			List<HhrUser> hhrUserList = hhrUserMapper.selectList(hhrUserWrapper);
			if(hhrUserList.size()==0){
				log.info("没有数据");
			}
			userIds.removeAll(userIds);
			for (HhrUser hhrUser : hhrUserList) {
				userIds.add(hhrUser.getId());
			}
		}
		Wrapper<SalesOrder> wrapper0 = new EntityWrapper();
		wrapper0.setSqlSelect("user_id userId,COUNT(*) recentlyNum");
		if(userIds.size()>0){
			wrapper0.in("user_id",userIds);
			userIds.removeAll(userIds);
		}
		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[] dates = activateTime.split("\\,");
			if(!activateTime.equals(",")){
				wrapper0.between("activate_time",dates[0],dates[1]);
			}
		}
		dataList = salesOrderMapper.selectMaps(wrapper0);
		if(dataList.size()==0){
			log.info("没有数据");
		}
		for (Map<String, Object> objectMap : dataList) {
			userIds.add(objectMap.get("userId").toString());
		}
		Wrapper<SalesOrder> wrapper = new EntityWrapper();
		if(userIds.size()>0){
			wrapper.in("user_id",userIds);
		}
		List<SalesOrder> salesOrderList = salesOrderMapper.selectList(wrapper);

		Wrapper<HhrUser> hhrUserWrapper1 = new EntityWrapper<>();
		hhrUserWrapper1.in("id",userIds);
		List<HhrUser> hhrUsers = hhrUserMapper.selectList(hhrUserWrapper1);

		Wrapper<SysUser> sysUserWrapper = new EntityWrapper<>();
		if(parentId.size()>0){
			List<String> list= removeDuplicate(parentId);
			sysUserWrapper.in("id",list);
		}
		List<SysUser> sysUserList = sysUserMapper.selectList(sysUserWrapper);
		for (Map<String, Object> objectMap : dataList) {
			String userId = objectMap.get("userId").toString();
			for (SalesOrder salesOrder : salesOrderList) {
				if(userId.equals(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())){
								for (SysUser sysUser : sysUserList) {
									if(hhrUser.getParentId().equals(sysUser.getId())){
										objectMap.put("leader",sysUser.getName());
										break;
									}
									objectMap.put("leader","");
								}
							}
							objectMap.put("leader","");
							break;
						}
						objectMap.put("position","");
					}
					break;
				}
			}
			objectMap.remove("userId");
		}
        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);
        }
    }

	/**
	 * List集合去除重复数据
	 * @param list
	 * @return
	 */
	public static List removeDuplicate(List list) {
		HashSet h = new HashSet(list);
		list.clear();
		list.addAll(h);
		return list;
	}
}
