package com.pcloud.book.mq.topic;

import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.group.biz.LearningReportBiz;
import com.pcloud.book.group.biz.WeixinQrcodeBiz;
import com.pcloud.book.group.dao.BookGroupClassifyDao;
import com.pcloud.book.group.dao.GroupQrcodeDao;
import com.pcloud.book.group.dto.BookWxQrcodeDTO;
import com.pcloud.book.group.dto.GroupClassifyQrcodeDTO;
import com.pcloud.book.group.dto.LearningScoreDTO;
import com.pcloud.book.group.entity.GroupQrcode;
import com.pcloud.book.mq.config.MQTopicConumer;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.QrcodeUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.common.utils.httpclient.UrlUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.facade.shareimage.dto.HtmlDto;
import com.pcloud.facade.shareimage.facade.Htm2ImgService;
import com.pcloud.wechatgroup.message.dto.GroupLearningReportDTO;
import com.sdk.wxgroup.SendPicMessageVO;
import com.sdk.wxgroup.SendTextMessageVO;
import com.sdk.wxgroup.WxGroupSDK;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Component
@RabbitListener(queues = MQTopicConumer.WXGROUP_LEARNING_REPORT)
public class WXGroupLearningReportListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(WXGroupLearningReportListener.class);

    @Autowired
    private LearningReportBiz learningReportBiz;
    @Autowired
    private GroupQrcodeDao groupQrcodeDao;
    @Autowired
    private Htm2ImgService htm2ImgService;
    @Autowired
    private BookGroupClassifyDao bookGroupClassifyDao;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private WeixinQrcodeBiz weixinQrcodeBiz;


    @ParamLog("接收学习报告topic")
    @RabbitHandler
    public void onMessage(GroupLearningReportDTO groupLearningReportDTO) throws BizException {
        try {
            if (groupLearningReportDTO == null
                    || groupLearningReportDTO.getWechatGroupId() == null
                    || groupLearningReportDTO.getWechatUserId() == null) {
                return;
            }
            String wechatUserId = groupLearningReportDTO.getWechatUserId();
            String wechatGroupId = groupLearningReportDTO.getWechatGroupId();
            //新增触发记录
            learningReportBiz.createLearningReportTouchRecord(wechatUserId, wechatGroupId);
            //发送报告等
            GroupQrcode groupQrcode = groupQrcodeDao.getGroupQrcodeByGroupId(wechatGroupId);
            if (groupQrcode == null) {
                LOGGER.info("没找到该群" + wechatGroupId);
                return;
            }
            GroupClassifyQrcodeDTO groupClassifyQrcodeDTO = bookGroupClassifyDao.getClassifyQrcodeInfo(wechatGroupId);
            if (groupClassifyQrcodeDTO == null) {
                LOGGER.info("没找到该分类" + wechatGroupId);
                return;
            }
            if (groupClassifyQrcodeDTO.getHasOpenLearningReport() == null || !groupClassifyQrcodeDTO.getHasOpenLearningReport()) {
                LOGGER.info("没找设置学习报告" + wechatGroupId);
                return;
            }
            Long groupQrcodeId = groupQrcode.getId();
            List<LearningScoreDTO> learningScoreDTOS = learningReportBiz.getLearningTopFive(groupQrcodeId);
            AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(groupClassifyQrcodeDTO.getChannelId());
            String url = "/other/grouppk?book_group_id=" + groupClassifyQrcodeDTO.getBookGroupId() + "&classify_id=" + groupClassifyQrcodeDTO.getClassifyId() + "&qrcode_id=" + groupQrcodeId;
            String resultUrl = accountSettingDto.getProtocol() + accountSettingDto.getDomain() + "/W" + accountSettingDto.getAccountSettingId() + "/C" + groupClassifyQrcodeDTO.getChannelId() + url;
            resultUrl=UrlUtils.getShortUrl4Own(resultUrl);
            String qrcodeUrl = QrcodeUtils.create(resultUrl);
            if (qrcodeUrl.contains("https://oss.5rs.me")) {
                qrcodeUrl = qrcodeUrl.replace("https://oss.5rs.me", "https://file.5rs.me");
            } else if (qrcodeUrl.contains("http://oss.5rs.me")) {
                qrcodeUrl = qrcodeUrl.replace("http://oss.5rs.me", "http://file.5rs.me");
            }
            String imageUrl = getPic(learningScoreDTOS,qrcodeUrl);
            String alt = groupLearningReportDTO.getWxId();
            if (StringUtil.isEmpty(alt)) {
                return;
            }
            SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
            sendTextMessageVO.setWxGroupId(wechatGroupId);
            sendTextMessageVO.setAltId(alt);
            sendTextMessageVO.setContent("个人专属学习报告，及群成员元气排行榜。点击获取" + resultUrl);
            sendTextMessageVO.setIp(findIp(wechatGroupId));
            LOGGER.info("发送文字消息开始"+sendTextMessageVO.toString());
            WxGroupSDK.sendTextMessage(sendTextMessageVO);
            LOGGER.info("发送文字消息结束"+sendTextMessageVO.toString());
            if (ListUtils.isEmpty(learningScoreDTOS)) {
                LOGGER.info("没有排行记录，不发送图片groupQrcodeId=" + groupQrcodeId);
                return;
            }
            SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
            sendPicMessageVO.setPicUrl(imageUrl);
            sendPicMessageVO.setWxGroupId(wechatGroupId);
            sendPicMessageVO.setAltId(alt);
            sendPicMessageVO.setIp(findIp(wechatGroupId));
            LOGGER.info("发送分享图消息开始"+sendPicMessageVO.toString());
            WxGroupSDK.sendPicMessage(sendPicMessageVO);
            LOGGER.info("发送分享图消息开始"+sendPicMessageVO.toString());
        } catch (Exception e) {
            LOGGER.error("接收学习报告topic失败" + e.getMessage(), e);
        }
    }

    @ParamLog("获取ip")
    private String findIp(String wechatGroupId) {
        Map<String, BookWxQrcodeDTO> groupVersion = weixinQrcodeBiz.getGroupVersion(Collections.singletonList(wechatGroupId));
        String ip = Optional.ofNullable(groupVersion.get(wechatGroupId)).orElse(new BookWxQrcodeDTO()).getWechatGroupIp();
        return ip;
    }

    @ParamLog("获取图片")
    private String getPic(List<LearningScoreDTO> learningScoreDTOS, String qrcodeUrl) {
        String list="";
        for (LearningScoreDTO learningScoreDTO:learningScoreDTOS){
            String headUrl = learningScoreDTO.getHeadUrl();
            if (headUrl.contains("https://oss.5rs.me")) {
                headUrl = headUrl.replace("https://oss.5rs.me", "https://file.5rs.me");
            } else if (headUrl.contains("http://oss.5rs.me")) {
                headUrl = headUrl.replace("http://oss.5rs.me", "http://file.5rs.me");
            }
            String s1 = "{\n" +
                    "      headPic: '" + headUrl + "?x-oss-process=image/auto-orient,0/resize,p_100',\n" +
                    "      nickName: '" + learningScoreDTO.getNickName() + "',\n" +
                    "      strength: " + learningScoreDTO.getScore() + "\n" +
                    "    }";
            list = list + "," + s1;
        }
        String yesterday=DateUtils.getYesterday();
        String mo=yesterday.substring(5,7);
        String da=yesterday.substring(8,10);

        String s3="<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "\n" +
                "<head>\n" +
                "  <meta charset=\"gbk\">\n" +
                "  <title>Document</title>\n" +
                "  <style>\n" +
                "    * {\n" +
                "      margin: 0;\n" +
                "      padding: 0;\n" +
                "      box-sizing: border-box;\n" +
                "      font-family: '微软雅黑', Arial, Helvetica, sans-serif;\n" +
                "    }\n" +
                "    th {\n" +
                "      font-weight: normal;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank {\n" +
                "      position: relative;\n" +
                "      width: 750px;\n" +
                "      height: 1334px;\n" +
                "      padding: 40px 32px 30px;\n" +
                "      background: #f5f4f4 url(https://file.5rs.me/oss/uploadfe/png/8021a28c21a36b31e2d47cb1cbdf673b.png) top / 750px no-repeat;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-header {\n" +
                "      color: #fff;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-header .title {\n" +
                "      font-size: 125px;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-header .tips {\n" +
                "      font-size: 31px;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-list,\n" +
                "    .group-rank-help {\n" +
                "      overflow: hidden;\n" +
                "      border-radius: 16px;\n" +
                "      margin-top: 50px;\n" +
                "      background-color: #fffdfb;\n" +
                "      box-shadow: 0px 14px 70px 0px rgba(26, 21, 15, 0.1);\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-list {\n" +
                "      height: 686px;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-list table {\n" +
                "      width: 100%;\n" +
                "      table-layout: fixed;\n" +
                "      border-spacing: 0;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-list table thead tr {\n" +
                "      height: 67px;\n" +
                "      font-size: 24px;\n" +
                "      color: #a19280;\n" +
                "      background-color: #fff6ed;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-list table tbody tr {\n" +
                "      height: 120px;\n" +
                "      text-align: center;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-list table tbody tr td .index::after {\n" +
                "      content: attr(data-index);\n" +
                "      font-size: 28px;\n" +
                "      color: #999;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-list table tbody tr:nth-child(1) td .index::after {\n" +
                "      content: url(https://file.5rs.me/oss/uploadfe/png/aa572981a172e47b974b62584cec584f.png?x-oss-process=image/auto-orient,0/resize,p_38);\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-list table tbody tr:nth-child(2) td .index::after {\n" +
                "      content: url(https://file.5rs.me/oss/uploadfe/png/24ff8ea2c40a4da97ce6d9f4cce7a599.png?x-oss-process=image/auto-orient,0/resize,p_38);\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-list table tbody tr:nth-child(3) td .index::after {\n" +
                "      content: url(https://file.5rs.me/oss/uploadfe/png/1c01dec272bef14c2a4d495042c44cd8.png?x-oss-process=image/auto-orient,0/resize,p_38);\n" +
                "    }\n" +
                "\n" +
                "    .headPic {\n" +
                "      border: 1px solid #eee;\n" +
                "      border-radius: 50%;\n" +
                "    }\n" +
                "\n" +
                "    .nickName {\n" +
                "      text-overflow: ellipsis;\n" +
                "      white-space: nowrap;\n" +
                "      overflow: hidden;\n" +
                "    }\n" +
                "\n" +
                "    .nickName,\n" +
                "    .strength {\n" +
                "      color: #442d12;\n" +
                "      font-size: 30px;\n" +
                "    }\n" +
                "\n" +
                "    .group-rank-help {\n" +
                "      display: flex;\n" +
                "      height: 280px;\n" +
                "      padding: 30px;\n" +
                "    }\n" +
                "\n" +
                "    .left-content {\n" +
                "      width: 400px;\n" +
                "    }\n" +
                "\n" +
                "    .right-content {\n" +
                "      width: 190px;\n" +
                "      margin-left: 30px;\n" +
                "    }\n" +
                "\n" +
                "    .left-content .question {\n" +
                "      margin-bottom: 35px;\n" +
                "      font-size: 36px;\n" +
                "      line-height: 32px;\n" +
                "      letter-spacing: 1px;\n" +
                "      color: #442d12;\n" +
                "    }\n" +
                "\n" +
                "    .left-content .answer {\n" +
                "      position: relative;\n" +
                "      padding-left: 30px;\n" +
                "      font-size: 28px;\n" +
                "      line-height: 46px;\n" +
                "      color: #75542f;\n" +
                "    }\n" +
                "\n" +
                "    .left-content .answer::before {\n" +
                "      content: '';\n" +
                "      position: absolute;\n" +
                "      top: 15px;\n" +
                "      left: 0;\n" +
                "      width: 10px;\n" +
                "      height: 10px;\n" +
                "      border-radius: 50%;\n" +
                "      background-color: currentColor;\n" +
                "    }\n" +
                "\n" +
                "    .right-content .qrcode {\n" +
                "      width: 172px;\n" +
                "      height: 176px;\n" +
                "      padding: 12px 0;\n" +
                "      text-align: center;\n" +
                "      background-color: #fffdfb;\n" +
                "      box-shadow: 0px 14px 70px 0px rgba(26, 21, 15, 0.1);\n" +
                "      margin: 0 auto;\n" +
                "    }\n" +
                "\n" +
                "    .right-content .qrcode img {\n" +
                "      line-height: 176px;\n" +
                "    }\n" +
                "\n" +
                "    .right-content p {\n" +
                "      text-align: center;\n" +
                "      margin-top: 15px;\n" +
                "      font-size: 22px;\n" +
                "      line-height: 22px;\n" +
                "      color: #442d12;\n" +
                "    }\n" +
                "  </style>\n" +
                "</head>\n" +
                "\n" +
                "<body>\n" +
                "  <div class=\"group-rank\">\n" +
                "    <div class=\"group-rank-header\">\n" +
                "      <div class=\"title\">排行榜</div>\n" +
                "      <p class=\"tips\">数据截止于"+mo+"月"+da+"日 24:00</p>\n" +
                "    </div>\n" +
                "    <div class=\"group-rank-list\">\n" +
                "      <table>\n" +
                "        <colgroup>\n" +
                "          <col width=\"100\">\n" +
                "          <col width=\"100\">\n" +
                "          <col>\n" +
                "          <col width=\"120\">\n" +
                "        </colgroup>\n" +
                "        <thead>\n" +
                "          <tr>\n" +
                "            <th>名次</th>\n" +
                "            <th>头像</th>\n" +
                "            <th>昵称</th>\n" +
                "            <th>元气值</th>\n" +
                "          </tr>\n" +
                "        </thead>\n" +
                "        <tbody>\n" +
                "        </tbody>\n" +
                "      </table>\n" +
                "    </div>\n" +
                "    <div class=\"group-rank-help\">\n" +
                "      <div class=\"left-content\">\n" +
                "        <div class=\"question\">什么是元气值？</div>\n" +
                "        <p class=\"answer\">元气值是根据群成员每天学习时长、坚持打卡天数、有效发言次数等因素评估得出。</p>\n" +
                "      </div>\n" +
                "      <div class=\"right-content\">\n" +
                "        <div class=\"qrcode\">\n" +
                "          <img\n" +
                "            src=\""+qrcodeUrl+"?x-oss-process=image/auto-orient,0/resize,p_100\"\n" +
                "            alt=\"qrcode\" width=\"153\" height=\"153\">\n" +
                "        </div>\n" +
                "        <p>扫码查看个人报告</p>\n" +
                "      </div>\n" +
                "    </div>\n" +
                "  </div>\n" +
                "</body>\n" +
                "\n" +
                "<script>\n" +
                "  var list = ["+list+
                "  ];\n" +
                "\n" +
                "  var html = '';\n" +
                "\n" +
                "  list.forEach((item, index) => {\n" +
                "    html += '<tr><td><span data-index=0' + index + ' class=index></span></td><td><img src=' + item.headPic +\n" +
                "      ' alt=\"headPic\" class=\"headPic\" width=\"64\" height=\"64\"></td><td class=\"nickName\"><span>' + item.nickName +\n" +
                "      '</span></td><td><span class=\"strength\">' + item.strength + '</span></td></tr>'\n" +
                "  });\n" +
                "\n" +
                "  document.querySelector('tbody').innerHTML = html;\n" +
                "</script>\n" +
                "\n" +
                "</html>";



        HtmlDto htmlDto=new HtmlDto();
        htmlDto.setHeight(1334);
        htmlDto.setWidth(750);
        htmlDto.setHtmlCode(s3);
        htmlDto.setSnapshot(new Long(System.currentTimeMillis()).toString());
        String pic = ResponseHandleUtil.parseResponse(htm2ImgService.toJPGByChrome(htmlDto),String.class);
        return pic;
    }
}
