package org.jeecg.ctop.finance.policy.controller;

import java.text.ParseException;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.ctop.common.module.entity.UserCompany;
import cn.com.ctop.common.module.mapper.MailLogMapper;
import cn.com.ctop.common.module.mapper.SysUserMapper;
import cn.com.ctop.common.module.service.ISysUserService;
import cn.com.ctop.common.module.service.IUserCompanyService;
import cn.com.ctop.common.module.utils.CorpWexinUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.entity.SysUser;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.ctop.finance.policy.entity.*;
import org.jeecg.ctop.finance.policy.mapper.*;
import org.jeecg.ctop.finance.policy.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.ctop.finance.policy.utils.Check;
import org.jeecg.ctop.finance.policy.utils.ListPageUtil;
import org.jeecg.ctop.finance.settlement.service.serviceImpl.ReportSettlementServiceImpl;
import org.jeecg.modules.ctop.service.IMaterialReportOverViewService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * 政策信息表
 * @author jeecg-boot
 * @date   2021-07-27
 * @version V1.0
 */
@Slf4j
@Api(tags="政策模块")
@RestController
@RequestMapping("/cwjsPolicyInfo")
public class CwjsPolicyInfoController {
	@Autowired
	private ICwjsPolicyInfoService cwjsPolicyInfoService;
	@Autowired
	private ICwjsPolicyProductService cwjsPolicyProductService;
	 @Autowired
	 private ISysRoleService roleService;
	 @Resource
	 IUserCompanyService userCompanyService;
	 @Autowired
	 ICwjsPolicyApprovalLogService policyApprovalLogService;
	 @Resource
	 CwjsCompanyApprovalUserMapper companyApprovalUserMapper;
	 @Resource
	 CwjsPolicyInfoMapper cwjsPolicyInfoMapper;
	 @Resource
	 CwjsCompanySubjectMapper companySubjectMapper;
	 @Autowired
	 ICwjsCompanySubjectService companySubjectService;
	 @Resource
	 CwjsPolicyApprovalLogMapper policyApprovalLogMapper;
	 @Resource
	 CorpWexinUtils corpWexinUtils;
	 @Resource
	 MailLogMapper mailLogMapper;
     @Autowired
     private ISysUserService sysUserService;


     @Resource
     private ReportSettlementServiceImpl reportSettlementService;

	 @Autowired
	 private ICwjsSaleAssistantInfoService cwjsSaleAssistantInfoService;


	 @GetMapping(value = "/queryApprovalRejectReason")
	 public Result<CwjsPolicyApprovalLog> queryApprovalRejectReason(@RequestParam(name="id",required=true) Integer id){
		 CwjsPolicyApprovalLog policyApprovalLog = policyApprovalLogService.getOneByPolicyId(id,1);
		 if(Check.isNull(policyApprovalLog)){
			 return Result.successMsg("无审核拒绝的记录",null);
		 }else{
			 return Result.successMsg("无审核拒绝的记录",policyApprovalLog);
		 }

	 }

