package org.jeecg.ctop.finance.policy.service.impl;

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.utils.CorpWexinUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.entity.SysUser;
import org.jeecg.ctop.finance.policy.entity.CwjsPolicyApprovalLog;
import org.jeecg.ctop.finance.policy.entity.CwjsPolicyInfo;
import org.jeecg.ctop.finance.policy.mapper.CwjsPolicyInfoMapper;
import org.jeecg.ctop.finance.policy.mapper.CwjsPolicyProductMapper;
import org.jeecg.ctop.finance.policy.service.ICwjsPolicyInfoService;
import org.jeecg.ctop.finance.policy.utils.Check;
import org.jeecg.ctop.finance.settlement.entity.vo.SettlementFileParamsVo;
import org.jeecg.ctop.finance.settlement.mapper.CwjsProfitMapper;
import org.jeecg.ctop.finance.settlement.mapper.ReportSettlementMapper;
import org.jeecg.ctop.finance.settlement.service.IReportSettlementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 政策信息表
 *
 * @author jeecg-boot
 * 2021-07-27
 * @version V1.0
 */
@Service
public class CwjsPolicyInfoServiceImpl extends ServiceImpl<CwjsPolicyInfoMapper, CwjsPolicyInfo> implements ICwjsPolicyInfoService {
    @Resource
    CwjsPolicyInfoMapper policyInfoMapper;

    @Resource
    private MailLogMapper mailLogMapper;

    @Resource
    private CorpWexinUtils corpWexinUtils;

    @Resource
    private CwjsPolicyApprovalLogServiceImpl policyApprovalLogService;

    @Resource
    private CwjsPolicyProductMapper cwjsPolicyProductMapper;


    @Resource
    private CwjsProfitMapper cwjsProfitMapper;

    /**
     * @param policyInfo
     * @description: 查看政策列表
     * 已通过的政策 按照 产品名称 拆分多条
     * @return: java.util.List<org.jeecg.ctop.finance.policy.entity.CwjsPolicyInfo>
     * @author: zianY
     * @time: 2022/3/29
     */
    @Override
    public List<CwjsPolicyInfo> queryPageList(CwjsPolicyInfo policyInfo) {

        List<CwjsPolicyInfo> policyInfoList = policyInfoMapper.selectPolicyInfos(policyInfo);
        List<CwjsPolicyInfo> result = new ArrayList<>();
        //1.过滤所有已通过审核的政策到结果表中
        policyInfoList.forEach(policy -> {
            if (policy.getApprovedStatus() == 3) {
                JSONArray policyProductName = new JSONArray();
                policyProductName.add(policy.getProductName());
                policy.setPolicyProductName(policyProductName);
                result.add(policy);
            }
        });
        policyInfoList.removeAll(result);
        Map<Integer, CwjsPolicyInfo> map = new HashMap<>();
        //2.未通过审核的政策需要通过政策id来进行聚合，把产品名称放到同一个列表里
        policyInfoList.forEach(policy -> {
            if (map.containsKey(policy.getId())) {
                map.get(policy.getId()).getPolicyProductName().add(policy.getProductName());
            } else {
                JSONArray policyProductName = new JSONArray();
                policyProductName.add(policy.getProductName());
                policy.setPolicyProductName(policyProductName);
                map.put(policy.getId(), policy);
            }
        });
        //3.遍历聚合完成后的map，每一个key对应一条不通过的政策的数据，放入到结果集返回
        Set<Integer> keys = map.keySet();
        for (Integer key : keys) {
            result.add(map.get(key));
        }
        return result;
    }

    @Override
    public List<JSONObject> getAllSale() {
        return policyInfoMapper.getAllSale();
    }

    @Override
    public List<JSONObject> getAllSaleAndMeidaManager() {
        return policyInfoMapper.getAllSaleAndMeidaManager();
    }

