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

import cn.com.ctop.common.module.entity.UserCompany;
import cn.com.ctop.common.module.mapper.MailLogMapper;
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.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
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.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.ctop.finance.policy.entity.CwjsCompanySubject;
import org.jeecg.ctop.finance.policy.entity.CwjsPolicyApprovalLog;
import org.jeecg.ctop.finance.policy.entity.CwjsPolicyInfo;
import org.jeecg.ctop.finance.policy.entity.CwjsPolicyProduct;
import org.jeecg.ctop.finance.policy.entity.ExportCwjsPolicyPojo;
import org.jeecg.ctop.finance.policy.mapper.CwjsCompanyApprovalUserMapper;
import org.jeecg.ctop.finance.policy.mapper.CwjsCompanySubjectMapper;
import org.jeecg.ctop.finance.policy.mapper.CwjsPolicyApprovalLogMapper;
import org.jeecg.ctop.finance.policy.mapper.CwjsPolicyInfoMapper;
import org.jeecg.ctop.finance.policy.mapper.CwjsSaleAssistantInfoMapper;
import org.jeecg.ctop.finance.policy.service.ICwjsCompanySubjectService;
import org.jeecg.ctop.finance.policy.service.ICwjsPolicyApprovalLogService;
import org.jeecg.ctop.finance.policy.service.ICwjsPolicyInfoService;
import org.jeecg.ctop.finance.policy.service.ICwjsPolicyProductService;
import org.jeecg.ctop.finance.policy.service.ICwjsSaleAssistantInfoService;
import org.jeecg.ctop.finance.policy.utils.Check;
import org.jeecg.ctop.finance.policy.utils.ListPageUtil;
import org.jeecg.ctop.finance.settlement.entity.vo.SettlementFileParamsVo;
import org.jeecg.ctop.finance.settlement.service.serviceImpl.ReportSettlementServiceImpl;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecgframework.poi.excel.ExcelExportUtil;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 政策信息表
 *
 * @author jeecg-boot master
 * @version V1.0
 * @date 2021-07-27
 */
