package com.pcloud.book.personal.biz.impl;

import com.google.common.collect.Lists;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.pcloudkeyword.biz.PcloudRobotBiz;
import com.pcloud.book.pcloudkeyword.biz.PcloudRobotClassifyBiz;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobot;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobotClassify;
import com.pcloud.book.personal.biz.PersonalMedalBiz;
import com.pcloud.book.personal.constants.MedalContants;
import com.pcloud.book.personal.dao.PersonalMedalDao;
import com.pcloud.book.personal.dao.PersonalMedalRecordDao;
import com.pcloud.book.personal.dao.PersonalStarRecordDao;
import com.pcloud.book.personal.dto.PersonalMedalRecordDto;
import com.pcloud.book.personal.dto.PersonalStarReceiveDto;
import com.pcloud.book.personal.entity.PersonalMedal;
import com.pcloud.book.personal.entity.PersonalMedalRecord;
import com.pcloud.book.personal.entity.PersonalShareTemplate;
import com.pcloud.book.personal.entity.PersonalStarRecord;
import com.pcloud.book.personal.enums.StarReceiveTypeEnum;
import com.pcloud.book.personal.mapper.PersonalShareTemplateMapper;
import com.pcloud.book.personalstage.dto.PersonalStageProgressDTO;
import com.pcloud.book.util.common.YesOrNoEnums;
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.ResponseHandleUtil;
import com.pcloud.facade.shareimage.dto.HtmlDto;
import com.pcloud.facade.shareimage.facade.Htm2ImgService;
import com.pcloud.readercenter.wechat.entity.WechatUser;
import com.pcloud.wechatgroup.group.dto.GroupRobotDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service("personalMedalBiz")
public class PersonalMedalBizImpl implements PersonalMedalBiz {

    @Autowired
    private PersonalMedalDao personalMedalDao;
    @Autowired
    private PersonalMedalRecordDao personalMedalRecordDao;
    @Autowired
    private PersonalStarRecordDao personalStarRecordDao;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private PcloudRobotBiz pcloudRobotBiz;
    @Autowired
    private Htm2ImgService htm2ImgService;
    @Autowired
    private PcloudRobotClassifyBiz pcloudRobotClassifyBiz;
    @Autowired
    private PersonalShareTemplateMapper personalShareTemplateMapper;

    @Override
    @ParamLog("获取基础勋章数据")
    public List<PersonalMedal> getBaseMedalList() {
        List<PersonalMedal> baseMedalList = personalMedalDao.getBaseMedalList();
        if(ListUtils.isEmpty(baseMedalList)){
            throw new BizException(BizException.DB_LIST_IS_NULL.getCode(),"未查询到勋章数据");
        }
        return baseMedalList;
    }

    @Override
    @ParamLog("获取用户已获得勋章数据")
    public List<PersonalMedalRecordDto> getUserMedalList(Long wechatUserId) {
        List<PersonalMedalRecordDto> userMedalList = personalMedalRecordDao.getUserMedalList(wechatUserId);
        if(ListUtils.isEmpty(userMedalList)){
            return Lists.newArrayList();
        }
        return userMedalList;
    }

