package cn.pluss.platform.wx.impl;

import cn.pluss.platform.entity.MerchantBaseInfo;
import cn.pluss.platform.entity.MerchantOrder;
import cn.pluss.platform.entity.MerchantOrderStatistics;
import cn.pluss.platform.entity.PlatformData;
import cn.pluss.platform.mapper.PlatformDataMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantOrder.MerchantOrderStatisticsService;
import cn.pluss.platform.platformData.PlatformDataService;
import cn.pluss.platform.wx.WxTalkService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

/**
 * @author DJH
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WxTalkServiceImpl implements WxTalkService {

    /**
     * 企业微信审核机器人的链接  https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=eba1e093-4cae-424d-be52-7013411194cc
     */
    //TODO 后面需要换成我们自己的
    private static final String WX_TALK_URL = "";

    /**
     * 企业微信上市机器人的链接  https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d89ed4ad-d723-4dce-a80b-bbf370c91943
     */
    //TODO 后面需要换成我们自己的
    public static final String WX_GO_PUBLIC_TALK_URL = "";

    private final RestTemplate restTemplate;

    private final MerchantBaseInfoService merchantBaseInfoService;

    @Lazy
    @Autowired
    private PlatformDataService platformDataService;

    @Resource
    private PlatformDataMapper platformDataMapper;

    @Lazy
    @Autowired
    private MerchantOrderService moService;

    @Lazy
    @Autowired
    private MerchantOrderStatisticsService mosService;

    @Override
    public void sendTextMsg(String textMsg) {
        sendTextMsg(textMsg, WX_TALK_URL);
    }

    @Override
    public void sendTextMsg(String textMsg, String url) {
        JSONObject object = new JSONObject();
        object.put("msgtype", "text");
        JSONObject content = new JSONObject();
        content.put("content", textMsg);
        object.put("text", content);

        try {
            Object result = restTemplate.postForObject(url, object, Object.class);
            log.info("微信机器人发送消息成功: {}", result);

            sendAtAll();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("微信机器人发送消息失败");
        }
    }

    @Override
    public void sendMarkDownMsg(String markDownMsg) {
        JSONObject object = new JSONObject();
        object.put("msgtype", "markdown");
        JSONObject content = new JSONObject();
        content.put("content", markDownMsg);
        object.put("markdown", content);

        try {
            Object result = restTemplate.postForObject(WX_TALK_URL, object, Object.class);
            log.info("微信机器人发送消息成功: {}", result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("微信机器人发送消息失败");
        }
    }

    @Override
    public void sendAuditAlert(String userId) {
        if (userId == null) {
            return;
        }

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getMerchantBaseInfoByUserId(userId);

        String merchantName = merchantBaseInfo.getAlias();

        String sb = "新增商户<font color=\"warning\">" +
                merchantName +
                "</font>进件请求，待审核\n" +
                ">[点击查看详情](https://www.shouyinbei.net/wap/merchant/toAudit?userId=" +
                userId + ")\n";
        sendMarkDownMsg(sb);
        sendAtAll();
    }

    @Override
    public void sendAuditResultAlert(String userId) {
        if (userId == null) {
            return;
        }

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getMerchantBaseInfoByUserId(userId);

        String merchantName = merchantBaseInfo.getAlias();

        sendMarkDownMsg("商户<font color=\"warning\">" +
                merchantName + "</font>进件请求已处理");
    }

    @Override
    public void sendPluginAuditAlert(String userId) {
        if (userId == null) {
            return;
        }

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getMerchantBaseInfoByUserId(userId);

        String merchantName = merchantBaseInfo.getAlias();

        String sb = "新增商户<font color=\"warning\">" +
                merchantName +
                "</font>插件进件请求，待审核\n" +
                ">[点击查看详情](https://www.shouyinbei.net/wap/merchant/toAudit?userId=" +
                userId + ")\n";
        sendMarkDownMsg(sb);
        sendAtAll();
    }

    @Override
    public void sendPluginAuditResultAlert(String userId) {
        if (userId == null) {
            return;
        }

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getMerchantBaseInfoByUserId(userId);

        String merchantName = merchantBaseInfo.getAlias();

        sendMarkDownMsg("商户<font color=\"warning\">" +
                merchantName + "</font>插件进件请求已处理");
    }

    @Override
    public void sendAtAll() {
        JSONObject object = new JSONObject();
        JSONObject content = new JSONObject();
        object.put("msgtype", "text");
        content.put("content", "");
        JSONArray mentionedList = new JSONArray();
        mentionedList.add("@all");
        content.put("mentioned_list", mentionedList);
        object.put("text", content);

        try {
            Object result = restTemplate.postForObject(WX_TALK_URL, object, Object.class);
            log.info("微信机器人发送消息成功: {}", result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("微信机器人发送消息失败");
        }
    }

    @Override
    public void sendManageLoginInfo(String loginName, String password, String ip, String isp, String ipLocation, boolean successFlag) {
        JSONObject object = new JSONObject();
        JSONObject content = new JSONObject();
        object.put("msgtype", "text");

        String contentStr = "用户" + loginName;
        if (successFlag) {
            contentStr += "登录成功\n";
            contentStr += "登录IP: " + ip + "\n";
            contentStr += "IP运营商: " + isp + "\n";
            contentStr += "登录地区: " + ipLocation + "\n";
        } else {
            contentStr += "登录失败\n";
            contentStr += "错误密码为: " + password + "\n";
            contentStr += "登录IP: " + ip + "\n";
            contentStr += "IP运营商: " + isp + "\n";
            contentStr += "登录地区: " + ipLocation + "\n";
        }

        content.put("content", contentStr);
        JSONArray mentionedList = new JSONArray();
        mentionedList.add("@all");
        content.put("mentioned_list", mentionedList);
        object.put("text", content);

        try {
            Object result = restTemplate.postForObject(WX_TALK_URL, object, Object.class);
            log.info("微信机器人发送消息成功: {}", result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("微信机器人发送消息失败");
        }
    }

    @Override
    public void sendStatisticData() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);

        final Date currentTime = calendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM", Locale.getDefault());

        final String currentDate = sdf.format(currentTime);
        final String currentMonth = sdf2.format(currentTime);

        LambdaQueryWrapper<PlatformData> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(PlatformData::getOperatDate, currentDate);
        // 获取昨天的数据
        final PlatformData yesterdayData = platformDataService.getOne(qWrapper);
        // 获取昨天当月的数据
        final PlatformData monthData = platformDataMapper.selectMonthData(currentMonth);

        final BigDecimal ysRate = BigDecimal.valueOf(0.6d);
        final BigDecimal monthDayCount = BigDecimal.valueOf(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        final BigDecimal dayTarget = BigDecimal.valueOf(8500000L);
        final BigDecimal hundred = BigDecimal.valueOf(100);
        final BigDecimal monthTarget = dayTarget.multiply(monthDayCount);
        final BigDecimal ysDayTarget = dayTarget.multiply(ysRate);
        final BigDecimal ysMonthTarget = ysDayTarget.multiply(monthDayCount);

        final BigDecimal dayProfitTarget = BigDecimal.valueOf(3600);
        final BigDecimal monthProfitTarget = dayProfitTarget.multiply(monthDayCount);

        StringBuilder sb = new StringBuilder();
        sb.append("目标日期 ").append(currentDate).append("\n");
        sb.append("单日目标：").append(dayTarget.stripTrailingZeros().toPlainString()).append("\n");
        sb.append("月总目标：").append(monthTarget.stripTrailingZeros().toPlainString()).append("\n");
        sb.append("银盛日目标（60%）：").append(ysDayTarget.stripTrailingZeros().toPlainString()).append("\n");
        sb.append("银盛月目标（60%）：").append(ysMonthTarget.stripTrailingZeros().toPlainString()).append("\n");
        sb.append("日目标营收：").append(dayProfitTarget.stripTrailingZeros().toPlainString()).append("\n");
        sb.append("月目标营收：").append(monthProfitTarget.stripTrailingZeros().toPlainString()).append("\n");
        sb.append("===================\n");
        sb.append(currentDate).append(" 数据：\n");
        sb.append("日交易额：").append(yesterdayData.getTransAmt().stripTrailingZeros().toPlainString()).append("\n");
        sb.append("月总交易额：").append(monthData.getTransAmt().stripTrailingZeros().toPlainString()).append("\n");
        sb.append("日交易及月交易额完成率：")
                .append(yesterdayData.getTransAmt().multiply(hundred).divide(dayTarget, 2, RoundingMode.HALF_EVEN))
                .append("% / ")
                .append(monthData.getTransAmt().multiply(hundred).divide(monthTarget, 2, RoundingMode.HALF_EVEN))
                .append("%\n");
        sb.append("------------------\n");

        QueryWrapper<MerchantOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.select("SUM(consumeFee) consumeFee");
        orderQueryWrapper.eq("status", "1");
        orderQueryWrapper.eq("settlementType", "0");
        orderQueryWrapper.eq("createDate", currentDate);
        Map<String, Object> ysDayData = moService.getMap(orderQueryWrapper);
        BigDecimal ysDay = new BigDecimal(ysDayData.get("consumeFee").toString());
        sb.append("银盛日交易额: ").append(ysDay.stripTrailingZeros().toPlainString()).append("\n");

        QueryWrapper<MerchantOrder> orderStatisticsQueryWrapper = new QueryWrapper<>();
        orderStatisticsQueryWrapper.select("SUM(consumeFee) consumeFee");
        orderStatisticsQueryWrapper.eq("settlementType", "0");
        orderStatisticsQueryWrapper.eq("status", "1");

        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date monthBegin = calendar.getTime();
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date monthEnd = calendar.getTime();

        orderStatisticsQueryWrapper.between("createDate", sdf.format(monthBegin), sdf.format(monthEnd));

        Map<String, Object> ysMonthData = moService.getMap(orderStatisticsQueryWrapper);
        BigDecimal ysMonth = new BigDecimal(ysMonthData.get("consumeFee").toString());
        sb.append("银盛月交易额：").append(ysMonth.stripTrailingZeros().toPlainString()).append("\n");
        sb.append("银盛日交易及月交易额完成率：")
                .append(ysDay.multiply(hundred).divide(ysDayTarget, 2, RoundingMode.HALF_EVEN))
                .append("% / ")
                .append(ysMonth.multiply(hundred).divide(ysMonthTarget, 2, RoundingMode.HALF_EVEN))
                .append("%\n");
        sb.append("------------------\n");
        sb.append("日营收：").append(yesterdayData.getActualAmt().stripTrailingZeros().toPlainString()).append("\n");
        sb.append("月营收：").append(monthData.getActualAmt().stripTrailingZeros().toPlainString()).append("\n");
        sb.append("日营收及月营收完成率：")
                .append(yesterdayData.getActualAmt().multiply(hundred).divide(dayProfitTarget, 2, RoundingMode.HALF_EVEN))
                .append("% / ")
                .append(monthData.getActualAmt().multiply(hundred).divide(monthProfitTarget, 2, RoundingMode.HALF_EVEN))
                .append("%\n");
        sb.append("------------------\n");
        sb.append("日通道占比：D0 （暂未统计）/ D1 （暂未统计）\n");
        sb.append("日新增门店：").append(yesterdayData.getStoreNum()).append("\n");
        sb.append("日新增推广员：").append(yesterdayData.getPromoterNum()).append("\n");
        sb.append("月总新增门店和推广员：暂未统计/暂未统计\n");
        sb.append("==================");

        sendTextMsg(sb.toString(), WX_GO_PUBLIC_TALK_URL);
    }
}
