package com.winsun.controller;

import java.io.IOException;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;
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.Bill;
import com.winsun.bean.BonusApply;
import com.winsun.bean.HhrUser;
import com.winsun.bean.SalesOrder;
import com.winsun.bean.School;
import com.winsun.bean.SysUser;
import com.winsun.mapper.BonusMapper;
import com.winsun.mapper.HhrUserMapper;
import com.winsun.mapper.SalesOrderMapper;
import com.winsun.mapper.SchoolMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.tenpay.CorporatePrepayResponse;
import com.winsun.tenpay.business.TenpayXyjlBusiness;
import com.winsun.utils.ExcelDealUtils;
import com.winsun.utils.MapUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 奖励结算 controller
 * @Author: dongyp
 * @Date: 2020/5/6
 */
@Slf4j
@RestController
@RequestMapping("/bonus")
public class BonusController extends BaseController {

	private static BonusMapper bonusMapper;
	private static SysUserMapper sysUserMapper;
	private static SchoolMapper schoolMapper;
	
	public static Lock lock = new ReentrantLock();
	List<Map<String,Object>> exportResponseList = new ArrayList<Map<String,Object>>();
	
	@Autowired
	private HhrUserMapper hhrUserMapper;
	@Autowired
	private SalesOrderMapper salesOrderMapper;

	@Autowired
	public BonusController(BonusMapper bonusMapper,SysUserMapper sysUserMapper,SchoolMapper schoolMapper) {
		BonusController.bonusMapper = bonusMapper;
		BonusController.sysUserMapper = sysUserMapper;
		BonusController.schoolMapper = schoolMapper;
	}
	
