package cn.com.ctop.toutiao.modules.material.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.IProjectService;
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.toutiao.modules.material.service.IByteDanceAdvertisePlanService;
import cn.com.ctop.toutiao.modules.material.service.IBytedanceBidWarningService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class BytedanceBidWarningServiceImpl implements IBytedanceBidWarningService {
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private MailLogMapper mailLogMapper;
    @Autowired
    private IByteDanceAdvertisePlanService byteDanceAdvertisePlanService;
    @Autowired
    private CorpWexinUtils corpWexinUtils;

    @Override
    public void bidWarning() {
        XxlJobHelper.log("开始头条出价预警定时任务");
        long start = System.currentTimeMillis();
        try {
            List<Project> projects = projectService.list();
            if (!Check.isNull(projects)) {
                for (Project project : projects) {
                    if (Check.isNull(project)) {
                        continue;
                    }
                    Long maxBid = project.getMaxBid();
                    Long projectId = project.getId();
                    List<UserAllocation> userAllocations = userAllocationService.getByParams(projectId, 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 bid = new BigDecimal(maxBid);
                                BigDecimal bigDecimal = BigDecimalUtil.divideBigDecimal(bid, new BigDecimal(1000));
                                unitWarning = byteDanceAdvertisePlanService.selectWarningGroup(accountId, bigDecimal);
                            }
                            if (!Check.isNull(unitWarning)) {
                                sendMessage(project.getMediaId(), accountId, projectId, project.getProjectName(), userAllocation.getAuthName(), unitWarning, maxBid);
                            }
                        }
                    }
                }
            }
            XxlJobHelper.log("头条出价预警定时任务执行完毕，共耗时：{} s", (System.currentTimeMillis() - start) / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMessage(String mediaId, Long accountId, Long projectId, String projectName, String authName, List<String> unitWarning, Long maxBid) {
        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 / 1000).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());
    }
}
