package org.jeecg.modules.ctop.service.impl;

import cn.com.ctop.common.module.entity.MailLog;
import cn.com.ctop.common.module.entity.Project;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.MailLogMapper;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.BigDecimalUtil;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CorpWexinUtils;
import cn.com.ctop.common.module.utils.SendMailUtil;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouGroupMapper;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceAdvertisePlanService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.ctop.service.ICpaBidWarningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 出价预警
 */
@Slf4j
@Service
public class CpaBidWarningServiceImpl implements ICpaBidWarningService {
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private MailLogMapper mailLogMapper;
    @Autowired
    private IByteDanceAdvertisePlanService byteDanceAdvertisePlanService;
    @Autowired
    private CorpWexinUtils corpWexinUtils;

    /**
     * 预警
     */
    @Override
    public void cpaBidWarning(Project project) {
        try {
            BigDecimal maxDeepCpaBid = project.getMaxDeepCpaBid();
            List<UserAllocation> userAllocations = userAllocationService.getByParams(project.getId(), null, null);
            if (!Check.isNull(userAllocations)) {
                for (UserAllocation userAllocation : userAllocations) {
                    if (userAllocation.getAccountStatus() == 1) {
                        continue;
                    }
                    Long accountId = userAllocation.getAccountId();
                    List<String> unitWarning = new ArrayList<>();
                    if ("1".equals(userAllocation.getMediaId())) {
                        BigDecimal deepBid = BigDecimalUtil.divideBigDecimal(maxDeepCpaBid, new BigDecimal(1000));
                        unitWarning = byteDanceAdvertisePlanService.selectWarningCpaBid(accountId, deepBid);
                    } else if ("2".equals(userAllocation.getMediaId())) {
                        unitWarning = groupMapper.selectWarningCpaBid(accountId, maxDeepCpaBid);
                    }

                    if (!Check.isNull(unitWarning)) {
                        sendMessage(project.getMediaId(), accountId, project.getId(), project.getProjectName(), userAllocation.getAuthName(), unitWarning, maxDeepCpaBid);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMessage(String mediaId, Long accountId, Long projectId, String projectName, String authName, List<String> unitWarning, BigDecimal maxCpaBid) {
        BigDecimal maxBid = BigDecimalUtil.divideBigDecimal(maxCpaBid, new BigDecimal(1000));
        String createTime = DateUtils.getNowDate("yyyy-MM-dd");
        Integer count = mailLogMapper.selectCountByAccountIdAndDate(accountId, createTime, 1);
        StringBuilder text = new StringBuilder();

        String s = "";
        for (int i = 0; i < unitWarning.size(); i++) {
            s += unitWarning.get(i) + "，" + "<br/>";

        }
        text.append("项目深度出价预警").append("<br/>").append("您的项目：").append(projectName + "，").append("<br/>")
                .append("授权名称为：" + authName + " 下的，").append("<br/>").append(s)
                .append("大于项目设置的最高深度转化出价：").append(maxBid).append(" 元！ 请您及时调整。");
        if (count < 3) {
            List<String> mailList = mailLogMapper.selectMailList(projectId);
            String subject;
            if ("1".equals(mediaId)) {
                subject = "头条-广告计划深度转化出价预警";

            } else {
                subject = "快手-广告组深度转化出价预警";
            }

            try {
                SendMailUtil.sendMail(mailList, subject, text.toString());
                MailLog mailLog = new MailLog();
                mailLog.setAccountId(accountId);
                mailLog.setMailType(1);
                mailLog.setContent(text.toString());
                mailLog.setSendEmil(JSON.toJSONString(mailList));
                mailLog.setSubject(subject);
                mailLogMapper.insert(mailLog);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        List<JSONObject> wexinIds = mailLogMapper.selectWeiXinIdList(projectId);
        corpWexinUtils.sendMessage(wexinIds, text.toString());
    }


}