	@Permission(menuname = "获取佣金申请数据", value = "applyDataList", method = RequestMethod.POST)
	public ResponseData<Page<Map<String, Object>>> applyDataList(@RequestParam("userName") String userName,
			@RequestParam("account") String account, @RequestParam("substName") String substName,
			@RequestParam(name = "schoolName", required = false) String schoolName,
			@RequestParam(name = "isBind", required = false) String isBind,
			@RequestParam(name = "pageNo", required = false) int pageIndex,
			@RequestParam(name = "pageSize", required = false) int pageSize) {
		Wrapper<SalesOrder> wrapperSales = new EntityWrapper<SalesOrder>();
		wrapperSales.setSqlSelect(" user_id userId,sum(non_send_bonus) bonus ");
		wrapperSales.eq("status", 3);
		wrapperSales.eq("del_flag", 0);
		wrapperSales.ne("non_send_bonus", 0);
		wrapperSales.groupBy("user_id");
		List<Map<String,Object>> salesList = salesOrderMapper.selectMaps(wrapperSales);
		
		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.setSqlSelect(" id,account,name ");
		wrapperSys.eq(StringUtils.isNotBlank(account), "account", account);
		wrapperSys.eq(StringUtils.isNotBlank(userName), "name", userName);
		//wrapperSys.ne("status", 1);
		Map<String,Map<String,Object>> sysUserMaps = MapUtil.listToMap(sysUserMapper.selectMaps(wrapperSys), "id");
		
		Wrapper<HhrUser> wrapperHhr = new EntityWrapper<HhrUser>();
		wrapperHhr.setSqlSelect(" id,(case when open_id is not null then '已绑定' else '未绑定' end) isBind  ");
		if(StringUtils.isNotBlank(isBind)) {
			if("0".equals(isBind)) {
				wrapperHhr.isNull("open_id");
			}else {
				wrapperHhr.isNotNull("open_id");
			}
		}

		Map<String,Object> hhrUserMaps = MapUtil.listToMap(hhrUserMapper.selectMaps(wrapperHhr), "id", "isBind");
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		wrapperSchool.setSqlSelect(" sub_name substName,school_name schoolName,id  ");
		wrapperSchool.eq(StringUtils.isNoneBlank(substName),"sub_name", substName);
		wrapperSchool.eq(StringUtils.isNoneBlank(schoolName),"school_name", schoolName);
		Map<String, Map<String, Object>> schoolMaps = MapUtil.listToMap(schoolMapper.selectMaps(wrapperSchool), "id");
		
		Map<String,Object> schoolRefMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		
		for(Map<String,Object> map : salesList) {
			String userId = map.get("userId").toString();
			boolean isMatch = false;
			
			if(null != sysUserMaps.get(userId)) {
				Map<String, Object> sysUserMap = sysUserMaps.get(userId);
				map.put("account", sysUserMap.get("account"));
				map.put("userName", sysUserMap.get("name"));
				isMatch = true;
			}
			
			if(isMatch && null != hhrUserMaps.get(userId)) {
				map.put("isBind", hhrUserMaps.get(userId).toString());
				String schoolId = schoolRefMap.get(userId).toString();
				
				if(null != schoolMaps.get(schoolId)) {
					Map<String, Object> schoolMap = schoolMaps.get(schoolId);
					map.put("substName", schoolMap.get("substName"));
					map.put("schoolName", schoolMap.get("schoolName"));
					
					dataList.add(map);
				}
			}
		}
		
		
		Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		if(dataList.size() < pageIndex * pageSize) {
			list = dataList.subList((pageIndex-1)*pageSize, dataList.size());
		}else {
			list = dataList.subList((pageIndex-1)*pageSize, pageIndex*pageSize);
		}
		
		page.setRecords(list);
		page.setTotal(dataList.size());
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "发起申请生成订单", value = "productOrder", method = RequestMethod.POST)
	public ResponseData<String> productOrder(@RequestParam("ids") String ids, 
			@RequestParam("status") String status){

		Wrapper<SalesOrder> wrapperSales = new EntityWrapper<SalesOrder>();
		wrapperSales.setSqlSelect(" user_id userId,non_send_bonus bonus,order_phone orderPhone,id ");
		wrapperSales.eq("status", 3);
		wrapperSales.eq("del_flag", 0);
		wrapperSales.ne("non_send_bonus", 0);
		wrapperSales.in("user_id", ids);
		List<Map<String,Object>> salesList = salesOrderMapper.selectMaps(wrapperSales);
		
		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.setSqlSelect(" id,account,name ");
		wrapperSys.eq("status", 1);
		Map<String,Map<String,Object>> sysUserMaps = MapUtil.listToMap(sysUserMapper.selectMaps(wrapperSys), "id");
		
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		for(Map<String,Object> map : salesList) {
			String userId = map.get("userId").toString();
			
			if(null != sysUserMaps.get(userId)) {
				dataList.add(map);
			}
		}
		
		List<Map<String,Object>> applyList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> applyDetailList = new ArrayList<Map<String,Object>>();
		Map<String, Object> firstMap = dataList.get(0);
		String theUserId = firstMap.get("userId").toString();
		double bonus = 0;;
		String applyNum = "Tbo" + Long.toString(System.currentTimeMillis()) + (int)(Math.random()* 100000) ;
	
		
		for(Map<String, Object> map : dataList) {
			String userId = map.get("userId").toString();
			double theBonus = (double)map.get("bonus");
			String bonusNum = "Tb" + Long.toString(System.currentTimeMillis()) + (int)(Math.random()* 100000) ;
			
			if(userId.equals(theUserId)) {
				bonus += theBonus;
			}else {
				Map<String, Object> applyMap = new HashMap<String, Object>();
				applyMap.put("userId", theUserId);
				applyMap.put("bonus", bonus);
				applyMap.put("applyNum", applyNum);
				applyMap.put("bonusNum", bonusNum);
				applyList.add(applyMap);

				bonus = theBonus;
			}
			
			map.put("applyNum", applyNum);
			map.put("bonusNum", bonusNum);
			applyDetailList.add(map);
			theUserId = userId;
		}
		
		Map<String, Object> lastMap = new HashMap<String, Object>();
		String lastBonusNum = "Tb" + Long.toString(System.currentTimeMillis()) + (int)(Math.random()* 100000) ;
		lastMap.put("userId", theUserId);
		lastMap.put("bonus", bonus);
		lastMap.put("applyNum", applyNum);
		lastMap.put("bonusNum", lastBonusNum);
		applyList.add(lastMap);
		
		ShiroUser user = getShiroUser();
		
		// 插入数据库
		for(Map<String, Object> map : applyList) {
			List<BonusApply> bonusList = new ArrayList<BonusApply>();
			BonusApply bonusApply = new BonusApply(); 
			bonusApply.setApplyNum(map.get("applyNum").toString());
			bonusApply.setUserId(map.get("userId").toString());
			bonusApply.setBonus((double)map.get("bonus"));
			bonusApply.setApplicant(user.getName());
			bonusApply.setBonusNum(map.get("bonusNum").toString());
			bonusApply.setApplicantId(Integer.toString(user.getId()));
			bonusApply.setCreateDate(new Date());
			
			bonusMapper.insert(bonusApply);
		}
		
		for(Map<String, Object> map : applyDetailList) {
			String orderPhone = map.get("orderPhone").toString();
			double theBonus = (double)map.get("bonus");
			int salesId = (int)map.get("id");
			String theApplyNum = map.get("applyNum").toString();
			String bonusNum = map.get("bonusNum").toString();
				
			bonusMapper.addApplyDetail(theBonus, theApplyNum, bonusNum, salesId, orderPhone);
		}

		return ResponseData.success("申请成功");
	}
	
