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

import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.WeixinQrcodeBiz;
import com.pcloud.book.group.enums.AppAndProductTypeEnum;
import com.pcloud.book.group.tools.SendWeixinRequestTools;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.pcloudkeyword.enums.WelcomeReplyTypeEnum;
import com.pcloud.book.skill.biz.PcloudSubRemindBiz;
import com.pcloud.book.skill.check.PcloudSkillCheck;
import com.pcloud.book.skill.dao.*;
import com.pcloud.book.skill.entity.PcloudSubRemind;
import com.pcloud.book.skill.entity.PcloudSubReply;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskMapper;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.httpclient.UrlUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.pcloud.wechatgroup.group.dto.GroupRobotDTO;
import com.sdk.wxgroup.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Component("pcloudSubRemindBiz")
public class PcloudSubRemindBizImpl implements PcloudSubRemindBiz {

    @Autowired
    private PcloudSkillDao pcloudSkillDao;
    @Autowired
    private PcloudSubReplyDao pcloudSubReplyDao;
    @Autowired
    private PcloudSkillCheck pcloudSkillCheck;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private ResourceConsr resourceConsr;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private WeixinQrcodeBiz weixinQrcodeBiz;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private TimeControlTaskMapper taskMapper;
    @Autowired
    private PcloudResourceDao pcloudResourceDao;
    @Autowired
    private PcloudGroupActivityDao pcloudGroupActivityDao;

    @Autowired
    private PcloudSubRemindDao pcloudSubRemindDao;
    @Value("${wechat.group.link.prefix}")
    private String wechatGroupLinkPrefix;

    @Override
    @ParamLog("修改技能任务订阅状态")
    public void updateSubState(Integer relSkillId, Integer skillType, String wxUserId,Integer skillId) {
        pcloudSubRemindDao.updateSubState(relSkillId,skillType,wxUserId,skillId);
    }

    @Override
    public void sendTimeTaskMessage() {
        List<PcloudSubRemind> unSubRecord = pcloudSubRemindDao.getUnSubRecord();
        Date compareTime = new Date();
        SimpleDateFormat format= new SimpleDateFormat("yyyyMMddHHmm");
        for (PcloudSubRemind pcloudSubRemind : unSubRecord) {
            Date createTime =pcloudSubRemind.getCreateTime();
            List<PcloudSubReply> replyMsgList = pcloudSubReplyDao.getBySkillIdAndType(pcloudSubRemind.getSkillId(), 3);
            if(ListUtils.isEmpty(replyMsgList)){
                continue;
            }
            for (PcloudSubReply pcloudSubReply : replyMsgList) {
                Date sendTime = DateUtils.addMinute(createTime, pcloudSubReply.getRemindIntervalTime());
                if(format.format(sendTime).equals(format.format(compareTime))){
                    this.sendSubReplyMessage(Arrays.asList(pcloudSubReply), pcloudSubRemind.getRobotWxId(),  pcloudSubRemind.getWxUserId(),pcloudSubRemind.getRelSkillId(),pcloudSubRemind.getSkillType());
                }
            }
           // System.out.println(22);
        }
      //  System.out.println(11);
    }

    private void fillRelies(List<PcloudSubReply> replies) {
        if (ListUtils.isEmpty(replies)) {
            return;
        }
        List<Long> appIds = new ArrayList<>();
        List<Long> resourceIds = new ArrayList<>();
        for (PcloudSubReply reply : replies) {
            Integer type = reply.getType();
            if (ReplyTypeEnum.APP.value.equals(type)) {
                if (AppAndProductTypeEnum.APP.value.equals(reply.getServeType())) {
                    appIds.add(reply.getServeId());
                }
            }
            if (ReplyTypeEnum.RESOURCE.value.equals(type)) {
                resourceIds.add(reply.getResourceId());
            }
        }
        Map<Long, AppDto> appDtoMap = new HashMap<>();
        Map<Long, ResourceDTO> resourceDTOMap = new HashMap<>();
        if (!ListUtils.isEmpty(appIds)) {
            appDtoMap = appConsr.getBaseByIds(appIds);
        }

        if (!ListUtils.isEmpty(resourceIds)) {
            resourceDTOMap = resourceConsr.mapByIds(resourceIds);
        }
        for (PcloudSubReply reply : replies) {
            Integer type = reply.getType();
            if (ReplyTypeEnum.APP.value.equals(type)) {
                Long serveId = reply.getServeId();
                if (AppAndProductTypeEnum.APP.value.equals(reply.getServeType())) {
                    AppDto appDto = appDtoMap.get(serveId);
                    if (appDto != null) {
                        reply.setServePic(appDto.getSquareImg());
                        reply.setServeName(appDto.getTitle());
                        reply.setServeTypeCode(appDto.getTypeCode());
                        reply.setServeTypeName(appDto.getTypeName());
                    }
                }
            }
            if (ReplyTypeEnum.RESOURCE.value.equals(type)) {
                ResourceDTO resourceDTO = resourceDTOMap.get(reply.getResourceId());
                if (resourceDTO != null) {
                    reply.setResourceName(resourceDTO.getResourceName());
                    reply.setResourceUrl(resourceDTO.getFileUrl());
                    reply.setResourceTypeCode(resourceDTO.getTypeCode());
                    reply.setResourceTypeName(resourceDTO.getTypeName());
                    reply.setFileType(resourceDTO.getFileType());
                    reply.setResourcePdfItems(resourceDTO.getResourcePdfItems());
                    reply.setResourceOfficeItemDTOs(resourceDTO.getResourceOfficeItemDTOs());
                    reply.setFileSize(resourceDTO.getFileSize());
                }
            }
        }
    }