    @Override
    @ParamLog("登录奖励星星")
    @Transactional(rollbackFor = Exception.class)
    public void loginReceiveStar(Long wechatUserId) {
        Date date = new Date();
        String receiveDate = DateUtils.getShortDateStr(date);
        // 查询用户今天是否领取过
        Integer count = personalStarRecordDao.hasReceive(wechatUserId, receiveDate, StarReceiveTypeEnum.LOGIN.key);
        //查询用户是否领取过第一次登陆的30颗星星
        Integer countFirstLogin = personalStarRecordDao.hasReceiveFirstLogin(wechatUserId, StarReceiveTypeEnum.FIRST_LOGIN.key);
        if(countFirstLogin!=null&&count==0){
            PersonalStarRecord starRecord = new PersonalStarRecord();
            starRecord.setWechatUserId(wechatUserId);
            starRecord.setStarCount(MedalContants.FIRST_LOGIN_RECEIVE_STAR_COUNT);
            starRecord.setType(StarReceiveTypeEnum.FIRST_LOGIN.key);
            starRecord.setReceiveDate(receiveDate);
            starRecord.setCreateTime(date);
            personalStarRecordDao.insert(starRecord);
        }

        if(count != null && count > 0){
            return;
        }
        PersonalStarRecord personalStarRecord = new PersonalStarRecord();
        personalStarRecord.setWechatUserId(wechatUserId);
        personalStarRecord.setStarCount(MedalContants.LOGIN_RECEIVE_STAR_COUNT);
        personalStarRecord.setType(StarReceiveTypeEnum.LOGIN.key);
        personalStarRecord.setReceiveDate(receiveDate);
        personalStarRecord.setCreateTime(date);
        // 如果没领取，则增加
        personalStarRecordDao.insert(personalStarRecord);
        // 尝试自动领取勋章
        autoReceiveMedal(wechatUserId);
    }

    @ParamLog("尝试自动领取勋章")
    public void autoReceiveMedal(Long wechatUserId){
        // 获取用户的星星数
        Integer starCount = personalStarRecordDao.getReceiveStarCount(wechatUserId);
        // 查询当前数量的星星可以领取的勋章(过滤掉已领取的)
        List<Long> medalIds = personalMedalDao.getReceivingMedal(wechatUserId, starCount);
        if(ListUtils.isEmpty(medalIds)){
            return;
        }
        // 插入可以领取的记录
        PersonalMedalRecord medalRecord;
        for (Long medalId : medalIds){
            medalRecord = new PersonalMedalRecord();
            medalRecord.setMedalId(medalId);
            medalRecord.setWechatUserId(wechatUserId);
            medalRecord.setHasShow(YesOrNoEnums.YES.getValue());
            // 插入领取记录
            personalMedalRecordDao.insert(medalRecord);
        }
    }

    @Override
    @ParamLog("用户已领取的星星数量")
    public Integer getReceiveStarCount(Long wechatUserId) {
        if(wechatUserId == null || wechatUserId == 0){
            throw new BizException(BizException.PARAM_IS_NULL.getCode(),"wechatUserId 不能为空");
        }
        return personalStarRecordDao.getReceiveStarCount(wechatUserId);
    }

    @Override
    @ParamLog("更新勋章为已展示")
    public void updateMedalShowed(Long medalRecordId){
        PersonalMedalRecord medalRecord = new PersonalMedalRecord();
        medalRecord.setId(medalRecordId);
        medalRecord.setHasShow(YesOrNoEnums.NO.getValue());
        personalMedalRecordDao.update(medalRecord);
    }

    @Override
    @ParamLog("完善基础资料、喜欢的频道领取星星")
    @Transactional(rollbackFor = Exception.class)
    public void receiveStar(Long wechatUserId, StarReceiveTypeEnum starReceiveTypeEnum){
        if(!starReceiveTypeEnum.key.equals(StarReceiveTypeEnum.BASE_INFO.key) && !starReceiveTypeEnum.key.equals(StarReceiveTypeEnum.LIKE.key)){
            log.info("错误的【StarReceiveTypeEnum】类型：" + starReceiveTypeEnum.toString());
            return;
        }
        // 查询用户是否领取过
        Integer count = personalStarRecordDao.hasReceive(wechatUserId, null, starReceiveTypeEnum.key);
        if(count != null && count > 0){
            return;
        }
        Date date = new Date();
        String receiveDate = DateUtils.getShortDateStr(date);
        Integer starCount = starReceiveTypeEnum.key.equals(StarReceiveTypeEnum.BASE_INFO.key) ? MedalContants.BASE_INFO_RECEIVE_STAR_COUNT : MedalContants.LIKE_RECEIVE_STAR_COUNT;
        PersonalStarRecord personalStarRecord = new PersonalStarRecord();
        personalStarRecord.setWechatUserId(wechatUserId);
        personalStarRecord.setStarCount(starCount);
        personalStarRecord.setType(starReceiveTypeEnum.key);
        personalStarRecord.setReceiveDate(receiveDate);
        personalStarRecord.setCreateTime(date);
        // 如果没领取，则增加
        personalStarRecordDao.insert4Type(personalStarRecord);
        // 尝试自动领取勋章
        autoReceiveMedal(wechatUserId);
    }