	 /**
	  * 审核-master
	  * @param id 政策id
	  * @param type 类型
	  * @param userId 用户id
	  * @param approvalContent 审核内容
	  * @return
	  */
	 @GetMapping(value = "/policyApproval")
	 public Result policyApproval(@RequestParam(name="id",required=true) Integer id,
	 							@RequestParam(name="type",required=true) Integer type,
								  @RequestParam(name="userId",required=true) String userId,
								@RequestParam(name="approvalContent",required=false) String approvalContent){
//		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		CwjsPolicyInfo cwjsPolicyInfoEntity = cwjsPolicyInfoService.getById(id);
		 if(cwjsPolicyInfoEntity==null) {
			 return Result.error("政策不存在或已被删除，请重新选择要审核的政策。");
		 }
		 //获取 主体
		 Integer companySubjectId= cwjsPolicyInfoEntity.getCompanySubjectId();

		 // 当前用户是否是审核人
		 CwjsCompanyApprovalUser cwjsCompanyApprovalUser = companyApprovalUserMapper.queryByCompanySubjectIdAndUserId(companySubjectId, userId);

		 if(type == 1){	//审核提交	等于新增的时候
			 List<CwjsCompanyApprovalUser> cwjsCompanyApprovalUsers = companyApprovalUserMapper.queryByCompanySubjectId(companySubjectId);
			 if(Check.isNull(cwjsCompanyApprovalUsers)){
				 return Result.errorMsg("此业务线暂时无审核人员，提交审核无效，请联系开发人员添加此区域主体的审核人员");
			 }
			 //普通销售，审核都是1，审核进度的人都是等级为0的审核人id
			 cwjsCompanyApprovalUsers.forEach(cwjsCompanyApprovalUser2 -> {
				 if(cwjsCompanyApprovalUser2.getLevel() == 0){
					 cwjsPolicyInfoEntity.setApprovedStatus(1);
					 cwjsPolicyInfoEntity.setApprovedProgress(cwjsCompanyApprovalUser2.getApprovalUserId());
				 }
			 });
			 //如果满足 当前用户 是 审核人员 且 创建人
			 cwjsCompanyApprovalUsers.forEach(cwjsCompanyApprovalUser2 -> {
				 if(cwjsCompanyApprovalUser2.getApprovalUserId().equalsIgnoreCase(cwjsPolicyInfoEntity.getCreateUserId())
						 && cwjsCompanyApprovalUser2.getApprovalUserId().equalsIgnoreCase(userId)){
					 CwjsCompanyApprovalUser approvalUserNext = companyApprovalUserMapper.queryByCompanySubjectIdAndLevel(companySubjectId, cwjsCompanyApprovalUser2.getLevel()+1);
					 if(Check.isNull(approvalUserNext)){
						 cwjsPolicyInfoEntity.setApprovedStatus(3);
						 cwjsPolicyInfoEntity.setApprovedProgress(null);
					 }else{
						 cwjsPolicyInfoEntity.setApprovedStatus(2);
						 cwjsPolicyInfoEntity.setApprovedProgress(approvalUserNext.getApprovalUserId());
					 }
				 }
			 });

			 JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(cwjsPolicyInfoEntity.getApprovedProgress());
			 StringBuilder text = new StringBuilder();
			 text.append("您有一条销售政策需要审核，该客户为：");
			 text.append(cwjsPolicyInfoEntity.getCompanyName());
			 text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
			 corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
		}
		 if(type == 2){	//审核通过  是不是终审，不是就给当前的下一个人发企业微信
			 CwjsCompanyApprovalUser nextApprovalUser = null;
			 //查询 下一个 审核人
		 	if(!Check.isNull(cwjsCompanyApprovalUser)){
				nextApprovalUser = companyApprovalUserMapper.queryByCompanySubjectIdAndLevel(companySubjectId, cwjsCompanyApprovalUser.getLevel() + 1);
			}
			 if(Check.isNull(nextApprovalUser)){//没有下一个审核人员，是终审
				cwjsPolicyInfoEntity.setApprovedStatus(3);
				 /**
				  * 终审通过后 添加 起始时间
				  */
				 reportSettlementService.cwjsPRofit(cwjsPolicyInfoEntity);
			}else{	//不是终审
				cwjsPolicyInfoEntity.setApprovedStatus(2);
				cwjsPolicyInfoEntity.setApprovedProgress(nextApprovalUser.getApprovalUserId());	//设置一下个人为审核人员
				 JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(nextApprovalUser.getApprovalUserId());
				 StringBuilder text = new StringBuilder();
				 text.append("您有一条销售政策需要审核，该客户为：");
				 text.append(cwjsPolicyInfoEntity.getCompanyName());
				 text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
				 corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
			}
			CwjsPolicyApprovalLog policyApprovalLog = new CwjsPolicyApprovalLog();
			policyApprovalLog.setPolicyId(id);
			policyApprovalLog.setCreateUserId(userId);
			policyApprovalLog.setApprovalStatus(0);
			policyApprovalLogService.save(policyApprovalLog);


		}
	 	if(type == 3){	//审核拒绝	给申请人发企业微信
			cwjsPolicyInfoEntity.setApprovedStatus(4);
			CwjsPolicyApprovalLog policyApprovalLog = new CwjsPolicyApprovalLog();
			policyApprovalLog.setPolicyId(id);
			policyApprovalLog.setCreateUserId(userId);
			policyApprovalLog.setApprovalContent(approvalContent);
			policyApprovalLog.setApprovalStatus(1);
			policyApprovalLogService.save(policyApprovalLog);

			JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(cwjsPolicyInfoEntity.getCreateUserId());
			StringBuilder text = new StringBuilder();
			text.append("您有一条销售政策审核未通过，客户为：");
			text.append(cwjsPolicyInfoEntity.getCompanyName());
			text.append("，请及时登录助手平台-销售政策页面进行政策修改，谢谢！");
			corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
		}

	 	//转领导审批 只有审核人是最后一个人的时候 才可以转领导
	 	if (type == 4){
			//根据主体查询 最后一个审核人员
			CwjsCompanyApprovalUser endApprovalUser = companyApprovalUserMapper.getEndApprovalUserBySub(companySubjectId);
			if (!Check.isNull(endApprovalUser)){
				if (!userId.equals(endApprovalUser.getApprovalUserId())){
					return Result.errorMsg("当前所登录用户不是最后一个审核人员，无法转领导审批。");
				}
			}
			cwjsPolicyInfoEntity.setApprovedStatus(2);
			cwjsPolicyInfoEntity.setApprovedProgress("4aba62011120ac565c7f2b9f8f4aa96b");	//设置 boss 为审核人员
			JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId("4aba62011120ac565c7f2b9f8f4aa96b");
			StringBuilder text = new StringBuilder();
			text.append("您有一条销售政策需要审核，该客户为：");
			text.append(cwjsPolicyInfoEntity.getCompanyName());
			text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
			corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());

			CwjsPolicyApprovalLog policyApprovalLog = new CwjsPolicyApprovalLog();
			policyApprovalLog.setPolicyId(id);
			policyApprovalLog.setCreateUserId(userId);
			policyApprovalLog.setApprovalStatus(2);//0-审核通过  1-审核不通过 2-转给领导
			policyApprovalLog.setApprovalContent(approvalContent);
			policyApprovalLogService.save(policyApprovalLog);


		}





