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

import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
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 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.entity.MailLog;
import org.jeecg.modules.ctop.entity.Project;
import org.jeecg.modules.ctop.mapper.MailLogMapper;
import org.jeecg.modules.ctop.mapper.ProjectMapper;
import org.jeecg.modules.ctop.service.IBidWarningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 出价预警
 */
@Slf4j
@Service
public class BidWarningServiceImpl implements IBidWarningService {

    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private UserAllocationMapper userAllocationMapper;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private MailLogMapper mailLogMapper;


    /**
     * 预警
     */

    @Override
    public void BidWarning() {
        log.info("开始出价预警定时任务");
        long l = System.currentTimeMillis();
        try {
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.eq("media_id", "2");
            List<Project> projects = projectMapper.selectList(projectQueryWrapper);
            if (!Check.isNull(projects)) {
                for (Project project : projects) {
                    Long maxBid = project.getMaxBid();
                    Long projectId = project.getId();
                    QueryWrapper<UserAllocation> userAllocationQueryWrapper = new QueryWrapper<>();
                    userAllocationQueryWrapper.eq("project_id", projectId);
                    List<UserAllocation> userAllocations = userAllocationMapper.selectList(userAllocationQueryWrapper);
                    if (!Check.isNull(userAllocations)) {
                        for (UserAllocation userAllocation : userAllocations) {
                            Long accountId = userAllocation.getAccountId();
                            List<String> unitWarning = groupMapper.selectWarningGroup(accountId, maxBid);
                            if (!Check.isNull(unitWarning)) {
                                sendMessage(accountId, projectId, project.getProjectName(), userAllocation.getAuthName(), unitWarning, maxBid);
                            }
                        }
                    }
                }
            }
            log.info("出价预警定时任务执行完毕，共耗时：{} s", (System.currentTimeMillis() - l) / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void sendMessage(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);
        StringBuilder text = new StringBuilder();


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

        }
        text.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 = "广告组出价预警";
            try {
                SendMailUtil.sendMail(mailList, subject, text.toString());
                MailLog mailLog = new MailLog();
                mailLog.setAccountId(accountId);
                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());


    }
}
