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.mapper.ProjectMapper;
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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.ctop.service.IBidWarningService;
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 BidWarningServiceImpl implements IBidWarningService {

    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private MailLogMapper mailLogMapper;
    @Autowired
    private IByteDanceAdvertisePlanService byteDanceAdvertisePlanService;


    /**
     * 预警
     */

    @Override
    public void bidWarning() {
        log.info("开始出价预警定时任务");
        long l = System.currentTimeMillis();
        try {
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            List<Project> projects = projectMapper.selectList(projectQueryWrapper);
            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);
                            } else if ("2".equals(userAllocation.getMediaId())) {
                                unitWarning = groupMapper.selectWarningGroup(accountId, maxBid);
                            }

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

            log.info("出价预警定时任务执行完毕，共耗时：{} s", (System.currentTimeMillis() - l) / 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<String> wexinIds = mailLogMapper.selectWeiXinIdList(projectId);
        CorpWexinUtils.sendMessage(wexinIds, text.toString());
    }


}