	@Permission(menuname = "获取佣金申请单", value = "applyOrderList", method = RequestMethod.POST)
	public ResponseData<Page<Map<String, Object>>> applyOrderList(@RequestParam("userName") String userName,
			@RequestParam("substName") String substName,@RequestParam(name = "schoolName", required = false) String schoolName,
			@RequestParam("state") String state, @RequestParam("applyNum") String applyNum,
			@RequestParam(name = "pageNo", required = false) int pageIndex,
			@RequestParam(name = "pageSize", required = false) int pageSize) {
		Wrapper<BonusApply> wrapperApply = new EntityWrapper<BonusApply>();
		wrapperApply.eq(StringUtils.isNotBlank(applyNum), "apply_num", applyNum);
		wrapperApply.eq(StringUtils.isNotBlank(state), "state", state);
		List<Map<String,Object>> applyList = bonusMapper.selectMaps(wrapperApply);
		
		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.setSqlSelect(" id,account,name ");
		wrapperSys.eq(StringUtils.isNotBlank(userName), "name", userName);
		wrapperSys.eq("status", 1);
		Map<String,Map<String,Object>> sysUserMaps = MapUtil.listToMap(sysUserMapper.selectMaps(wrapperSys), "id");
		
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		wrapperSchool.setSqlSelect(" sub_name substName,school_name schoolName,id  ");
		wrapperSchool.eq(StringUtils.isNoneBlank(substName),"sub_name", substName);
		wrapperSchool.eq(StringUtils.isNoneBlank(schoolName),"school_name", schoolName);
		Map<String, Map<String, Object>> schoolMaps = MapUtil.listToMap(schoolMapper.selectMaps(wrapperSchool), "id");
		
		Map<String,Object> schoolRefMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		
		for(Map<String,Object> map : applyList) {
			String userId = map.get("userId").toString();
			
			if(null != sysUserMaps.get(userId)) {
				Map<String, Object> sysUserMap = sysUserMaps.get(userId);
				map.put("account", sysUserMap.get("account"));
				map.put("userName", sysUserMap.get("name"));
				String schoolId = schoolRefMap.get(userId).toString();
				
				if(null != schoolMaps.get(schoolId)) {
					Map<String, Object> schoolMap = schoolMaps.get(schoolId);
					map.put("substName", schoolMap.get("substName"));
					map.put("schoolName", schoolMap.get("schoolName"));
					
					dataList.add(map);
				}
			}
		}
		
		Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		if(dataList.size() < pageIndex * pageSize) {
			list = dataList.subList((pageIndex-1)*pageSize, dataList.size());
		}else {
			list = dataList.subList((pageIndex-1)*pageSize, pageIndex*pageSize);
		}
		
		page.setRecords(list);
		page.setTotal(dataList.size());
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "修改申请单状态", value = "updateState", method =  RequestMethod.POST)
	public ResponseData<String> updateState(@RequestParam("applyNums") String applyNums,@RequestParam("state") String state){
		String[] applyNumArray = applyNums.split(",");
		
		for(String applyNum : applyNumArray) {
			Wrapper<BonusApply> wrapper = new EntityWrapper<BonusApply>();
			wrapper.eq("apply_num", applyNum);
			
			BonusApply bonusApply = new BonusApply();
			bonusApply.setState(state);
			int num = bonusMapper.update(bonusApply, wrapper);
		}
		
		return ResponseData.success("申请成功");
	}
	
