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

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.guide.mapper.PcloudRobotSilenceMapper;
import com.pcloud.book.pcloudkeyword.biz.PcloudRobotBiz;
import com.pcloud.book.pcloudkeyword.dao.PcloudClassifyTemplateDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudKeywordClassifyDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotQrcodeDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotWelcomeDao;
import com.pcloud.book.pcloudkeyword.entity.PcloudClassifyTemplate;
import com.pcloud.book.pcloudkeyword.entity.PcloudKeywordClassify;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobot;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobotQrcode;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobotWelcome;
import com.pcloud.book.pcloudkeyword.enums.WelcomeReplyTypeEnum;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.QrcodeUtils;
import com.pcloud.common.utils.httpclient.UrlUtils;
import com.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.sdk.wxgroup.SendFileVO;
import com.sdk.wxgroup.SendMessageTypeEnum;
import com.sdk.wxgroup.SendPicMessageVO;
import com.sdk.wxgroup.SendTextMessageVO;
import com.sdk.wxgroup.WxGroupSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("pcloudRobotBiz")
public class PcloudRobotBizImpl implements PcloudRobotBiz {

    @Autowired
    private PcloudRobotDao pcloudRobotDao;
    @Autowired
    private PcloudRobotWelcomeDao pcloudRobotWelcomeDao;
    @Autowired
    private ResourceConsr resourceConsr;
    @Autowired
    private PcloudKeywordClassifyDao pcloudKeywordClassifyDao;
    @Autowired
    private PcloudRobotQrcodeDao pcloudRobotQrcodeDao;
    @Value("${wechat.group.link.prefix}")
    private String wechatLinkPrefix;
    @Autowired
    private PcloudRobotSilenceMapper pcloudRobotSilenceMapper;
    @Autowired
    private PcloudClassifyTemplateDao pcloudClassifyTemplateDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPcloudRobot(PcloudRobot pcloudRobot) {
        pcloudRobotDao.insert(pcloudRobot);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePcloudRobot(PcloudRobot pcloudRobot) {
        pcloudRobotDao.update(pcloudRobot);
        if(pcloudRobot.getRobotType() != null) {
            PcloudRobotQrcode robotQrcode = pcloudRobotQrcodeDao.getByRobotType(pcloudRobot.getRobotType());
            if(robotQrcode == null) {
                PcloudRobotQrcode pcloudRobotQrcode = new PcloudRobotQrcode();
                pcloudRobotQrcode.setRobotType(pcloudRobot.getRobotType());
                String linkUrl = wechatLinkPrefix + "/group/info?classify_id=" + pcloudRobot.getRobotType();
                String codeUrl = QrcodeUtils.create( UrlUtils.getShortUrl4Own(linkUrl));
                pcloudRobotQrcode.setLinkUrl(linkUrl);
                pcloudRobotQrcode.setQrcodeUrl(codeUrl);
                pcloudRobotQrcodeDao.insert(pcloudRobotQrcode);
            }
        }
        List<PcloudRobotWelcome> robotWelcomeList = pcloudRobot.getRobotWelcomeList();
        pcloudRobotWelcomeDao.deleteByPcloudRobotId(pcloudRobot.getId());
        if (ListUtils.isEmpty(robotWelcomeList)){
            return;
        }
        pcloudRobotWelcomeDao.batchInsert(robotWelcomeList);
    }

    @Override
    @ParamLog
    public PageBeanNew<PcloudRobot> getPcloudRobotList(String nickName, Integer currentPage, Integer numPerPage) {
        if (currentPage == null || currentPage < 0 || numPerPage == null || numPerPage <= 0) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "分页参数错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("nickName", nickName);
        PageBeanNew<PcloudRobot> pageBeanNew = pcloudRobotDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getPcloudRobotList");
        for (PcloudRobot pcloudRobot : pageBeanNew.getRecordList()) {
            List<PcloudRobotWelcome> robotWelcomeList = pcloudRobotWelcomeDao.getRobotWelcomeListByPcloudRobotId(pcloudRobot.getId());
            fillRobotWelcome(robotWelcomeList);
            pcloudRobot.setRobotWelcomeList(robotWelcomeList);
            if(pcloudRobot.getKeywordClassifyId() != null) {
                PcloudKeywordClassify pcloudKeywordClassify = pcloudKeywordClassifyDao.getById(pcloudRobot.getKeywordClassifyId());
                pcloudRobot.setKeywordClassifyName(pcloudKeywordClassify == null ? "" : pcloudKeywordClassify.getKeywordClassify());
            }
            if(pcloudRobot.getRobotType() != null) {
                PcloudRobotQrcode robotQrcode = pcloudRobotQrcodeDao.getByRobotType(pcloudRobot.getRobotType());
                pcloudRobot.setEntryQrcodeUrl(robotQrcode == null ? "" : robotQrcode.getQrcodeUrl());
            } else {
                pcloudRobot.setEntryQrcodeUrl("");
            }
        }
        return pageBeanNew;
    }

    @Override
    @ParamLog
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdatePcloudRobotWelcome(List<PcloudRobotWelcome> robotWelcomeList) {
        if (ListUtils.isEmpty(robotWelcomeList)){
            return;
        }
        Long pcloudRobotId = robotWelcomeList.get(0).getPcloudRobotId();
        pcloudRobotWelcomeDao.deleteByPcloudRobotId(pcloudRobotId);
        pcloudRobotWelcomeDao.batchInsert(robotWelcomeList);
    }

    @Override
    @ParamLog
    public PcloudRobot getPcloudRobot(Long id) {
        PcloudRobot pcloudRobot = pcloudRobotDao.getById(id);
        if(pcloudRobot != null) {
            pcloudRobot.setSilenceDuration(pcloudRobotSilenceMapper.getSilenceDurationByRobotWxId(pcloudRobot.getWxId()));
            List<PcloudRobotWelcome> robotWelcomeList = pcloudRobotWelcomeDao.getRobotWelcomeListByPcloudRobotId(pcloudRobot.getId());
            fillRobotWelcome(robotWelcomeList);
            pcloudRobot.setRobotWelcomeList(robotWelcomeList);
        }
        return pcloudRobot;
    }

    @Override
    public void sendWelcomeReply(String robotWxId, String userWxId, String ip) {
        Map<String, Object> map = new HashMap<>();
        map.put("robotWxId", robotWxId);
        PcloudRobot pcloudRobot = (PcloudRobot)pcloudRobotDao.getBy(map, "getByRobotWxId");
        if(pcloudRobot != null) {
            List<PcloudRobotWelcome> robotWelcomeList = pcloudRobotWelcomeDao.getRobotWelcomeListByPcloudRobotId(pcloudRobot.getId());
            fillRobotWelcome(robotWelcomeList);
            for (PcloudRobotWelcome robotWelcome : robotWelcomeList) {
                Integer replyType = robotWelcome.getReplyType();
                if(WelcomeReplyTypeEnum.TEXT.value.equals(replyType)) {
                    SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
                    sendTextMessageVO.setContent(robotWelcome.getContent());
                    sendTextMessageVO.setAltId(robotWxId);
                    sendTextMessageVO.setWxGroupId(userWxId);
                    sendTextMessageVO.setIp(ip);
                    sendTextMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
                    WxGroupSDK.sendTextMessage(sendTextMessageVO);
                } else if(WelcomeReplyTypeEnum.IMAGE.value.equals(replyType)) {
                    SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
                    sendPicMessageVO.setWxGroupId(userWxId);
                    sendPicMessageVO.setAltId(robotWxId);
                    sendPicMessageVO.setPicUrl(robotWelcome.getPicUrl());
                    sendPicMessageVO.setIp(ip);
                    sendPicMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
                    WxGroupSDK.sendPicMessage(sendPicMessageVO);
                } else if(WelcomeReplyTypeEnum.RESOURCE.value.equals(replyType)) {
                    SendFileVO sendFileVO = new SendFileVO();
                    sendFileVO.setFileUrl(robotWelcome.getResourceUrl());
                    sendFileVO.setFileName(robotWelcome.getResourceName());
                    sendFileVO.setIp(ip);
                    sendFileVO.setAltId(robotWxId);
                    sendFileVO.setWxId(userWxId);
                    sendFileVO.setCode(SendMessageTypeEnum.SELF.getCode());
                    WxGroupSDK.sendFile(sendFileVO);
                }
            }
            //发送H5链接
            String endUrl = wechatLinkPrefix + "/dialog" + "?book_group_id=" + 0 + "&wxId=" + userWxId + "&robotWxId=" + robotWxId;
            String resultUrl = UrlUtils.getShortUrl4Own(endUrl);
            String h5Content = "你可以通过点击" + resultUrl + "，或者输入【】内关键词唤醒我\n" + "小睿会在这里时时陪伴你";
            SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
            sendTextMessageVO.setContent(h5Content);
            sendTextMessageVO.setAltId(robotWxId);
            sendTextMessageVO.setWxGroupId(userWxId);
            sendTextMessageVO.setIp(ip);
            sendTextMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
            WxGroupSDK.sendTextMessage(sendTextMessageVO);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void relateKeywordClassify(Long pcloudRobotId, Long keywordClassifyId) {
        PcloudRobot pcloudRobot = new PcloudRobot();
        pcloudRobot.setId(pcloudRobotId);
        pcloudRobot.setKeywordClassifyId(keywordClassifyId);
        pcloudRobotDao.update(pcloudRobot);
    }

    @Override
    public PcloudRobot getPcloudRobotByType(Integer robotType) {
        return pcloudRobotDao.getPcloudRobotByType(robotType);
    }

    @Override
    public PageBeanNew<PcloudClassifyTemplate> listClassifyTemplate(Integer classifyId, Integer currentPage, Integer numPerPage) {
        if (currentPage == null || currentPage < 0 || numPerPage == null || numPerPage <= 0) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "分页参数错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("classifyId", classifyId);
        return pcloudClassifyTemplateDao.listPageNew(new PageParam(currentPage, numPerPage), map, "listClassifyTemplate");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void openTemplate(Integer classifyId, Long templateId) {
        PcloudClassifyTemplate template = new PcloudClassifyTemplate();
        template.setClassifyId(classifyId);
        template.setIsOpen(false);
        pcloudClassifyTemplateDao.updateOpenStateByClassifyId(template);
        template.setId(templateId);
        template.setIsOpen(true);
        pcloudClassifyTemplateDao.updateOpenStateById(template);
    }

    @Override
    public PcloudClassifyTemplate getTemplateByClassifyId(Integer classifyId) {
        return pcloudClassifyTemplateDao.getTemplateByClassifyId(classifyId);
    }

    @ParamLog("填充欢迎语回复")
    private void fillRobotWelcome(List<PcloudRobotWelcome> robotWelcomeList) {
        if(ListUtils.isEmpty(robotWelcomeList)){
            return;
        }
        List<Long> resourceIds=new ArrayList<>();
        for (PcloudRobotWelcome robotWelcome : robotWelcomeList){
            Integer type = robotWelcome.getReplyType();
            if (WelcomeReplyTypeEnum.RESOURCE.value.equals(type)){
                resourceIds.add(robotWelcome.getResourceId());
            }
        }
        Map<Long, ResourceDTO> resourceDTOMap=new HashMap<>();
        if (!ListUtils.isEmpty(resourceIds)){
            resourceDTOMap = resourceConsr.mapByIds(resourceIds);
        }
        for (PcloudRobotWelcome robotWelcome : robotWelcomeList){
            Integer type = robotWelcome.getReplyType();
            if (WelcomeReplyTypeEnum.RESOURCE.value.equals(type)){
                ResourceDTO resourceDTO = resourceDTOMap.get(robotWelcome.getResourceId());
                if (resourceDTO != null){
                    robotWelcome.setResourceName(resourceDTO.getResourceName());
                    robotWelcome.setResourceUrl(resourceDTO.getFileUrl());
                    robotWelcome.setResourceTypeCode(resourceDTO.getTypeCode());
                    robotWelcome.setResourceTypeName(resourceDTO.getTypeName());
                    robotWelcome.setFileType(resourceDTO.getFileType());
                    robotWelcome.setFileSize(resourceDTO.getFileSize());
                    robotWelcome.setResourcePdfItems(resourceDTO.getResourcePdfItems());
                    robotWelcome.setResourceOfficeItemDTOs(resourceDTO.getResourceOfficeItemDTOs());
                }
            }
        }
    }
}