@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);
        }

    }

    @Autowired
    private ICwjsCompanySubjectService cwjsCompanySubjectService;

    /**
     * 审核-master
     * id 政策id
     * type 类型
     * userId 用户id
     * approvalContent 审核内容
     *
     * @return
     */
    @PostMapping(value = "/policyApproval")
    public Result policyApproval(@RequestBody JSONObject object
                                 //@RequestParam(name="id") Integer id,
                                 //@RequestParam(name="type") Integer type,
                                 //@RequestParam(name="userId") String userId,
                                 //@RequestParam(name="approvalContent",required=false) String approvalContent
    ) {

        Integer id = object.getInteger("id");
        Integer type = object.getInteger("type");
        String userId = object.getString("userId");
        String approvalContent = object.getString("approvalContent");
        CwjsPolicyInfo cwjsPolicyInfo = cwjsPolicyInfoService.getById(id);

        if (cwjsPolicyInfo == null) {
            return Result.error("政策不存在或已被删除，请重新选择要审核的政策。");
        }
        //当前政策审核人
        String approvalUser = cwjsPolicyInfo.getApprovedProgress();
        //策略审核人不是 法务 和 政审时，必须 登录人和审核人一致
        if (!Check.isNull(approvalUser) && !"legalAffairs".equals(approvalUser) && !"1747433221403979778".equals(approvalUser)) {
            if (!Check.isNull(userId) && !userId.equals(approvalUser)) {
                return Result.error("该政策已被审核，请刷新政策列表");
            }

        }
        cwjsPolicyInfo.setLoginUserId(userId);
        cwjsPolicyInfo.setApprovalContent(approvalContent);
        //获取 公司主题
        Integer companySubjectId = cwjsPolicyInfo.getCompanySubjectId();

        CwjsCompanySubject companySubject = cwjsCompanySubjectService.getById(companySubjectId);
        cwjsPolicyInfo.setCompanyId(companySubject.getCompanyId());

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

        String sendFlag = "1";
        // 提交 - 待审核
        //华北==> 法务  其他===> 销售上级
        if (type == 1) {
            if (cwjsPolicyInfo.getAdvancePay() == 0 && cwjsPolicyInfo.getCustomerFlag() == 0) {
                //第一次审核人 -- 法务(法务有多个用户 无法判断审核人 所以 法务审核人为 角色code legalAffairs 占位)
                //firstAudit = examineUser.getString("directorId");
                firstAudit = "legalAffairs";
            } else {
                //查询创建人角色 -- 自己创建的
                String createUserRole = roleService.getRoleCodeByUserId(cwjsPolicyInfo.getCreateUserId());
                if (StringUtils.equals("saleDirector", createUserRole)) {
                    firstAudit = cwjsPolicyInfo.getCreateUserId();
                } 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")) {
                //查询创建人角色 -- 自己创建的
                String createUserRole = roleService.getRoleCodeByUserId(cwjsPolicyInfo.getCreateUserId());
                if (StringUtils.equals("saleDirector", createUserRole)) {
                    cwjsPolicyInfo.setApprovedStatus(1);
                    cwjsPolicyInfo.setApprovedProgress(cwjsPolicyInfo.getCreateUserId());    //设置一下个审核人员  是自己
                } else {
                    cwjsPolicyInfo.setApprovedStatus(1);
                    cwjsPolicyInfo.setApprovedProgress(examineUser.getString("leaderId"));    //设置一下个审核人员  上级
                }
            }

            //查询审核人角色
            String roleCode = roleService.getRoleCodeByUserId(approvalUser);

            //第二个审核人 = 上级 = 销售总监
            //if(approvalUser.equals(examineUser.getString("leaderId"))){
            //审核人角色为销售总监
            if (StringUtils.equals("saleDirector", roleCode)) {
                if (examineUser.getString("departName").contains("渠道")) {
                    cwjsPolicyInfo.setApprovedStatus(3);
                    cwjsPolicyInfoService.updateById(cwjsPolicyInfo);
                    /**
                     * 终审通过后 添加 起始时间
                     */
                    reportSettlementService.cwjsPRofit(cwjsPolicyInfo);
                    return Result.successMsg("审核通过", cwjsPolicyInfo);
                }
                //丁兆明：b161b7d9793942f980dbfe8c931cd1b0
                if (examineUser.getString("departName").contains("销售") && !"b161b7d9793942f980dbfe8c931cd1b0".equals(userId)) {
                    //华北 ---> 通过转政审
                    if (cwjsPolicyInfo.getCompanyId().equals("d57fecdcf7a94d009736d9c850731582")) {
                        //审核人 如果是 赵旺 则需要单独处理 转审上级 丁兆明
                        //查询审核人 上级
  /*                      JSONObject jsonObject = cwjsPolicyInfoMapper.getUserLeaderByUserId(cwjsPolicyInfo.getApprovedProgress());
                        if (!Check.isNull(jsonObject) && (StringUtils.equals(cwjsPolicyInfo.getApprovedProgress(), "00d630a129e4487cba5427788a1f08ce")
                                || StringUtils.equals(cwjsPolicyInfo.getApprovedProgress(), "7fb2684c348341d193727e791c75dbeb"))) {
                            // 下一步审核人
                            cwjsPolicyInfo.setApprovedStatus(1);
                            cwjsPolicyInfo.setApprovedProgress(jsonObject.getString("leaderId"));    //设置一下个审核人员

                        } else {*/
                        /*    List<SysUser> users = sysUserService.getUserListByRoleId("4b68d4e66cbd4ad018d33ddc48880db7");
                            if (!Check.isNull(users)) {
                            }*/
                        sendFlag = "2";
                        cwjsPolicyInfo.setApprovedStatus(1);
                        cwjsPolicyInfo.setApprovedProgress("1747433221403979778");    //设置政策审核角色人员 固定为 郭艳玲（政审）
                        cwjsPolicyInfoService.updateById(cwjsPolicyInfo);
//                        }
                    } else {
                        // 下一步审核 分公司总经理
                        cwjsPolicyInfo.setApprovedStatus(1);
                        cwjsPolicyInfo.setApprovedProgress(examineUser.getString("directorId"));    //设置一下个审核人员  分公司总经理
                    }
                }
                //审核人角色为 政审角色，将一下个审核人置位 丁兆明
            } else if (StringUtils.equals("policyReview", roleCode)) {
                cwjsPolicyInfo.setApprovedStatus(1);
                cwjsPolicyInfo.setApprovedProgress("b161b7d9793942f980dbfe8c931cd1b0");
                cwjsPolicyInfoService.updateById(cwjsPolicyInfo);
            }


            //丁兆明 : b161b7d9793942f980dbfe8c931cd1b0,审核通过直接到老板或者结束
            if (approvalUser.equals(userId) && "b161b7d9793942f980dbfe8c931cd1b0".equals(userId)) {

                List<JSONObject> autoConveryList = null;
                //老客+有账期，不过老板审核
                if (!(cwjsPolicyInfo.getCustomerFlag() == 1 && !Check.isNull(cwjsPolicyInfo.getAccountingPeriod()))) {
                    //查询 是否符合条件
                    autoConveryList = cwjsPolicyInfoMapper.selAutoConveryInfo(cwjsPolicyInfo.getAccountingPeriod(), cwjsPolicyInfo.getMediaType(),
                            cwjsPolicyInfo.getAdvancePay(), cwjsPolicyInfo.getRebateType(), cwjsPolicyInfo.getRebateRate());
                }
                if (!Check.isNull(autoConveryList)) {
                    //符合条件，自动转老板
                    cwjsPolicyInfoService.automaticConveyBossExamine(cwjsPolicyInfo);
                    cwjsPolicyInfoService.updateById(cwjsPolicyInfo);
                    return Result.successMsg("审核通过", cwjsPolicyInfo);
                } else {
                    //不符合，流程结束
                    cwjsPolicyInfo.setApprovedStatus(3);
                    cwjsPolicyInfoService.updateById(cwjsPolicyInfo);
                    /**
                     * 终审通过后 添加 起始时间
                     */
                    reportSettlementService.cwjsPRofit(cwjsPolicyInfo);
                    return Result.successMsg("审核通过", cwjsPolicyInfo);
                }
            }
            //第三个审核人- 分公司总经理
            if (approvalUser.equals(examineUser.getString("directorId"))) {
                cwjsPolicyInfo.setApprovedStatus(3);
                cwjsPolicyInfoService.updateById(cwjsPolicyInfo);
                /**
                 * 终审通过后 添加 起始时间
                 */
                reportSettlementService.cwjsPRofit(cwjsPolicyInfo);
                return Result.successMsg("审核通过", cwjsPolicyInfo);
            }

            //老板:4aba62011120ac565c7f2b9f8f4aa96b
            if (approvalUser.equals(userId) && userId.equals("4aba62011120ac565c7f2b9f8f4aa96b")) {
                cwjsPolicyInfo.setApprovedStatus(3);
                cwjsPolicyInfoService.updateById(cwjsPolicyInfo);

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

            if ("2".equals(sendFlag)) {
                //政策审核 发送消息到 郭艳玲（16eab477cd7a43538c1049d9678753e0） 李域（2dfcf0fb1ef143298e2db3d5af1271de）
                sendMsg("16eab477cd7a43538c1049d9678753e0", cwjsPolicyInfo.getCompanyName());
                sendMsg("2dfcf0fb1ef143298e2db3d5af1271de", cwjsPolicyInfo.getCompanyName());
            } 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(id);
            policyApprovalLog.setCreateUserId(userId);
            policyApprovalLog.setApprovalStatus(0);
            policyApprovalLog.setApprovalContent(Check.isNull(approvalContent) ? "审核通过" : approvalContent);
            policyApprovalLog.setCreateTime(new Date());
            policyApprovalLogService.save(policyApprovalLog);

        }
        if (type == 3) {    //审核拒绝	给申请人发企业微信
            cwjsPolicyInfo.setApprovedStatus(4);
            CwjsPolicyApprovalLog policyApprovalLog = new CwjsPolicyApprovalLog();
            policyApprovalLog.setApprovalStatus(1);
            policyApprovalLog.setPolicyId(id);
            policyApprovalLog.setCreateUserId(userId);
            policyApprovalLog.setApprovalContent(Check.isNull(approvalContent) ? "审核拒绝" : 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) {
            cwjsPolicyInfoService.automaticConveyBossExamine(cwjsPolicyInfo);
        }

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

    }

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

    @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) || "financialReview".equalsIgnoreCase(roleCode) || "policyReview".equalsIgnoreCase(roleCode)) {

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

            //分公司总经理
        } else if ("CompanyManager".equalsIgnoreCase(roleCode)) {
            //自己所属区域
            //查询 用户 所属区域 公司主题id
            List<Integer> subjectId = cwjsPolicyInfoService.getCompanySubjectByUserId(userId);
            cwjsPolicyInfo.setCompanySubjectIds(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);
        }

        // 1：待审核 2:审核中 3：审核通过4：审核拒绝 5-作废 默认不显示作废
        if (Check.isNull(cwjsPolicyInfo.getApprovedStatus())) {
            cwjsPolicyInfo.setStatusList(Arrays.asList(1, 2, 3, 4));
        } else {
            cwjsPolicyInfo.setStatusList(Arrays.asList(cwjsPolicyInfo.getApprovedStatus()));
        }


        //查询政策
        List<CwjsPolicyInfo> cwjsPolicyInfoList = cwjsPolicyInfoService.queryPageList(cwjsPolicyInfo);
        if (Check.isNull(cwjsPolicyInfoList)) {
            return Result.errorMsg("暂无政策。");
        }
        //时间 降序
        Collections.sort(cwjsPolicyInfoList, Comparator.comparing(CwjsPolicyInfo::getCreateTime).reversed());

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

        //查询政策审核人员