	@Permission(menuname = "获取申请单审核列表", value = "auditOrderList", method = RequestMethod.POST)
	public ResponseData<Page<BonusApply>> auditOrderList(@RequestParam("applicant") String applicant,
			@RequestParam("state") String state, @RequestParam("applyNum") String applyNum,
			@RequestParam(name = "pageNo", required = false) int pageIndex,
			@RequestParam(name = "pageSize", required = false) int pageSize) {
		Page<BonusApply> page = new Page<>(pageIndex, pageSize);
		Wrapper<BonusApply> wrapperApply = new EntityWrapper<BonusApply>();
		wrapperApply.setSqlSelect(" id,apply_num applyNum,state,create_date createDate,sum(bonus) bonus,applicant");
		wrapperApply.eq(StringUtils.isNotBlank(applicant),"applicant", applicant);
		wrapperApply.eq(StringUtils.isNotBlank(applyNum),"apply_num", applyNum);
		wrapperApply.eq(StringUtils.isNotBlank(state),"state", state);
		wrapperApply.groupBy("apply_num");
		List<BonusApply> dataList = bonusMapper.selectPage(page, wrapperApply);
		
		page.setRecords(dataList);
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "获取佣金结算", value = "bonusList", method = RequestMethod.POST)
	public ResponseData<Page<Map<String, Object>>> bonusList(@RequestParam("account") String account,
			@RequestParam("state") String state, @RequestParam("userName") String userName,
			@RequestParam(name = "pageNo", required = false) int pageIndex,
			@RequestParam(name = "pageSize", required = false) int pageSize) {
		Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
		Wrapper<BonusApply> wrapperApply = new EntityWrapper<BonusApply>();
		wrapperApply.setSqlSelect(" id,state,create_date createDate,bonus,user_id userId,bonus_num bonusNum ");
		wrapperApply.eq(StringUtils.isNotBlank(state),"state", state);
		wrapperApply.in("state", "4,6,7");
		List<Map<String, Object>> bonusList = bonusMapper.selectMaps(wrapperApply);
		
		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.eq(StringUtils.isNotBlank(account), "account", account);
		wrapperSys.eq(StringUtils.isNotBlank(userName), "name", userName);
		wrapperSys.eq("status", 1);
		List<Map<String, Object>> sysList = sysUserMapper.selectMaps(wrapperSys);
		Wrapper<HhrUser> wrapperHhr = new EntityWrapper<HhrUser>();
		Map<String, Object> hhrMaps = MapUtil.listToMap(hhrUserMapper.selectMaps(wrapperHhr),"id","open_id");
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		wrapperSchool.setSqlSelect(" sub_name substName,school_name schoolName,id  ");
		Map<String, Map<String, Object>> schoolMaps = MapUtil.listToMap(schoolMapper.selectMaps(wrapperSchool), "id");
		Map<String,Object> schoolRefMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		
		for(Map<String, Object> bonusMap : bonusList) {
			String userId = Integer.toString((int)bonusMap.get("userId"));
			bonusMap.put("isBind", "未绑定");
			
			if(null != hhrMaps.get(userId) && StringUtils.isNotBlank((String)hhrMaps.get(userId))) {
				bonusMap.put("isBind", "已绑定");
			}
			
			for(Map<String, Object> sysMap : sysList) {
				String theUserId = Integer.toString((int)sysMap.get("id"));
				String schoolId = schoolRefMap.get(userId).toString();
				
				if(null != schoolMaps.get(schoolId)) {
					Map<String, Object> schoolMap = schoolMaps.get(schoolId);
					bonusMap.put("substName", schoolMap.get("substName"));
					bonusMap.put("schoolName", schoolMap.get("schoolName"));
				}
				
				if(theUserId.equals(userId)) {
					bonusMap.put("account", sysMap.get("account"));
					bonusMap.put("userName", sysMap.get("name"));
					
					dataList.add(bonusMap);
				}
			}
		}
		
		if(dataList.size() < pageIndex*pageSize) {
			resultList = dataList.subList((pageIndex-1)*pageSize, dataList.size());
		}else {
			resultList = dataList.subList((pageIndex-1)*pageSize, pageIndex*pageSize);
		}
		
		page.setRecords(resultList);
		page.setTotal(dataList.size());
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "佣金结算", value = "sendBonus", method = RequestMethod.POST)
	public ResponseData<String> sendBonus(@RequestParam("bonusNums") String bonusNums) {
		Wrapper<BonusApply> wrapperApply = new EntityWrapper<BonusApply>();
		wrapperApply.setSqlSelect(" id,state,apply_num applyNum,bonus_num bonusNum,create_date createDate,bonus,user_id userId");
		wrapperApply.in("bonus_num", bonusNums);
		List<Map<String, Object>> bonusList = bonusMapper.selectMaps(wrapperApply);
		
		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.eq("status", 1);
		List<Map<String, Object>> sysList = sysUserMapper.selectMaps(wrapperSys);
		Wrapper<HhrUser> wrapperHhr = new EntityWrapper<HhrUser>();
		wrapperHhr.setSqlSelect(" id,open_id,grade,position ");
		Map<String, Object> hhrMaps = MapUtil.listToMap(hhrUserMapper.selectMaps(wrapperHhr),"id","open_id");
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		wrapperSchool.setSqlSelect(" sub_name substName,school_name schoolName,id  ");
		Map<String, Map<String, Object>> schoolMaps = MapUtil.listToMap(schoolMapper.selectMaps(wrapperSchool), "id");
		Map<String,Object> schoolRefMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		
		// 提前取出销售清单数据
		Wrapper<SalesOrder> wrapperOrder = new EntityWrapper<SalesOrder>();
		wrapperOrder.ne("non_send_bonus", 0);
		wrapperOrder.eq("del_flag", 0);
		Map<String, Map<String, Object>> orderMaps = MapUtil.listToMap(salesOrderMapper.selectMaps(wrapperOrder), "id");
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		
		for(Map<String, Object> bonusMap : bonusList) {
			String userId = Integer.toString((int)bonusMap.get("userId"));
			bonusMap.put("openId", hhrMaps.get(userId));
			
			for(Map<String, Object> sysMap : sysList) {
				String theUserId = Integer.toString((int)sysMap.get("id"));
				String schoolId = schoolRefMap.get(userId).toString();
				
				if(null != schoolMaps.get(schoolId)) {
					Map<String, Object> schoolMap = schoolMaps.get(schoolId);
					bonusMap.put("substName", schoolMap.get("substName"));
					bonusMap.put("schoolName", schoolMap.get("schoolName"));
				}
				
				if(theUserId.equals(userId)) {
					bonusMap.put("account", sysMap.get("account"));
					bonusMap.put("userName", sysMap.get("name"));
					
					dataList.add(bonusMap);
				}
			}
		}
		
		exportResponseList = null;
		int num =  wxPayBonus(dataList, orderMaps);
		StringBuffer info = new StringBuffer();
		resultMap.put("num", num);
		info.append("成功结算"+ num +"记录。");
		
		if(dataList.size() < num) {
			info.append((dataList.size() - num) +"结算失败");
		}
		
		return ResponseData.success(info.toString(),"success");
	}
	