    /**
     * 查询 所有 运营
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getAllOperationUser() {
        return policyInfoMapper.getAllOperationUser();
    }

    @Override
    public List<JSONObject> getAllSaleByUserId(String userId) {
        return policyInfoMapper.getAllSaleByUserId(userId);
    }


    @Resource
    private SysUserMapper userMapper;

    @Override
    public List<JSONObject> getAllSubordinate2(String userId) {
        List<SysUser> allList = userMapper.selectAllUser();
        List<SysUser> mulUserList = treeCategoryData(allList, userId);
        List<JSONObject> users = new ArrayList<>();
        mulUserList.forEach(mulUser -> {
            JSONObject jo = new JSONObject();
            jo.put("userId", mulUser.getId());
            jo.put("userName", mulUser.getRealname());
            users.add(jo);
        });
        return users;
    }


    @Override
    public List<String> getAllSubordinate(String userId) {
        List<SysUser> allList = userMapper.selectAllUser();
        List<SysUser> mulUserList = treeCategoryData(allList, userId);
        List<String> userIds = new ArrayList<>();
        userIds.add(userId);
        mulUserList.forEach(mulUser -> userIds.add(mulUser.getId()));
        return userIds;
    }

    public List<SysUser> treeCategoryData(List<SysUser> allList, String leaderId) {
        List<SysUser> mapList = new ArrayList<>();
        for (SysUser vo : allList) {
            if (leaderId.equals(vo.getLeaderId())) {
                mapList.add(vo);
                mapList.addAll(treeCategoryData(allList, vo.getId()));
            }
        }
        return mapList;

    }

    @Override
    public boolean isExistCwjsPolicyInfo(CwjsPolicyInfo policyInfo) {
        CwjsPolicyInfo cwjsPolicyInfoEntity = new CwjsPolicyInfo();
        cwjsPolicyInfoEntity.setAdvertiserName(policyInfo.getAdvertiserName());
        cwjsPolicyInfoEntity.setProductName(policyInfo.getProductName());
        cwjsPolicyInfoEntity.setMediaType(policyInfo.getMediaType());
        cwjsPolicyInfoEntity.setCreateUserId(policyInfo.getCreateUserId());
        cwjsPolicyInfoEntity.setPolicyStartDate(policyInfo.getPolicyStartDate());
        cwjsPolicyInfoEntity.setPolicyEndDate(policyInfo.getPolicyEndDate());
        List<CwjsPolicyInfo> cwjsPolicyInfos = policyInfoMapper.selectPolicyInfos(policyInfo);
        if (Check.isNull(cwjsPolicyInfos)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void updatePolicyInfoById(CwjsPolicyInfo policyInfo) {
        policyInfoMapper.updatePolicyInfoById(policyInfo);
    }


    @Override
    public void automaticConveyBossExamine(CwjsPolicyInfo cwjsPolicyInfo) {
        cwjsPolicyInfo.setApprovedStatus(2);
        cwjsPolicyInfo.setApprovedProgress("4aba62011120ac565c7f2b9f8f4aa96b");    //设置 boss 为审核人员
        JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId("4aba62011120ac565c7f2b9f8f4aa96b");
        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.getLoginUserId());
        policyApprovalLog.setApprovalStatus(2);//0-审核通过  1-审核不通过 2-转给领导
        policyApprovalLog.setApprovalContent(Check.isNull(cwjsPolicyInfo.getApprovalContent()) ? "转审领导" : cwjsPolicyInfo.getApprovalContent());
        policyApprovalLog.setCreateTime(new Date());
        policyApprovalLogService.save(policyApprovalLog);
    }

    /**
     * 查询 政策审核记录
     *
     * @param policyId
     * @return
     */
    @Override
    public Result getPolicyApprovalLogByPolicyId(Integer policyId) {
        List<JSONObject> policyApprovalList = policyInfoMapper.getPolicyApprovalLogByPolicyId(policyId);
        //不显示审核意见
        for (JSONObject object : policyApprovalList) {
            if (object.getString("approvalContent").length() > 4) {
                object.put("approvalContent", "审核" + (object.getString("approvalStatus").equals("0") ? "成功" : "失败"));
            }
        }

        return Result.successMsg("政策审核记录查询成功", policyApprovalList);
    }