		cwjsPolicyInfoService.updateById(cwjsPolicyInfoEntity);
	 	return Result.successMsg("成功",cwjsPolicyInfoEntity);
	 }


	 @Resource
	 private CwjsSaleAssistantInfoMapper cwjsSaleAssistantInfoMapper;
	/**
	  * 分页列表查询
	 * @param cwjsPolicyInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="政策信息表-分页列表查询", notes="政策信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result queryPageList(CwjsPolicyInfo cwjsPolicyInfo,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  @RequestParam(name="userId") String userId,
									  HttpServletRequest req) {

		//查询用户角色
        String roleCode = roleService.getRoleCodeByUserId(userId);


		List<String> userIds = new ArrayList<>();
		if ("admin".equalsIgnoreCase(roleCode) || "finance".equalsIgnoreCase(roleCode) ){

		}else if("saleDirector".equalsIgnoreCase(roleCode)){
			//总监 看下属
			userIds = cwjsPolicyInfoService.getAllSubordinate(userId);

		//法务
		}else if("legalAffairs".equalsIgnoreCase(roleCode)){
			//法务 查看 华北
			cwjsPolicyInfo.setCompanySubjectId(1);
		}else {
			//查询 对应的销售或 助理
			userIds = cwjsSaleAssistantInfoService.getCwSaleAndAssistantListStr(userId);
			if (Check.isNull(userIds)){
				userIds.add(userId);
			}

		}
		cwjsPolicyInfo.setSaleIds(userIds);


        //查询政策
		List<CwjsPolicyInfo> cwjsPolicyInfoList = cwjsPolicyInfoService.queryPageList(cwjsPolicyInfo);
		if(Check.isNull(cwjsPolicyInfoList)){
			return Result.successMsg("没有符合条件的政策，请重新选择。",null);
		}


		List<CwjsPolicyInfo> cwjsPolicyInfos = ListPageUtil.page(cwjsPolicyInfoList, pageSize, pageNo);

		cwjsPolicyInfos.forEach(cwjsPolicy ->{
			CwjsPolicyApprovalLog log = policyApprovalLogMapper.getOneByPolicyId(cwjsPolicy.getId(),1);	// 查询 被拒 审核意见 最新的一条
			cwjsPolicy.setApprovalContent(Check.isNull(log) ? "暂无被拒意见" : log.getApprovalContent());

			CwjsPolicyApprovalLog bossContent = policyApprovalLogMapper.getOneByPolicyId(cwjsPolicy.getId(),2);	// 查询 转发领导的 审核意见 最新的一条
			cwjsPolicy.setTheBossContent(Check.isNull(bossContent) ? "暂无老板审核意见" : bossContent.getApprovalContent());

			CwjsPolicyApprovalLog legalContent = policyApprovalLogMapper.getOneByPolicyId(cwjsPolicy.getId(),11);	// 查询 法务 审核意见 最新的一条
			cwjsPolicy.setLegalAffairsContent(Check.isNull(legalContent) ? "暂无法务审核意见" : legalContent.getApprovalContent());


			String directorUserId = "";
			//主体为1 为 华北
			if (cwjsPolicy.getCompanySubjectId() == 1){
				//查询 该销售 所属的审核人员
				//华北审核人员 - 法务==>销售总监（销售上级）==>手动转领导/自动转领导
				directorUserId = cwjsPolicyInfoMapper.getUserLeaderAndDirectorByRoleName(userId,"法务").getString("leaderId");

			}else {
				//查询 该销售 所属的审核人员
				//华南审核人员 - 销售总监（销售上级） ==> 分公司经理 ==>转领导
				directorUserId = cwjsPolicyInfoMapper.getUserLeaderAndDirectorByRoleName(userId,"分公司总经理").getString("directorId");

			}

				//政策当前审核人 = 最后一个审核人 = 当前用户   && 状态不为3 审核通过  && 状态不为4 审核拒绝  ||  当前用户 不是老板
				// 则显示 转领导审批
				if(cwjsPolicy.getApprovedStatus() != 3 && cwjsPolicy.getApprovedStatus() != 4){
					if (cwjsPolicy.getApprovedProgress().equals(directorUserId) && directorUserId.equals(userId)
							&& !"80e747cdea6f41dbbc8cde23046fd4e0".equals(userId)){
						cwjsPolicy.setTheBossRight("yes");
					}
				}else {
					cwjsPolicy.setTheBossRight("no");
				}



			StringBuilder stringBuilder = new StringBuilder();

			//审核拒绝
			if (cwjsPolicy.getApprovedStatus() == 4){
				//有 销售-助理 关联的人员 都可以编辑
				if(!"admin".equalsIgnoreCase(roleCode) && !"finance".equalsIgnoreCase(roleCode)){
					List <String> saleOrAssis = cwjsSaleAssistantInfoService.getCwSaleAndAssistantListStr(userId);
					if(saleOrAssis.contains(cwjsPolicy.getSaleId())){
						stringBuilder.append("编辑").append("|").append("提交审核").append("|");
					}
				}
			}
			//待审核
			if (cwjsPolicy.getApprovedStatus() == 1 || cwjsPolicy.getApprovedStatus() == 2){
				if(cwjsPolicy.getApprovedProgress().equals(userId)){
					stringBuilder.append("审核通过").append("|").append("审核拒绝").append("|");
				}
			}

			stringBuilder.append("查看").append("|");
			cwjsPolicy.setOperation(stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("|")).toString());



		});
		PageInfo<CwjsPolicyInfo> pageInfo = new PageInfo<>(cwjsPolicyInfos);
		pageInfo.setTotal(cwjsPolicyInfoList.size());
		pageInfo.setPageSize(pageSize);
		pageInfo.setPageNum(pageNo);
		return Result.successMsg("成功",pageInfo);
	}



	@ApiOperation(value="政策信息表-获取当前公司的销售", notes="政策信息表-获取当前公司的销售")
	@GetMapping(value = "/getAllSaleList")
	public Result getAllSaleList(@RequestParam(name="userId",required=true) String userId){
        String roleCode = roleService.getRoleCodeByUserId(userId);
        List<JSONObject> allSaleList;
        if("admin".equalsIgnoreCase(roleCode) || "finance".equalsIgnoreCase(roleCode)){
            allSaleList = cwjsPolicyInfoService.getAllSale();   //所有销售角色和管理员
        }else{
            allSaleList = cwjsPolicyInfoService.getAllSaleByUserId(userId);
            List<JSONObject> allSubordinate = cwjsPolicyInfoService.getAllSubordinate2(userId);
            if(!Check.isNull(allSubordinate)){
                allSaleList.addAll(allSubordinate);
            }
        }

        if(Check.isNull(allSaleList)){
            allSaleList = new ArrayList<>();
            SysUser sysUser = sysUserService.getById(userId);
            JSONObject jo = new JSONObject();
            jo.put("userId",sysUser.getId());
            jo.put("userName",sysUser.getRealname());

        }

		return Result.OK(allSaleList);
	}

	 /**
	  * 获取当前用户的公司、区域、和主体 修改
	  * @param userId
	  * @return
	  */
	 @ApiOperation(value="政策信息表-获取当前用户的公司、区域、和主体", notes="政策信息表-获取当前用户的公司、区域、和主体")
	 @GetMapping(value = "/queryAeraByUserId")
	 public Result<JSONArray> queryAeraByUserId(@RequestParam(name="userId",required=true) String userId) {
		 Result<JSONArray> result = new Result<>();
		 List<UserCompany> userCompany = userCompanyService.getAllByUserId(userId);
		 JSONArray res = new JSONArray();
		 userCompany.forEach(user -> {
			 List<CwjsCompanySubject> companySubjects = companySubjectMapper.queryAllSubjectName();
			 JSONObject jsonObject = new JSONObject();
			 jsonObject.put("UserCompany",userCompany);
			 jsonObject.put("companySubjects",companySubjects);
			 res.add(jsonObject);
		 });
		 result.setSuccess(true);
		 result.setResult(res);
		 return result;
	 }

	/**
	  *   添加
	 * @param cwjsPolicyInfo
	 * @return
	 */
	@ApiOperation(value="政策信息表-添加", notes="政策信息表-添加")
	@PostMapping(value = "/add")
	public Result<CwjsPolicyInfo> add(@RequestBody CwjsPolicyInfo cwjsPolicyInfo) {
		Result<CwjsPolicyInfo> result = new Result<>();
		try {

			String companySubjectName = cwjsPolicyInfo.getCompanySubjectName();
			String areaInfo = cwjsPolicyInfo.getAreaInfo();
			Integer companySubjectId = companySubjectMapper.queryIdBySubjectNameAndArea(companySubjectName, areaInfo);
			if(Check.isNull(companySubjectId)){
				return  Result.errorMsg("您选择的区域和公司主体系统不支持，请联系开发人员开放");
			}
			cwjsPolicyInfo.setCompanySubjectId(companySubjectId);
			List<CwjsCompanyApprovalUser> cwjsCompanyApprovalUsers = companyApprovalUserMapper.queryByCompanySubjectId(companySubjectId);
			if(Check.isNull(cwjsCompanyApprovalUsers)){
				return Result.errorMsg("此业务线暂时无审核人员，提交审核无效，请联系开发人员添加此区域主体的审核人员");
			}
			//普通销售，新增都是1，审核进度的人都是等级为0的审核人id
			cwjsCompanyApprovalUsers.forEach(cwjsCompanyApprovalUser -> {
				if(cwjsCompanyApprovalUser.getLevel() == 0){
					cwjsPolicyInfo.setApprovedStatus(1);
					cwjsPolicyInfo.setApprovedProgress(cwjsCompanyApprovalUser.getApprovalUserId());
				}
			});
			//如果满足有审核人员等于当前创建的人，
			//当前用户 和 选择的销售(创建人) 相同
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			if(user.getId().equals(cwjsPolicyInfo.getCreateUserId())){
				cwjsCompanyApprovalUsers.forEach(cwjsCompanyApprovalUser -> {
					if(cwjsCompanyApprovalUser.getApprovalUserId().equalsIgnoreCase(cwjsPolicyInfo.getCreateUserId())){
						CwjsCompanyApprovalUser approvalUserNext = companyApprovalUserMapper.queryByCompanySubjectIdAndLevel(companySubjectId, cwjsCompanyApprovalUser.getLevel()+1);
						if(Check.isNull(approvalUserNext)){
							cwjsPolicyInfo.setApprovedStatus(3);
							cwjsPolicyInfo.setApprovedProgress(null);
						}else{
							cwjsPolicyInfo.setApprovedStatus(2);
							cwjsPolicyInfo.setApprovedProgress(approvalUserNext.getApprovalUserId());
						}
					}
				});
			}



			if(cwjsPolicyInfo.getAdvancePay() == 1){
				cwjsPolicyInfo.setIsDianPay(null);
				cwjsPolicyInfo.setDianPayCompanyName(null);
				cwjsPolicyInfo.setDianPayCompanyRebateRate(null);
			}
			SysUser sysUser = sysUserService.getById(cwjsPolicyInfo.getCreateUserId());
			cwjsPolicyInfo.setCreateUserName(sysUser.getRealname());

			cwjsPolicyInfoService.save(cwjsPolicyInfo);
			JSONArray products = cwjsPolicyInfo.getPolicyProductName();
			List<CwjsPolicyProduct> policyProductList = new ArrayList<>();
			products.forEach(productName -> {
				CwjsPolicyProduct policyProduct = new CwjsPolicyProduct();
				policyProduct.setCreateUserId(cwjsPolicyInfo.getCreateUserId());
				policyProduct.setDelFlag(0);
				policyProduct.setPolicyProductName((String) productName);
				policyProduct.setPolicyId(cwjsPolicyInfo.getId());
				policyProductList.add(policyProduct);
			});
			cwjsPolicyProductService.saveBatch(policyProductList);
			//先给first发企业微信 -- 先注释掉
			JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(cwjsPolicyInfo.getApprovedProgress());
			StringBuilder text = new StringBuilder();
			text.append("您有一条销售政策需要审核，该客户为：");
			text.append(cwjsPolicyInfo.getCompanyName());
			text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
			corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	  *  编辑
	 * @param cwjsPolicyInfo
	 * @return
	 */
	@ApiOperation(value="政策信息表-编辑", notes="政策信息表-编辑")
	@PostMapping(value = "/edit")
	public Result<CwjsPolicyInfo> edit(@RequestBody CwjsPolicyInfo cwjsPolicyInfo) {
		Result<CwjsPolicyInfo> result = new Result<CwjsPolicyInfo>();
		CwjsPolicyInfo cwjsPolicyInfoEntity = cwjsPolicyInfoService.getById(cwjsPolicyInfo.getId());
		if(cwjsPolicyInfoEntity==null) {
			result.error500("未找到对应实体");
		}else {
			String companySubjectName = cwjsPolicyInfo.getCompanySubjectName();
			String areaInfo = cwjsPolicyInfo.getAreaInfo();
			Integer companySubjectId = companySubjectMapper.queryIdBySubjectNameAndArea(companySubjectName, areaInfo);
			if(Check.isNull(companySubjectId)){
				return  Result.errorMsg("您要修改的区域和公司主体系统不支持，请联系开发人员开放");
			}
			cwjsPolicyInfo.setCompanySubjectId(companySubjectId);
			//删除旧的产品
			cwjsPolicyProductService.deleteProductsByPolicyId(cwjsPolicyInfo.getId());
			//保存新的产品
			List<CwjsPolicyProduct> policyProductList = new ArrayList<>();
			JSONArray products = cwjsPolicyInfo.getPolicyProductName();
			products.forEach(productName -> {
				CwjsPolicyProduct policyProduct = new CwjsPolicyProduct();
				policyProduct.setCreateUserId(cwjsPolicyInfo.getCreateUserId());
				policyProduct.setDelFlag(0);
				policyProduct.setPolicyProductName((String) productName);
				policyProduct.setPolicyId(cwjsPolicyInfo.getId());
				policyProductList.add(policyProduct);
			});
			cwjsPolicyProductService.saveBatch(policyProductList);
			if(cwjsPolicyInfo.getAdvancePay() == 1){
				cwjsPolicyInfo.setIsDianPay(null);
				cwjsPolicyInfo.setDianPayCompanyName(null);
				cwjsPolicyInfo.setDianPayCompanyRebateRate(null);
			}
			cwjsPolicyInfoService.updatePolicyInfoById(cwjsPolicyInfo);
			result.success("修改成功!");
		}
		return result;
	}



	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@ApiOperation(value="政策信息表-通过id查询", notes="政策信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CwjsPolicyInfo> queryById(@RequestParam(name="id",required=true) Integer id) throws ParseException {
		Result<CwjsPolicyInfo> result = new Result<>();
		CwjsPolicyInfo cwjsPolicyInfo = cwjsPolicyInfoService.getById(id);
		Date startDate = DateUtils.parseDate(cwjsPolicyInfo.getPolicyStartDate(),"yyyy-MM-dd");
		cwjsPolicyInfo.setPolicyStartDate(DateUtils.formatDate(startDate,"yyyy年MM月dd日"));
		Date endDate = DateUtils.parseDate(cwjsPolicyInfo.getPolicyEndDate(),"yyyy-MM-dd");
		cwjsPolicyInfo.setPolicyEndDate(DateUtils.formatDate(endDate,"yyyy年MM月dd日"));
		List<CwjsPolicyProduct> policyProductList = cwjsPolicyProductService.queryProductsByPolicyId(id);
		JSONArray jsonArr = new JSONArray();
		policyProductList.forEach(policyProduct -> {
			jsonArr.add(policyProduct.getPolicyProductName());
		});
		cwjsPolicyInfo.setPolicyProductName(jsonArr);
		if(cwjsPolicyInfo==null) {
			result.error500("未找到对应实体");
		}else if(policyProductList==null){
			result.error500("此政策的没有绑定产品，或者已绑定的产品被删除");
		}else {
			result.setResult(cwjsPolicyInfo);
			result.setSuccess(true);
		}
		return result;
	}



	 /**
	  *   通过id删除
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="政策信息表-通过id删除", notes="政策信息表-通过id删除")
	 @DeleteMapping(value = "/delete")
	 public Result<?> delete(@RequestParam(name="id") String id) {
		 try {
			 cwjsPolicyInfoService.removeById(id);
		 } catch (Exception e) {
			 log.error("删除失败",e.getMessage());
			 return Result.error("删除失败!");
		 }
		 return Result.ok("删除成功!");
	 }

	 /**
	  *  批量删除
	  * @param ids
	  * @return
	  */
	 @ApiOperation(value="政策信息表-批量删除", notes="政策信息表-批量删除")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<CwjsPolicyInfo> deleteBatch(@RequestParam(name="ids") String ids) {
		 Result<CwjsPolicyInfo> result = new Result<>();
		 if(ids==null || "".equals(ids.trim())) {
			 result.error500("参数不识别！");
		 }else {
			 this.cwjsPolicyInfoService.removeByIds(Arrays.asList(ids.split(",")));
			 result.success("删除成功!");
		 }
		 return result;
	 }



  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<CwjsPolicyInfo> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              CwjsPolicyInfo cwjsPolicyInfo = JSON.parseObject(deString, CwjsPolicyInfo.class);
              queryWrapper = QueryGenerator.initQueryWrapper(cwjsPolicyInfo, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<CwjsPolicyInfo> pageList = cwjsPolicyInfoService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "政策信息表列表");
      mv.addObject(NormalExcelConstants.CLASS, CwjsPolicyInfo.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("政策信息表列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CwjsPolicyInfo> listCwjsPolicyInfos = ExcelImportUtil.importExcel(file.getInputStream(), CwjsPolicyInfo.class, params);
              cwjsPolicyInfoService.saveBatch(listCwjsPolicyInfos);
              return Result.ok("文件导入成功！数据行数:" + listCwjsPolicyInfos.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }


  @GetMapping(value = "/weiXinNotice")
  public Result weiXinNotice(){
	  CwjsPolicyInfo cwjsPolicyInfo = new CwjsPolicyInfo();
	  cwjsPolicyInfo.setApprovedStatus(1);
	  //待审核的状态的 政策
	  List<CwjsPolicyInfo> cwjsPolicyInfoListStatus1 = cwjsPolicyInfoService.queryPageList(cwjsPolicyInfo);
	  cwjsPolicyInfoListStatus1.forEach(cwjsPolicy -> {
		  JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(cwjsPolicy.getApprovedProgress());
		  StringBuilder text = new StringBuilder();
		  text.append("您有一条销售政策需要审核，该客户为：");
		  text.append(cwjsPolicy.getCompanyName());
		  text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
		  corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
	  });

	  //审核中的状态的政策
	  cwjsPolicyInfo.setApprovedStatus(2);
	  List<CwjsPolicyInfo> cwjsPolicyInfoListStatus2 = cwjsPolicyInfoService.queryPageList(cwjsPolicyInfo);
	  cwjsPolicyInfoListStatus2.forEach(cwjsPolicy -> {
		  JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(cwjsPolicy.getApprovedProgress());
		  StringBuilder text = new StringBuilder();
		  text.append("您有一条销售政策需要审核，该客户为：");
		  text.append(cwjsPolicy.getCompanyName());
		  text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
		  corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
	  });

	  //审核拒绝的状态的政策
	  cwjsPolicyInfo.setApprovedStatus(4);
	  List<CwjsPolicyInfo> cwjsPolicyInfoListStatus4 = cwjsPolicyInfoService.queryPageList(cwjsPolicyInfo);
	  cwjsPolicyInfoListStatus4.forEach(cwjsPolicy -> {
		  JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(cwjsPolicy.getCreateUserId());
		  StringBuilder text = new StringBuilder();
		  text.append("您有一条销售政策审核未通过，该客户为：");
		  text.append(cwjsPolicy.getCompanyName());
		  text.append("，请及时登录助手平台-销售政策页面进行政策修改，谢谢！");
		  corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
	  });

  	return Result.OK();
  }

}