    @Override
    @ParamLog("分享")
    public String shareMedal(Long wechatUserId, String robotWxId) {
        // 获取用户基本信息
        WechatUser wechatUser = readerConsr.getWechatUser(wechatUserId);
        Integer loginDays =  getLoginDays(wechatUserId);
        // 获取小号信息
        PcloudRobot pcloudRobot = pcloudRobotBiz.getPcloudRobotByWxId(robotWxId);
        PcloudRobotClassify pcloudRobotClassify = null;
        if (null != pcloudRobot){
             pcloudRobotClassify = pcloudRobotClassifyBiz.getClassifyById(Long.valueOf(pcloudRobot.getRobotType().toString()));
        }
        // 获取勋章信息
        List<PersonalMedalRecordDto> personalMedalRecordDtos = getUserMedalList(wechatUserId);
        if(wechatUser == null){
            throw new BizException(BizException.DB_DML_FAIL.getCode(), "未找到用户信息");
        }
        if(pcloudRobot == null){
            throw new BizException(BizException.DB_DML_FAIL.getCode(), "未找到小号信息");
        }
        if(ListUtils.isEmpty(personalMedalRecordDtos)){
            throw new BizException(BizException.DB_DML_FAIL.getCode(), "未找到勋章信息");
        }
        String html = null;
        if (personalMedalRecordDtos.size() == 1){
            //只生成大图
            html = buildMedalHtml4Big(personalMedalRecordDtos.get(0), wechatUser, pcloudRobotClassify,loginDays);
        }else {
            //多个小图
            html = buildMedalHtml4Little(personalMedalRecordDtos, wechatUser, pcloudRobotClassify,loginDays);
        }
        HtmlDto htmlDto=new HtmlDto();
        htmlDto.setHeight(1206);
        htmlDto.setWidth(750);
        htmlDto.setHtmlCode(html);
        htmlDto.setSnapshot(new Long(System.currentTimeMillis()).toString());
        return ResponseHandleUtil.parseResponse(htm2ImgService.toJPGByChrome(htmlDto),String.class);
    }

    private String buildMedalHtml4Little(List<PersonalMedalRecordDto> personalMedalRecordDtos, WechatUser wechatUser, PcloudRobotClassify pcloudRobotClassify, Integer loginDays) {
        PersonalShareTemplate personalShareTemplate = personalShareTemplateMapper.selectByPrimaryKey(2);
        String html = personalShareTemplate.getContent();
        html = html.replace("${headUrl}",wechatUser.getWechatUserHeadurl());
        html = html.replace("${nickName}",wechatUser.getWechatUserNickname());
        html = html.replace("${loginDays}",loginDays.toString());
        html = html.replace("${classifyQrcode}",pcloudRobotClassify.getQrcodeUrl());
        html = html.replace("${medalCount}",personalMedalRecordDtos.size()+"");
        String medalImg = "";
        for(PersonalMedalRecordDto personalMedalRecordDto : personalMedalRecordDtos){
            medalImg +=  "<img src='"+personalMedalRecordDto.getLightImgUrl()+"'class=\"medal\" />";
        }
        html = html.replace("${medalImgs}",medalImg);
        return  html;
    }

    private String buildMedalHtml4Big(PersonalMedalRecordDto personalMedalRecordDto, WechatUser wechatUser, PcloudRobotClassify pcloudRobotClassify, Integer loginDays) {
        PersonalShareTemplate personalShareTemplate = personalShareTemplateMapper.selectByPrimaryKey(1);
        String html = personalShareTemplate.getContent();
        html = html.replace("${headUrl}",wechatUser.getWechatUserHeadurl());
        html = html.replace("${nickName}",wechatUser.getWechatUserNickname());
        html = html.replace("${loginDays}",loginDays.toString());
        html = html.replace("${classifyQrcode}",pcloudRobotClassify.getQrcodeUrl());
        return  html;
    }