    private void sendSubReplyMessage(List<PcloudSubReply> subReplyList, String robotWxId, String userWxId, Integer relSkillId, Integer skillType) {
        this.fillRelies(subReplyList);
        for (PcloudSubReply reply : subReplyList) {
            Integer type = reply.getType();
            GroupRobotDTO groupRobotDTO = wechatGroupConsr.getGroupRobotByWxId(robotWxId);
            String ip = weixinQrcodeBiz.getRobotIpByGeneration(groupRobotDTO.getVersion());
            if (WelcomeReplyTypeEnum.TEXT.value.equals(type)) {
                SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
                sendTextMessageVO.setContent(reply.getContent());
                sendTextMessageVO.setAltId(robotWxId);
                sendTextMessageVO.setWxGroupId(userWxId);
                sendTextMessageVO.setIp(ip);
                sendTextMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
                WxGroupSDK.sendTextMessage(sendTextMessageVO);
            } else if (WelcomeReplyTypeEnum.IMAGE.value.equals(type)) {
                SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
                sendPicMessageVO.setWxGroupId(userWxId);
                sendPicMessageVO.setAltId(robotWxId);
                sendPicMessageVO.setPicUrl(reply.getPicUrl());
                sendPicMessageVO.setIp(ip);
                sendPicMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
                WxGroupSDK.sendPicMessage(sendPicMessageVO);
            } else if (WelcomeReplyTypeEnum.RESOURCE.value.equals(type)) {
                SendFileVO sendFileVO = new SendFileVO();
                sendFileVO.setFileUrl(reply.getResourceUrl());
                if (!StringUtil.isEmpty(reply.getResourceName())) {
                    sendFileVO.setFileName(reply.getResourceName().substring(0, reply.getResourceName().lastIndexOf(".")));
                }
                sendFileVO.setIp(ip);
                sendFileVO.setAltId(robotWxId);
                sendFileVO.setWxId(userWxId);
                sendFileVO.setCode(SendMessageTypeEnum.SELF.getCode());
                WxGroupSDK.sendFile(sendFileVO);
            } else if (ReplyTypeEnum.APP.value.equals(type)) {
                Long serveId = reply.getServeId();
                if (AppAndProductTypeEnum.APP.value.equals(reply.getServeType())) {
                    AppDto appDto = appConsr.getBaseById(serveId);
                    if (appDto != null) {
                        AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(appDto.getChannelId());
                        SendArticleMessageVO sendArticleMessageVO = new SendArticleMessageVO();
                        sendArticleMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
                        sendArticleMessageVO.setAltId(robotWxId);
                        sendArticleMessageVO.setDescription(reply.getDescription());
                        sendArticleMessageVO.setWxGroupId(userWxId);
                        // 处理链接地址
                        String endUrl = reply.getLinkUrl();
                        String linkUrl = SendWeixinRequestTools.splitUrl(accountSettingDto, endUrl);
                        sendArticleMessageVO.setLinkUrl(linkUrl);
                        sendArticleMessageVO.setPicUrl(reply.getPicUrl());
                        sendArticleMessageVO.setTitle(reply.getContent());
                        sendArticleMessageVO.setIp(ip);
                        WxGroupSDK.sendArticleMessage(sendArticleMessageVO);
                    }
                }
            }
            if (null != reply.getSubLinkConfirm() && reply.getSubLinkConfirm() == 1) {
                //封装退订提醒
                SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
                sendTextMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
                sendTextMessageVO.setWxId(robotWxId);
                sendTextMessageVO.setAltId(robotWxId);
                sendTextMessageVO.setWxGroupId(userWxId);
                sendTextMessageVO.setIp(ip);
                String content = reply.getSubLinkIntroduce();
                String baseUrl = wechatGroupLinkPrefix + "/dialog?";
                String finishLinkUrl = baseUrl + "wxId=" + userWxId + "&skillId=" + reply.getPcloudSkillId() + "&type=" + skillType + "&relSkillId=" + relSkillId + "&robotWxId=" + robotWxId;
                String resultUrl = UrlUtils.getShortUrl4Own(finishLinkUrl);
                content = content + "\n" + resultUrl;
                sendTextMessageVO.setContent(content);
                WxGroupSDK.sendTextMessage(sendTextMessageVO);
            }
        }
    }
}