    @Override
    public List<Integer> getCompanySubjectByUserId(String userId) {
        return policyInfoMapper.getCompanySubjectByUserId(userId);
    }


    @Override
    public List<JSONObject> getLegalAffairsUsers() {
        return policyInfoMapper.getLegalAffairsUsers();
    }


    /**
     * 政策作废
     *
     * @param policyId  政策id
     * @param delReason 作废原因
     * @return
     */
    @Override
    public Result toVoidpolicy(String policyId, String delReason) {
        CwjsPolicyInfo cwjsPolicyInfo = policyInfoMapper.selectById(policyId);
        // 1：待审核 2:审核中 3：审核通过4：审核拒绝
        if (Check.isNull(cwjsPolicyInfo) || cwjsPolicyInfo.getApprovedStatus() != 3) {
            return Result.errorMsg("政策不存在或政策还在审核，审核中的政策无法作废。");
        }
        //修改政策状态及作废原因
        policyInfoMapper.updatePolicyToVOidById(policyId, delReason);
        //删除政策关联的产品信息
        //cwjsPolicyProductMapper.deleteProductsByPolicyId(Integer.valueOf(policyId));
        //删除该政策利润表记录
        cwjsProfitMapper.delSlettmentReportByPolicyId(policyId);

        JSONObject examineUser = policyInfoMapper.getUserLeaderAndDirectorByRoleName(cwjsPolicyInfo.getCreateUserId(), "分公司总经理");
        List<String> userList = new ArrayList<>();
        userList.add(examineUser.getString("leaderId"));
        userList.add(examineUser.getString("directorId"));

        for (String userId : userList) {
            //给销售总监发送
            JSONObject wChatIdByUserId = mailLogMapper.getWChatIdByUserId(userId);
            StringBuilder text = new StringBuilder();
            text.append(cwjsPolicyInfo.getCreateUserName() + "创建的政策，客户为：" + cwjsPolicyInfo.getCompanyName());
            text.append("，该销售政策已作废。");
            corpWexinUtils.sendMessageByWeChatId(wChatIdByUserId, text.toString());
        }

        return Result.successMsg("政策作废成功", null);
    }

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IReportSettlementService reportSettlementService;

    @Resource
    private ReportSettlementMapper reportSettlementMapper;

    @Override
    public Result getSettlementNoPictureAccountList(SettlementFileParamsVo paramsVo) {
        SysUser user = userService.getById(paramsVo.getUserId());
        //查询账户数量
        List<String> accountIds = reportSettlementService.getAccountId(paramsVo, user);

        if (Check.isNull(accountIds)) {
            return Result.errorMsg("未上传结算单账户列表查询为空。");
        }
        //过滤消耗为0 的账户 1-头条 2-快手
        if (paramsVo.getMediaId().equals(1)) {
            accountIds = reportSettlementMapper.getAccountIdBytedanceRepeat(accountIds, paramsVo.getStartTime(), paramsVo.getEndTime());
        } else if (paramsVo.getMediaId().equals(2)) {
            accountIds = reportSettlementMapper.getAccountIdKuaiShouRepeat(accountIds, paramsVo.getStartTime(), paramsVo.getEndTime());
        }
        //过滤以上传的账户
        //List<JSONObject> list = policyInfoMapper.getSettlementNoPictureAccountList(productId,projectId,uploadYears,mediaIds);


        PageHelper.startPage(paramsVo.getPageNo(), paramsVo.getPageSize());
        List<JSONObject> list = policyInfoMapper.getSettlementNoPictureAccountAgentList(paramsVo.getProductId(), paramsVo.getProjectId(), paramsVo.getEndTime(), accountIds);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        return Result.successMsg("未上传结算单账户查询成功。", pageInfo);
    }

    @Override
    public Result<Object> queryInfo(String advertiserName, String productName, String type) {
        return Result.ok(policyInfoMapper.queryInfo(advertiserName, productName, type));
    }


}