    @Override
    public Integer getRanking(Long wechatUserId) {
        Integer ranking=0;
      List<PersonalStarReceiveDto> list= personalStarRecordDao.getReceiveStarCountList();
      if(list==null||list.size()==0){
          return ranking;
      }

      for (int i=0;i<=list.size()-1;i++){
          PersonalStarReceiveDto personalStarReceiveDto = list.get(i);
          if(personalStarReceiveDto.getWechatUserId().equals(wechatUserId)){
            ranking=i+1;
            return ranking;
          }
      }

        return ranking;
    }

    @Override
    public Integer getLoginDays(Long wechatUserId) {
        return personalStarRecordDao.getLoginDays(wechatUserId);
    }

    @Override
    public Integer getMedalAllDays(Long wechatUserId, Integer medalDays) {
       Integer conut= personalStarRecordDao.getTaskCount(wechatUserId);
       Integer medalAllDays=medalDays-(conut*30)-30;
        return medalAllDays;
    }


    private String buildMedalHtml(PersonalMedal medal, WechatUser wechatUser, PcloudRobot pcloudRobot) {
        return "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "  <meta charset=\"GBK\">\n" +
                "  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "  <title>Document</title>\n" +
                "</head>\n" +
                "<style>\n" +
                "  *{\n" +
                "    margin: 0;\n" +
                "    padding: 0;\n" +
                "  }\n" +
                "  .headBg {\n" +
                "    position: absolute;\n" +
                "    top: 150px;\n" +
                "    height: 686px;\n" +
                "    left: 50%;\n" +
                "    margin-left: -300px;\n" +
                "  }\n" +
                "  .Img {\n" +
                "    width: 750px;\n" +
                "    height: 100vh;\n" +
                "  }\n" +
                "  .header {\n" +
                "    height: 370px;\n" +
                "    color: white;\n" +
                "    position: relative;\n" +
                "    overflow: hidden;\n" +
                "     \n" +
                "  }\n" +
                "  .goBack {\n" +
                "    margin-top: 30px;\n" +
                "    margin-left: 30px;\n" +
                "    width: 100px;\n" +
                "  }\n" +
                "  .sharInfoBox {\n" +
                "    position: absolute;\n" +
                "    top: 119px;\n" +
                "    left: 50%;\n" +
                "    margin-left: -375px;\n" +
                "  }\n" +
                "  .Img {\n" +
                "    width: 690px;\n" +
                "    height: 972px;\n" +
                "  }\n" +
                "  .head {\n" +
                "    position: absolute;\n" +
                "    height: 150px;\n" +
                "    width: 150px;\n" +
                "    top: 75px;\n" +
                "    left: 50%;\n" +
                "    margin-left: -75px;\n" +
                "    border-radius: 50%!important;\n" +
                "    background-image: url(https://file.5rs.me/oss/uploadfe/png/5cda5008f3334ea44a50092afaae3a28.png);\n" +
                "    background-size: auto;\n" +
                "    background-repeat: no-repeat;\n" +
                "    background-position: center;\n" +
                "  }\n" +
                "  h1 {\n" +
                "    position: relative;\n" +
                "    top: 229px;\n" +
                "    /* color: #1b7ec4; */\n" +
                "    color: black;\n" +
                "    font-size: 44px;\n" +
                "    margin: 0 auto;\n" +
                "    text-align: center;\n" +
                "  }\n" +
                "  .medal {\n" +
                "    z-index: 2;\n" +
                "    position: absolute;\n" +
                "    top: 296px;\n" +
                "    height: 330px;\n" +
                "    width: 330px;\n" +
                "    border-radius: 50%;\n" +
                "    left: 50%;\n" +
                "    margin-left: -165px;\n" +
                "  }\n" +
                "  .medalLevel {\n" +
                "    font-size: 36px;\n" +
                "    color: #333;\n" +
                "    position: relative;\n" +
                "    top: 586px;\n" +
                "    margin: 0 auto;\n" +
                "    text-align: center;\n" +
                "  }\n" +
                "  .medalDesc {\n" +
                "    font-size: 28px;\n" +
                "    color: #333;\n" +
                "    position: absolute;\n" +
                "    top: 720px;\n" +
                "    left: 50%;\n" +
                "    margin-left: -209px;\n" +
                "  }\n" +
                "  .qrcode {\n" +
                "    width: 183px;\n" +
                "    height: 183px;\n" +
                "    position: absolute;\n" +
                "    top: 890px;\n" +
                "    left: 9%;\n" +
                "  }\n" +
                "  .ShareInfo {\n" +
                "    position: relative;\n" +
                "    height: 100vh;\n" +
                "    background-image: linear-gradient(126deg, #3a82ee 0%, #3a67ee 50%, #3a4bee 100%), linear-gradient(#3a82ee, #3a82ee);\n" +
                "    background-blend-mode: normal, normal;\n" +
                "  }\n" +
                "  .longPress {\n" +
                "    width: 358px;\n" +
                "    height: 183px;\n" +
                "    position: absolute;\n" +
                "    top: 840px;\n" +
                "    left: 40%;\n" +
                "  }\n" +
                "  p {\n" +
                "    font-size: 24px;\n" +
                "    color: #666;\n" +
                "    margin-top: 12px;\n" +
                "  }\n" +
                "  .shadows {\n" +
                "    top: 120px;\n" +
                "    position: absolute;\n" +
                "    width: 286px;\n" +
                "    height: 15px;\n" +
                "    background-color: #fbbf1f;\n" +
                "  }\n" +
                "  .shadow {\n" +
                "    top: 68px;\n" +
                "    position: absolute;\n" +
                "    width: 286px;\n" +
                "    height: 15px;\n" +
                "    background-color: #fbbf1f;\n" +
                "  }\n" +
                "  h3 {\n" +
                "    margin-top: 44px;\n" +
                "    position: relative;\n" +
                "    font-size: 32px;\n" +
                "    color: #1a2235;\n" +
                "    font-weight: bold;\n" +
                "    z-index: 2;\n" +
                "  }\n" +
                "  .double{\n" +
                "    margin-top: 7px;\n" +
                "  }\n" +
                "</style>\n"+
                "<body>\n" +
                "  <div class=\"ShareInfo\">\n" +
                "    <div class=\"sharInfoBox\">\n" +
                "      <!-- 大背景图照片 -->\n" +
                "      <img src='https://file.5rs.me/oss/uploadfe/png/10c414d99b869c8bc8c2d064de60cfe4.png' />\n" +
                "    </div>\n" +
                "    <img src='"+ wechatUser.getWechatUserHeadurl() +"' class=\"head\" />\n" +
                "    <h1>"+ wechatUser.getWechatUserNickname() +"</h1>\n" +
                "    <img src='"+ medal.getBigImgUrl() +"'class=\"medal\" />\n" +
                "    <h2 class=\"medalLevel\">" + medal.getMedalName() +"</h2>\n" +
                "    <p class=\"medalDesc\">"+ (medal.getContent() == null ? "" : medal.getContent()) +"</p>\n" +
                "    <img src='"+ pcloudRobot.getQrcodeUrl() +"' class=\"qrcode\" />\n" +
                "    <div class=\"longPress\">\n" +
                "      <div class=\"shadow\"></div>\n" +
                "      <div class=\"shadows\"></div>\n" +
                "      <h3>学习太累快加小睿</h3>\n" +
                "      <h3 class=\"double\">学习效率马上翻倍</h3>\n" +
                "      <p>长按转发，把我介绍给你的朋友吧或长按名片保存到手机</p>\n" +
                "    </div>\n" +
                "    <img src='https://file.5rs.me/oss/uploadfe/png/e4bfffe37f09e74b73db4a6b467635ad.png' class=\"headBg\" />\n" +
                "  </div>\n" +
                "</body>\n" +
                "</html>";
    }
}