	public int wxPayBonus(List<Map<String, Object>> list,Map<String, Map<String, Object>> orderMaps) {
		ShiroUser user = getShiroUser();
		int successNum = 0;
		
		for(Map<String, Object> map : list) {
			String account = map.get("account").toString();
			double amount = Double.valueOf(map.get("bonus").toString()).doubleValue();
			int id = (int)map.get("id");
			String openid = map.get("openId").toString();
			String bonusNum = map.get("bonusNum").toString();
			String orderNum = getOrderNumber("T00");
			String desc = "发起结算；管理员" + user.getAccount() + "发起向销售员" + account + "（id为"+ id +"）发放奖励金" + amount + "元";
			String sendDesc = "校园合伙人向您发放奖励金" + amount + "元;订单号为" + orderNum + ";";
			bonusMapper.addBonusLog(orderNum, desc, "微信企业付款", user.getId(), 0);
			
			// 测试
			amount = 1;
			openid = "oLLfr0_XJc2mcaRqRl3sOQ7GwmVw";

			int sendAmount = (int) (amount * 100.0D);
			String createIp = "127.0.0.1";
			String check_name = "NO_CHECK";
			String re_user_name = "";
			CorporatePrepayResponse resp;
			
			try {
				resp = TenpayXyjlBusiness.xyjlTenPayRequest(orderNum, openid, check_name, re_user_name, sendAmount, sendDesc, createIp);
				if (StringUtils.isNotBlank(resp.getPaymentNo())) {
					desc = "结算成功；管理员" + user.getAccount() + "发起向销售员" + account + "（id为"+ id +"）发放奖励金" + amount + "元";
					
					bonusMapper.updateBonus(1, id);
					bonusMapper.updateBonusLog(desc, resp.getPaymentNo(), 1, orderNum);
					updateSalesOrderBonus(bonusNum,orderMaps);
					successNum++;
				}else {
					desc = "结算失败；管理员" + user.getAccount() + "发起向销售员" + account + "发放奖励金" + amount + "元";
					bonusMapper.updateBonusLog(desc, "", 0, orderNum);

					Map<String, Object> respMap = new HashMap<String, Object>();
					respMap.put("account", map.get("account"));
					respMap.put("name", map.get("name"));
					respMap.put("substName", map.get("substName"));
					respMap.put("schoolName", map.get("schoolName"));
					respMap.put("bonus", map.get("bonus"));
					respMap.put("desc", resp.getErrCodeDesc());
					exportResponseList.add(respMap);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return successNum;
	}
	
	public void updateSalesOrderBonus(String bonusNum, Map<String, Map<String, Object>> orderMaps) {
		List<Map<String, Object>> list = bonusMapper.getBonusDetail(bonusNum);
		
		for(Map<String, Object> map : list) {
			int salesId = (int)map.get("salesId");
			double bonus = (double)map.get("bonus");
			
			Map<String, Object> orderMap = orderMaps.get(Integer.toString((int)map.get("salesId")));
			double nonSendBonus = (double)orderMap.get("nonSendBonus") - bonus;
			double sendBonus = (double)orderMap.get("SendBonus") + bonus;
			
			SalesOrder salesOrder = new SalesOrder();
			salesOrder.setId(salesId);
			salesOrder.setNonSendBonus(nonSendBonus);
			salesOrder.setSendBonus(sendBonus);
			
			salesOrderMapper.updateById(salesOrder);
		}
	}
	
	public String getOrderNumber(String code) {
		// 订单号格式（20）：业务编码（3）+年（2）+月（2）+日（2）+时（2）+分（2）+秒（2）+五位随机数（5）
		String businessCode = code;// 业务编码,暂时没设为"T00"
		SimpleDateFormat formatter;
		formatter = new SimpleDateFormat("yyMMddhhmmss"); // 时间格式
		String times = formatter.format(System.currentTimeMillis());
		SecureRandom random = new SecureRandom();
		int num = random.nextInt(100000);
		String orderNo = businessCode + times + num;
		return orderNo;
	}
	
	@Permission(menuname = "导出奖励结算反馈", value = "exportResult", method = RequestMethod.POST)
    public void exportSendResult() throws IOException {
		
        List<String> tops = new ArrayList<>();
        tops.add("账号");
        tops.add("姓名");
        tops.add("县分");
        tops.add("学校");
        tops.add("金额");
        tops.add("结算失败原因");

        List<String> columns = new ArrayList<>();
        columns.add("account");
        columns.add("userName");
        columns.add("substName");
        columns.add("schoolName");
        columns.add("bonus");
        columns.add("desc");
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("结算失败清单");
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            //设置列宽度
            sheet.setColumnWidth(1, 3000);

            //第一行字段名称
            tops.forEach(column -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(column);
            });
            //数据
            int rowIndex = row.getRowNum();
            for (Map<String, Object> maps: exportResponseList) {
                final XSSFRow rowdata = sheet.createRow(++rowIndex);
                for (String column : columns) {
                    XSSFCell cell = rowdata.createCell(Math.max(rowdata.getLastCellNum(), 0));
                    if (maps.get(column) != null) {
                        cell.setCellValue(maps.get(column).toString());
                    }
                }
            }

            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            
            exportResponseList = null;
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
    }
	
	@Permission(menuname = "导出奖励结算清单", value = "exportSettlementList", method = RequestMethod.POST)
    public void exportStatisList(@RequestParam("account") String account,
			@RequestParam("state") String state, @RequestParam("userName") String userName
    		) throws IOException {

		Wrapper<BonusApply> wrapperApply = new EntityWrapper<BonusApply>();
		wrapperApply.setSqlSelect(" id,state,create_date createDate,bonus,user_id userId");
		wrapperApply.eq(StringUtils.isNotBlank(state),"state", state);
		wrapperApply.in("state", "4,6,7");
		List<Map<String, Object>> bonusList = bonusMapper.selectMaps(wrapperApply);
		
		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.eq(StringUtils.isNotBlank(account), "account", account);
		wrapperSys.eq(StringUtils.isNotBlank(userName), "name", userName);
		wrapperSys.eq("status", 1);
		wrapperSys.eq("del_flag", 0);
		List<Map<String, Object>> sysList = sysUserMapper.selectMaps(wrapperSys);
		Wrapper<HhrUser> wrapperHhr = new EntityWrapper<HhrUser>();
		Map<String, Object> hhrMaps = MapUtil.listToMap(hhrUserMapper.selectMaps(wrapperHhr),"id","open_id");
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		wrapperSchool.setSqlSelect(" sub_name substName,school_name schoolName,id  ");
		Map<String, Map<String, Object>> schoolMaps = MapUtil.listToMap(schoolMapper.selectMaps(wrapperSchool), "id");
		Map<String,Object> schoolRefMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		
		for(Map<String, Object> bonusMap : bonusList) {
			String userId = Integer.toString((int)bonusMap.get("userId"));
			bonusMap.put("isBind", "未绑定");
			
			if(null != hhrMaps.get(userId) && StringUtils.isNotBlank((String)hhrMaps.get(userId))) {
				bonusMap.put("isBind", "已绑定");
			}
			
			for(Map<String, Object> sysMap : sysList) {
				String theUserId = Integer.toString((int)sysMap.get("id"));
				String schoolId = schoolRefMap.get(userId).toString();
				
				if(null != schoolMaps.get(schoolId)) {
					Map<String, Object> schoolMap = schoolMaps.get(schoolId);
					bonusMap.put("substName", schoolMap.get("substName"));
					bonusMap.put("schoolName", schoolMap.get("schoolName"));
				}
				
				if(theUserId.equals(userId)) {
					bonusMap.put("account", sysMap.get("account"));
					bonusMap.put("userName", sysMap.get("name"));
					
					dataList.add(bonusMap);
				}
			}
		}

        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook(ExcelDealUtils.bonusExcel("奖励结算清单"), dataList);
        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);
        }
    }

}