//        List<SysUser> users = sysUserService.getUserListByRoleId("4b68d4e66cbd4ad018d33ddc48880db7");
        cwjsPolicyInfos.forEach(cwjsPolicy -> {
            CwjsPolicyApprovalLog log = policyApprovalLogMapper.getOneByPolicyId(cwjsPolicy.getId(), 1);    // 查询 被拒 审核意见 最新的一条
            cwjsPolicy.setApprovalContent(Check.isNull(log) ? "" : log.getApprovalContent());

            CwjsPolicyApprovalLog forwardContent = policyApprovalLogMapper.getOneByPolicyId(cwjsPolicy.getId(), 2);    // 查询 转发领导的理由 最新的一条
            cwjsPolicy.setTheForwardingBossContent(Check.isNull(forwardContent) ? "" : forwardContent.getApprovalContent());

            CwjsPolicyApprovalLog bossContent = policyApprovalLogMapper.getBossOneByPolicyId(cwjsPolicy.getId());    // 查询 老板审核意见 最新的一条
            if (!Check.isNull(bossContent)) {
                cwjsPolicy.setTheBossContent(StringUtils.equals("终审通过", bossContent.getApprovalContent()) ? "-" : bossContent.getApprovalContent());
            } else {
                cwjsPolicy.setTheBossContent("-");
            }

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


            CwjsPolicyApprovalLog mediaContent = policyApprovalLogMapper.getOneByPolicyMeidaInfo(cwjsPolicy.getId());    // 查询 政策审核角色 审核意见 最新的一条
            cwjsPolicy.setMeidiaAffairsContent(Check.isNull(mediaContent) ? "" : mediaContent.getApprovalContent());

            JSONObject examineUser = new JSONObject();
            String directorUserId = "";

            //角色
            String createRoleCode = roleService.getRoleCodeByUserId(cwjsPolicy.getCreateUserId());

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

                if (StringUtils.equals("saleDirector", createRoleCode)) {
                    directorUserId = cwjsPolicy.getCreateUserId();
                } else if (StringUtils.equals("00d630a129e4487cba5427788a1f08ce", examineUser.getString("leaderId")) ||
                        StringUtils.equals("7fb2684c348341d193727e791c75dbeb", examineUser.getString("leaderId"))) {
                    //当前审核人是 zhaowang 则下一步审核人是 dingzhaoming
                    directorUserId = "b161b7d9793942f980dbfe8c931cd1b0";

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

            }

            cwjsPolicy.setTheBossRight("no");
            //丁兆明 ： 状态不为3 审核通过  && 状态不为4 审核拒绝 则显示 转领导审批
            if (cwjsPolicy.getApprovedStatus() != 3 && cwjsPolicy.getApprovedStatus() != 4 && "b161b7d9793942f980dbfe8c931cd1b0".equals(cwjsPolicy.getApprovedProgress()) && userId.equals(cwjsPolicy.getApprovedProgress())) {
                cwjsPolicy.setTheBossRight("yes");
            }
            /*
            if () {
                if (StringUtils.equals(cwjsPolicy.getApprovedProgress(), directorUserId) && directorUserId.equals(userId)
                        && !"4aba62011120ac565c7f2b9f8f4aa96b".equals(userId)) {

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

                    if (examineUser.getString("departName").contains("销售")) {
                        //华北
                        if (cwjsPolicy.getCompanyId().equals("d57fecdcf7a94d009736d9c850731582")) {
                            //查询 是否符合自动转审条件
                            List<JSONObject> autoConveryList = cwjsPolicyInfoMapper.selAutoConveryInfo(cwjsPolicy.getAccountingPeriod(), cwjsPolicy.getMediaType(),
                                    cwjsPolicy.getAdvancePay(), cwjsPolicy.getRebateType(), cwjsPolicy.getRebateRate());
                            if (Check.isNull(autoConveryList)) {
                                cwjsPolicy.setTheBossRight("yes");
                            }
                        } else {
                            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"))
                        || "policyReview".equals(roleCode) && "1747433221403979778".equals(cwjsPolicy.getApprovedProgress())
                ) {
                    stringBuilder.append("审核通过").append("|").append("审核拒绝").append("|");
                }

            }
            //审核中
            if (cwjsPolicy.getApprovedStatus() == 2) {
                if (StringUtils.equals(cwjsPolicy.getApprovedProgress(), userId)) {
                    stringBuilder.append("审核通过").append("|").append("审核拒绝").append("|");
                }
            }

            //审核通过
            if (cwjsPolicy.getApprovedStatus() == 3) {
                //有 销售-助理 关联的人员 都可以 作废
                if (!"admin".equalsIgnoreCase(roleCode) && !"finance".equalsIgnoreCase(roleCode)) {
                    List<String> saleOrAssis = cwjsSaleAssistantInfoService.getCwSaleAndAssistantListStr(userId);
                    if (saleOrAssis.contains(cwjsPolicy.getSaleId()) || saleOrAssis.contains(cwjsPolicy.getCreateUserId())) {
                        stringBuilder.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);


            //查询创建人角色
            String roleCode = roleService.getRoleCodeByUserId(cwjsPolicyInfo.getCreateUserId());


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

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

                //销售总监创建
            } else if (StringUtils.equals(roleCode, "saleDirector")) {
                //审核人是 自己
                firstAudit = cwjsPolicyInfo.getCreateUserId();
            } 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());

            cwjsPolicyInfo.setCreateTime(new Date());
            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());
            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;
    }


    @GetMapping(value = "/queryInfo")
    public Result<Object> queryInfo(String advertiserName, String productName, String type) {
        try {
            if (Check.isNull(advertiserName) || Check.isNull(productName) || Check.isNull(type)) {
                return Result.error("缺少参数");
            }
            return cwjsPolicyInfoService.queryInfo(advertiserName, productName, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询异常");
    }


    /**
     * 通过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("文件导入失败！");
    }


    /**
     * 提示政策审核任务（接口废弃）
     * 在定时任务中使用-job为 cwjsPolicyApprovedNoticeWxJob
     *
     * @return
     */
    @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);
    }


    @ApiOperation(value = "政策作废", notes = "政策作废")
    @GetMapping(value = "/toVoidpolicy")
    public Result toVoidpolicy(@RequestParam(name = "policyId") String policyId,
                               @RequestParam(name = "delReason") String delReason) {
        if (Check.isNull(delReason)) {
            return Result.errorMsg("请输入政策作废的理由。");
        }
        return cwjsPolicyInfoService.toVoidpolicy(policyId, delReason);
    }


    @ApiOperation(value = "政策信息导出", notes = "政策信息导出")
    @GetMapping(value = "/exportPolicy")
    public Result exportPolicy(CwjsPolicyInfo cwjsPolicyInfo,
                               HttpServletResponse response) {

        try {
            // 1：待审核 2:审核中 3：审核通过4：审核拒绝 5-作废 默认不显示作废
            if (Check.isNull(cwjsPolicyInfo.getApprovedStatus())) {
                cwjsPolicyInfo.setStatusList(Arrays.asList(1, 2, 3, 4));
            } else {
                cwjsPolicyInfo.setStatusList(Arrays.asList(cwjsPolicyInfo.getApprovedStatus()));
            }
            //查询政策
            List<CwjsPolicyInfo> cwjsPolicyInfoList = cwjsPolicyInfoService.queryPageList(cwjsPolicyInfo);
            if (Check.isNull(cwjsPolicyInfoList)) {
                return Result.errorMsg("暂无政策。");
            }
            List<ExportCwjsPolicyPojo> resultList = new ArrayList<>();
            for (CwjsPolicyInfo vo : cwjsPolicyInfoList) {
                ExportCwjsPolicyPojo exportCwjsPolicyPojo = new ExportCwjsPolicyPojo();
                BeanUtils.copyProperties(vo, exportCwjsPolicyPojo);
                exportCwjsPolicyPojo.setMediaType(ExportCwjsPolicyPojo.getMediaTypeStr(vo.getMediaType()));
                exportCwjsPolicyPojo.setApprovedStatus(ExportCwjsPolicyPojo.getApprovedStatusStr(vo.getApprovedStatus()));
                exportCwjsPolicyPojo.setRebateType(ExportCwjsPolicyPojo.getRebateTypeStr(vo.getRebateType()));
                exportCwjsPolicyPojo.setRebateRate(vo.getRebateRate() + "%");
                exportCwjsPolicyPojo.setDianPayCompanyRebateRate(Check.isNull(vo.getDianPayCompanyRebateRate()) ? "" : vo.getDianPayCompanyRebateRate() + "%");
                exportCwjsPolicyPojo.setPromotionType(Check.isNull(vo.getPromotionType()) ? "-" : vo.getPromotionType() == 0 ? "自运营" : "代运营");
                exportCwjsPolicyPojo.setAdvancePay(Check.isNull(vo.getAdvancePay()) ? "-" : vo.getAdvancePay() == 0 ? "否" : "是");
                exportCwjsPolicyPojo.setIsDianPay(Check.isNull(vo.getIsDianPay()) ? "-" : vo.getIsDianPay() == 0 ? "否" : "是");
                exportCwjsPolicyPojo.setCustomerFlag(Check.isNull(vo.getCustomerFlag()) ? "-" : vo.getCustomerFlag() == 0 ? "否" : "是");
                exportCwjsPolicyPojo.setCreateTime(DateUtils.dateToStringTime(vo.getCreateTime()));
                exportCwjsPolicyPojo.setProductName(StringUtils.strip(vo.getPolicyProductName().toString(), "[]").replace("\"", ""));

                CwjsPolicyApprovalLog mediaContent = policyApprovalLogMapper.getOneByPolicyMeidaInfo(vo.getId());    // 查询 政策审核角色 审核意见 最新的一条
                exportCwjsPolicyPojo.setMeidiaAffairsContent(Check.isNull(mediaContent) ? "" : mediaContent.getApprovalContent());

                CwjsPolicyApprovalLog bossContent = policyApprovalLogMapper.getBossOneByPolicyId(vo.getId());    // 查询 老板审核意见 最新的一条
                exportCwjsPolicyPojo.setBossContent(Check.isNull(bossContent) ? "-" : StringUtils.equals("终审通过", bossContent.getApprovalContent()) ? "-" : bossContent.getApprovalContent());

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

                resultList.add(exportCwjsPolicyPojo);
            }
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("政策内容", "销售政策"), ExportCwjsPolicyPojo.class, resultList);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("销售政策.xls", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


    /**
     * 查询 结算单 没有上传账户图片的账户信息
     *
     * @param productId   产品id
     * @param projectId   项目id
     * @param uploadYears 年-月
     * @param mediaId     媒体类型 1-头条 2-快手 3-头条内广 4-快手内广
     * @return
     */
    @ApiOperation(value = "查询结算单没有上传账户图片的账户信息", notes = "查询结算单没有上传账户图片的账户信息")
    @GetMapping(value = "/getSettlementNoPictureAccountList")
    public Result getSettlementNoPictureAccountList(
            @RequestParam(name = "advertiserId") String advertiserId,
            @RequestParam(name = "productId") String productId,
            @RequestParam(name = "projectId") String projectId,
            @RequestParam(name = "uploadYears") String uploadYears,
            @RequestParam(name = "startTime") String startTime,
            @RequestParam(name = "endTime") String endTime,
            @RequestParam(name = "mediaId") String mediaId,
            @RequestParam(name = "userId") String userId,
            @RequestParam(name = "pageNo") Integer pageNo,
            @RequestParam(name = "pageSize") Integer pageSize
    ) {
        SettlementFileParamsVo paramsVo = new SettlementFileParamsVo();
        paramsVo.setAdvertiserId(advertiserId);
        paramsVo.setProductId(productId);
        paramsVo.setProjectId(projectId);
        paramsVo.setUploadYears(uploadYears);
        paramsVo.setMediaId(Integer.valueOf(mediaId));
        paramsVo.setUserId(userId);
        paramsVo.setPageNo(pageNo);
        paramsVo.setPageSize(pageSize);
        paramsVo.setStartTime(startTime);
        paramsVo.setEndTime(endTime);
        return cwjsPolicyInfoService.getSettlementNoPictureAccountList(paramsVo);
    }

/*
素材id


 */
}
