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.commons.lang3.StringUtils;
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") Integer id,
	 							@RequestParam(name="type") Integer type,
								  @RequestParam(name="userId") String userId,
								@RequestParam(name="approvalContent",required=false) String approvalContent){

		CwjsPolicyInfo cwjsPolicyInfo = cwjsPolicyInfoService.getById(id);
		 if(cwjsPolicyInfo==null) {
			 return Result.error("政策不存在或已被删除，请重新选择要审核的政策。");
		 }
		 //获取 公司主题
		 Integer companySubjectId = cwjsPolicyInfo.getCompanySubjectId();

		 //当前政策审核人
		 String approvalUser = cwjsPolicyInfo.getApprovedProgress();

		 //政策所属销售的部门 和 上级
		 JSONObject examineUser = cwjsPolicyInfoMapper.getUserLeaderAndDirectorByRoleName(cwjsPolicyInfo.getSaleId(),"分公司总经理");
		 String firstAudit = "";//第一次审核人

		 // 提交 - 待审核
		 //华北==> 法务  其他===> 销售上级
		 if(type == 1){
		 	if (cwjsPolicyInfo.getAdvancePay() == 0 && cwjsPolicyInfo.getCustomerFlag() == 0){
				//第一次审核人 -- 法务(法务有多个用户 无法判断审核人 所以 法务审核人为 角色code legalAffairs 占位)
				//firstAudit = examineUser.getString("directorId");
				firstAudit = "legalAffairs";
			}else {
				//销售的 上级
				firstAudit = examineUser.getString("leaderId");
			}

			 cwjsPolicyInfo.setApprovedStatus(1);
			 cwjsPolicyInfo.setApprovedProgress(firstAudit);


			 if(StringUtils.equals(firstAudit,"legalAffairs")){
				 List<JSONObject> legalUserList = cwjsPolicyInfoService.getLegalAffairsUsers();
				 for (JSONObject jsonObject : legalUserList) {
					 JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(jsonObject.getString("userId"));
					 StringBuilder text = new StringBuilder();
					 text.append("您有一条销售政策需要审核，该客户为：");
					 text.append(cwjsPolicyInfo.getCompanyName());
					 text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
					 corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
				 }
			 } else {
				 JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(cwjsPolicyInfo.getApprovedProgress());
				 StringBuilder text = new StringBuilder();
				 text.append("您有一条销售政策需要审核，该客户为：");
				 text.append(cwjsPolicyInfo.getCompanyName());
				 text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
				 corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
			 }

			 //添加记录
			 CwjsPolicyApprovalLog policyApprovalLog = new CwjsPolicyApprovalLog();
			 policyApprovalLog.setPolicyId(cwjsPolicyInfo.getId());
			 policyApprovalLog.setCreateUserId(cwjsPolicyInfo.getCreateUserId());
			 policyApprovalLog.setApprovalStatus(0);
			 policyApprovalLog.setApprovalContent("提交政策");
			 policyApprovalLog.setCreateTime(new Date());
			 policyApprovalLogService.save(policyApprovalLog);

		}
		 //审核通过 是不是终审，不是就给当前的下一个人发企业微信
		 if(type == 2){

			 //第一个审核人 - 法务
		 	if(approvalUser.equals("legalAffairs")){
				cwjsPolicyInfo.setApprovedStatus(2);
				cwjsPolicyInfo.setApprovedProgress(examineUser.getString("leaderId"));	//设置一下个审核人员  上级
		 	}


		 	//第二个审核人 = 上级
		 	if(approvalUser.equals(examineUser.getString("leaderId"))){
		 		if(examineUser.getString("departName").contains("渠道")){
					cwjsPolicyInfo.setApprovedStatus(3);
					cwjsPolicyInfoService.updateById(cwjsPolicyInfo);

					/**
					 * 终审通过后 添加 起始时间
					 */
					reportSettlementService.cwjsPRofit(cwjsPolicyInfo);
					return Result.successMsg("审核通过",cwjsPolicyInfo);
				}

				if(examineUser.getString("departName").contains("销售")){
					//华北 ---> 自动转老板
					if (companySubjectId == 1){
						//查询 是否符合条件
						List<JSONObject> autoConveryList = cwjsPolicyInfoMapper.selAutoConveryInfo(cwjsPolicyInfo.getAccountingPeriod(),cwjsPolicyInfo.getMediaType(),
								cwjsPolicyInfo.getAdvancePay(),cwjsPolicyInfo.getRebateType(),cwjsPolicyInfo.getRebateRate());
						if (!Check.isNull(autoConveryList)){
							cwjsPolicyInfoService.automaticConveyBossExamine(cwjsPolicyInfo);
							cwjsPolicyInfoService.updateById(cwjsPolicyInfo);
							log.info("-----自动转老板");
							return Result.successMsg("审核通过",cwjsPolicyInfo);
						}else {
							//结束
							cwjsPolicyInfo.setApprovedStatus(3);
							cwjsPolicyInfoService.updateById(cwjsPolicyInfo);

							/**
							 * 终审通过后 添加 起始时间
							 */
							reportSettlementService.cwjsPRofit(cwjsPolicyInfo);
							return Result.successMsg("审核通过",cwjsPolicyInfo);

						}
					}else {
						// 下一步审核 分公司总经理
						cwjsPolicyInfo.setApprovedStatus(2);
						cwjsPolicyInfo.setApprovedProgress(examineUser.getString("directorId"));	//设置一下个审核人员  分公司总经理

					}
				}

			}

		 	//第三个审核人- 分公司总经理
			 if(approvalUser.equals(examineUser.getString("directorId"))){
				 cwjsPolicyInfo.setApprovedStatus(3);
				 cwjsPolicyInfoService.updateById(cwjsPolicyInfo);


				 /**
				  * 终审通过后 添加 起始时间
				  */
				 reportSettlementService.cwjsPRofit(cwjsPolicyInfo);
				 return Result.successMsg("审核通过",cwjsPolicyInfo);
			 }

			 //老板
			 if (approvalUser.equals(userId) && userId.equals("80e747cdea6f41dbbc8cde23046fd4e0")){
				 cwjsPolicyInfo.setApprovedStatus(3);

				 /**
				  * 终审通过后 添加 起始时间
				  */
				 reportSettlementService.cwjsPRofit(cwjsPolicyInfo);
				 return Result.successMsg("审核通过",cwjsPolicyInfo);
			 }




			 JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(cwjsPolicyInfo.getApprovedProgress());
			 StringBuilder text = new StringBuilder();
			 text.append("您有一条销售政策需要审核，该客户为：");
			 text.append(cwjsPolicyInfo.getCompanyName());
			 text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
			 corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());

			CwjsPolicyApprovalLog policyApprovalLog = new CwjsPolicyApprovalLog();
			policyApprovalLog.setPolicyId(id);
			policyApprovalLog.setCreateUserId(userId);
			policyApprovalLog.setApprovalStatus(0);
			 policyApprovalLog.setApprovalContent(approvalContent);
			 policyApprovalLog.setCreateTime(new Date());
			policyApprovalLogService.save(policyApprovalLog);

		}
	 	if(type == 3){	//审核拒绝	给申请人发企业微信
			cwjsPolicyInfo.setApprovedStatus(4);

			CwjsPolicyApprovalLog policyApprovalLog = new CwjsPolicyApprovalLog();
			//老板
			if (approvalUser.equals(userId) && userId.equals("80e747cdea6f41dbbc8cde23046fd4e0")){
				policyApprovalLog.setApprovalStatus(3);

			}else {
				policyApprovalLog.setApprovalStatus(1);
			}

			policyApprovalLog.setPolicyId(id);
			policyApprovalLog.setCreateUserId(userId);
			policyApprovalLog.setApprovalContent(approvalContent);
			policyApprovalLog.setCreateTime(new Date());
			policyApprovalLogService.save(policyApprovalLog);


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

	 	//手动-转领导审批 只有审核人是最后一个人的时候 才可以转领导
	 	if (type == 4){
			// 最后一个审核人员
			if (!approvalUser.equals(examineUser.getString("leaderId")) && !approvalUser.equals(examineUser.getString("directorId"))){
				return Result.errorMsg("当前审核人不是最后一个审核人员，无法转领导审批。");
			}

			cwjsPolicyInfoService.automaticConveyBossExamine(cwjsPolicyInfo);
		}

		cwjsPolicyInfoService.updateById(cwjsPolicyInfo);
	 	return Result.successMsg(type ==  3 ? "审核拒绝" : "审核通过",cwjsPolicyInfo);
	 }


	 @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);
			cwjsPolicyInfo.setSaleIds(userIds);

			//分公司总经理
		}else if("CompanyManager".equalsIgnoreCase(roleCode)){
			//自己所属区域
			//查询 用户 所属区域 公司主题id
			Integer subjectId = cwjsPolicyInfoService.getCompanySubjectByUserId(userId);
			cwjsPolicyInfo.setCompanySubjectId(subjectId);

			//法务
		}else if("legalAffairs".equalsIgnoreCase(roleCode)){
			//法务 查看
			cwjsPolicyInfo.setAdvancePay(0); //预付 -否
			cwjsPolicyInfo.setCustomerFlag(0);// 老客户 -否

		}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 bossContent = policyApprovalLogMapper.getBossOneByPolicyId(cwjsPolicy.getId(),3);	// 查询 老板 审核意见 最新的一条
			cwjsPolicy.setTheBossContent(Check.isNull(bossContent) ? "" : bossContent.getApprovalContent());

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


			JSONObject examineUser = new JSONObject();
			String directorUserId = "";
			//主体为1 为 华北
			if (cwjsPolicy.getCompanySubjectId() == 1){
				//查询 该销售 所属的审核人员
				//华北审核人员 - 法务==>销售总监（销售上级）==>手动转领导/自动转领导
				examineUser = cwjsPolicyInfoMapper.getUserLeaderAndDirectorByRoleName(cwjsPolicy.getSaleId(),"法务");
				directorUserId = examineUser.getString("leaderId");
			}else {
				//查询 该销售 所属的审核人员
				//华南审核人员 - 销售总监（销售上级） ==> 分公司经理 ==>转领导
				examineUser = cwjsPolicyInfoMapper.getUserLeaderAndDirectorByRoleName(cwjsPolicy.getSaleId(),"分公司总经理");
				directorUserId = examineUser.getString("directorId");

			}

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

						if(examineUser.getString("departName").contains("渠道")){
							cwjsPolicy.setTheBossRight("yes");
						}

						if(examineUser.getString("departName").contains("销售")){
							//华北
							if (cwjsPolicy.getCompanySubjectId() == 1){
								//查询 是否符合自动转审条件
								List<JSONObject> autoConveryList = cwjsPolicyInfoMapper.selAutoConveryInfo(cwjsPolicy.getAccountingPeriod(),cwjsPolicy.getMediaType(),
										cwjsPolicy.getAdvancePay(),cwjsPolicy.getRebateType(),cwjsPolicy.getRebateRate());
								if (Check.isNull(autoConveryList)){
									cwjsPolicy.setTheBossRight("yes");
								}
							}
						}
					}
				}

			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){
				if(StringUtils.equals(cwjsPolicy.getApprovedProgress(),userId)
						|| (StringUtils.equals(cwjsPolicy.getApprovedProgress(),"legalAffairs") && StringUtils.equals(roleCode,"legalAffairs"))){
					stringBuilder.append("审核通过").append("|").append("审核拒绝").append("|");
				}

			}
			//待审核
			if (cwjsPolicy.getApprovedStatus() == 2){
				if(StringUtils.equals(cwjsPolicy.getApprovedProgress(),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);


			//政策所属销售的部门 和 上级
			JSONObject examineUser = cwjsPolicyInfoMapper.getUserLeaderAndDirectorByRoleName(cwjsPolicyInfo.getSaleId(),"分公司总经理");
			String firstAudit = "";//第一次审核人

			//普通销售，新增都是1，审核进度的人都是等级为0的审核人i
			// 预付-否 && 老客户-否
			if (cwjsPolicyInfo.getAdvancePay() == 0 && cwjsPolicyInfo.getCustomerFlag() == 0){
				//第一次审核人 -- 法务(法务有多个用户 无法判断审核人 所以 法务审核人为 角色code legalAffairs 占位)
				//firstAudit = examineUser.getString("directorId");
				cwjsPolicyInfo.setApprovedStatus(1);
				firstAudit = "legalAffairs";
			}else {
				//销售的 上级
				firstAudit = examineUser.getString("leaderId");
			}

			cwjsPolicyInfo.setApprovedStatus(1);
			cwjsPolicyInfo.setApprovedProgress(firstAudit);


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

			log.info("政策创建时间是--------------{}",cwjsPolicyInfo.getCreateTime());

			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);


			//发企业微信   法务有两个用户
			if (StringUtils.equals(cwjsPolicyInfo.getApprovedProgress(),"legalAffairs")){
				List<JSONObject> legalUserList = cwjsPolicyInfoService.getLegalAffairsUsers();
				for (JSONObject jsonObject : legalUserList) {
					JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(jsonObject.getString("userId"));
					StringBuilder text = new StringBuilder();
					text.append("您有一条销售政策需要审核，该客户为：");
					text.append(cwjsPolicyInfo.getCompanyName());
					text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
					corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
				}
			}else {
				JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(cwjsPolicyInfo.getApprovedProgress());
				StringBuilder text = new StringBuilder();
				text.append("您有一条销售政策需要审核，该客户为：");
				text.append(cwjsPolicyInfo.getCompanyName());
				text.append("，请及时登录助手平台-销售政策页面进行审核，谢谢！");
				corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId,text.toString());
			}

			//添加记录
			CwjsPolicyApprovalLog policyApprovalLog = new CwjsPolicyApprovalLog();
			policyApprovalLog.setPolicyId(cwjsPolicyInfo.getId());
			policyApprovalLog.setCreateUserId(cwjsPolicyInfo.getCreateUserId());
			policyApprovalLog.setApprovalStatus(0);
			policyApprovalLog.setApprovalContent("创建政策");
			policyApprovalLog.setCreateTime(new Date());

			log.info("时间是===========1========={}",new Date());
			log.info("时间是==========2=========={}",DateUtils.formatDateTime());


			policyApprovalLogService.save(policyApprovalLog);

			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);
			}

			cwjsPolicyInfo.setCreateUserName(cwjsPolicyInfoEntity.getCreateUserName());
			cwjsPolicyInfoService.updatePolicyInfoById(cwjsPolicyInfo);

			//添加记录
			CwjsPolicyApprovalLog policyApprovalLog = new CwjsPolicyApprovalLog();
			policyApprovalLog.setPolicyId(cwjsPolicyInfo.getId());
			policyApprovalLog.setCreateUserId(cwjsPolicyInfo.getCreateUserId());
			policyApprovalLog.setApprovalStatus(0);
			policyApprovalLog.setApprovalContent("修改政策");
			policyApprovalLog.setCreateTime(new Date());
			policyApprovalLogService.save(policyApprovalLog);

			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();
  }


	 @ApiOperation(value="查询政策审核记录", notes="查询政策审核记录")
	 @GetMapping(value = "/getPolicyApprovalLogByPolicyId")
	 public Result getPolicyApprovalLogByPolicyId(@RequestParam(name="policyId") Integer policyId) {
		 return cwjsPolicyInfoService.getPolicyApprovalLogByPolicyId(policyId);
	 }







 }
