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

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.pcloudKeyword.dto.PcloudRobotDTO;
import com.pcloud.book.pcloudKeyword.dto.RobotClassifyDTO;
import com.pcloud.book.pcloudkeyword.biz.PcloudRobotClassifyBiz;
import com.pcloud.book.pcloudkeyword.dao.PcloudClassifyTemplateDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotClassifyDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotWelcomeDao;
import com.pcloud.book.pcloudkeyword.dto.ClassifyWelcomeDTO;
import com.pcloud.book.pcloudkeyword.dto.PcloudRobotCountDTO;
import com.pcloud.book.pcloudkeyword.entity.PcloudClassifyTemplate;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobotClassify;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobotWelcome;
import com.pcloud.book.pcloudkeyword.enums.PcloudGroupRobotTypeEnum;
import com.pcloud.book.pcloudkeyword.facade.response.PcloudRobotClassifyResponseVO;
import com.pcloud.book.pcloudkeyword.set.PcloudRobotSet;
import com.pcloud.book.pcloudkeyword.vo.ClassifySeqNumUpdateVO;
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.ResponseHandleUtil;
import com.pcloud.common.utils.httpclient.UrlUtils;
import com.pcloud.facade.wechat.service.QrcodeService;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class PcloudRobotClassifyBizImpl implements PcloudRobotClassifyBiz {

    @Resource
    private PcloudRobotClassifyDao pcloudRobotClassifyDao;
    @Value("${wechat.group.link.prefix}")
    private String wechatLinkPrefix;
    @Resource
    private PcloudRobotWelcomeDao pcloudRobotWelcomeDao;
    @Autowired
    private PcloudRobotSet pcloudRobotSet;
    @Autowired
    private PcloudClassifyTemplateDao pcloudClassifyTemplateDao;
    @Autowired
    private QrcodeService qrcodeService;
    @Autowired
    private PcloudRobotDao pcloudRobotDao;

    @Override
    public List<PcloudRobotClassifyResponseVO> listAllRobotClassify() {
        return pcloudRobotClassifyDao.listAllRobotClassify();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void saveRobotClassify(String classifyName) {
        PcloudRobotClassify classify = new PcloudRobotClassify();
        classify.setClassifyName(classifyName);
        classify.setIsDelete(0);
        pcloudRobotClassifyDao.insert(classify);
        String linkUrl = wechatLinkPrefix + "/group/info?classify_id=" + classify.getId();
        String codeUrl = QrcodeUtils.create( UrlUtils.getShortUrl4Own(linkUrl));
        String url = ResponseHandleUtil.parseResponse(qrcodeService.create4MiniApp(777L, String.valueOf(classify.getId()), null, null), String.class);
        if (null != url) {
            pcloudRobotClassifyDao.updateMiniAppQr(classify.getId(), url);
        }
        classify.setLinkUrl(linkUrl);
        classify.setQrcodeUrl(codeUrl);
        classify.setSeqNum(classify.getId().intValue());
        pcloudRobotClassifyDao.update(classify);
        //新增默认模板
        PcloudClassifyTemplate classifyTemplate = new PcloudClassifyTemplate();
        classifyTemplate.setClassifyId(classify.getId().intValue());
        classifyTemplate.setTemplateCode("common_template");
        pcloudClassifyTemplateDao.insert(classifyTemplate);

    }

    @Override
    public void updateRobotClassify(PcloudRobotClassify classify) {
        pcloudRobotClassifyDao.update(classify);
    }

    @Override
    public PcloudRobotClassify getClassifyById(Long id) {
        return pcloudRobotClassifyDao.getById(id);
    }

    @Override
    public PageBeanNew<PcloudRobotClassifyResponseVO> listClassifyByPage(Integer currentPage, Integer numPerPage,Boolean testShow) {
        Map<String,Object> map=new HashMap<>();
        map.put("testShow",testShow);
        PageBeanNew<PcloudRobotClassifyResponseVO> listClassifyByPage = pcloudRobotClassifyDao.listPageNew(new PageParam(currentPage, numPerPage), map, "listClassifyByPage");
        if(ListUtils.isEmpty(listClassifyByPage.getRecordList())){
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        List<Long> classifyIds = listClassifyByPage.getRecordList().stream().map(a -> a.getId()).distinct().collect(Collectors.toList());
        Map<Long, PcloudRobotDTO> pcloudRobotDTOMap = pcloudRobotDao.getValidPcloudRobotMapByType(classifyIds);
        List<PcloudRobotCountDTO> pcloudRobotCount = pcloudRobotDao.getPcloudRobotCount(classifyIds);
        Map<String, Integer> robotCountMap = new HashMap<>();
        if(!ListUtils.isEmpty(pcloudRobotCount)){
            robotCountMap =pcloudRobotCount.stream().collect(Collectors.toMap(a -> a.getClassifyAndRobotType(), a -> a.getCount(), (k1, k2) -> k2));
        }
        for (PcloudRobotClassifyResponseVO pcloudRobotClassifyResponseVO : listClassifyByPage.getRecordList()) {
            String wxCountkey=pcloudRobotClassifyResponseVO.getId()+"-"+ PcloudGroupRobotTypeEnum.WXROBOT.value;
            String qqCountkey=pcloudRobotClassifyResponseVO.getId()+"-"+ PcloudGroupRobotTypeEnum.QQROBOT.value;
            pcloudRobotClassifyResponseVO.setRobotCount(0);
            pcloudRobotClassifyResponseVO.setQqRobotCount(0);
            if(MapUtils.isNotEmpty(robotCountMap) && robotCountMap.containsKey(wxCountkey)){
                pcloudRobotClassifyResponseVO.setRobotCount(null==robotCountMap.get(wxCountkey)?0:robotCountMap.get(wxCountkey));
            }
            if(MapUtils.isNotEmpty(robotCountMap) && robotCountMap.containsKey(qqCountkey)){
                pcloudRobotClassifyResponseVO.setQqRobotCount(null==robotCountMap.get(qqCountkey)?0:robotCountMap.get(qqCountkey));
            }
            if(MapUtils.isNotEmpty(pcloudRobotDTOMap) && pcloudRobotDTOMap.containsKey(pcloudRobotClassifyResponseVO.getId().intValue())){
                pcloudRobotClassifyResponseVO.setValidRobotQrcodeUrl(pcloudRobotDTOMap.get(pcloudRobotClassifyResponseVO.getId().intValue()).getQrcodeUrl());
            }
        }
        return listClassifyByPage;
    }

    @Override
    public PageBeanNew<PcloudRobotClassifyResponseVO> listClassifyByPage4Mini(Integer currentPage, Integer numPerPage) {
        PageBeanNew<PcloudRobotClassifyResponseVO> listClassifyByPage = pcloudRobotClassifyDao.listPageNew(new PageParam(currentPage, numPerPage), new HashMap<>(), "listClassifyByPage");
        if(ListUtils.isEmpty(listClassifyByPage.getRecordList())){
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        List<Long> classifyIds = listClassifyByPage.getRecordList().stream().map(a -> a.getId()).distinct().collect(Collectors.toList());
        Map<Long, PcloudRobotDTO> pcloudRobotDTOMap = pcloudRobotDao.getValidPcloudRobotMapByType(classifyIds);
        for (PcloudRobotClassifyResponseVO pcloudRobotClassifyResponseVO : listClassifyByPage.getRecordList()) {
            if (MapUtils.isNotEmpty(pcloudRobotDTOMap) && pcloudRobotDTOMap.containsKey(pcloudRobotClassifyResponseVO.getId().intValue())) {
                pcloudRobotClassifyResponseVO.setValidRobotQrcodeUrl(pcloudRobotDTOMap.get(pcloudRobotClassifyResponseVO.getId().intValue()).getQrcodeUrl());
            }
        }
        return listClassifyByPage;
    }

    @Override
    public ClassifyWelcomeDTO getClassifyWelcome(Long classifyId,Integer robotType) {
        ClassifyWelcomeDTO classifyWelcomeDTO = new ClassifyWelcomeDTO();
        List<PcloudRobotWelcome> pcloudRobotWelcomeList = pcloudRobotWelcomeDao.getRobotWelcomeListByPcloudClassifyId(classifyId,robotType);
        if(pcloudRobotWelcomeList!=null&&pcloudRobotWelcomeList.size()>0){
            classifyWelcomeDTO.setIsOpenPushH5url(pcloudRobotWelcomeList.get(0).getIsOpenPushH5url());
            classifyWelcomeDTO.setWelcomeDuration(pcloudRobotWelcomeList.get(0).getWelcomeDuration());
        }
        pcloudRobotSet.fillRobotWelcome(pcloudRobotWelcomeList);
        classifyWelcomeDTO.setPcloudRobotWelcomeList(pcloudRobotWelcomeList);
        return classifyWelcomeDTO;
    }

    @Override
    public void updateClassifyWelcome(ClassifyWelcomeDTO classifyWelcomeDTO) {
       // pcloudRobotClassifyDao.updateWelcomeDuration(classifyWelcomeDTO.getPcloudClassifyId(), classifyWelcomeDTO.getWelcomeDuration(),classifyWelcomeDTO.getIsOpenPushH5url());
        List<PcloudRobotWelcome> robotWelcomeList = classifyWelcomeDTO.getPcloudRobotWelcomeList();
        pcloudRobotWelcomeDao.deleteByPcloudClassifyId(classifyWelcomeDTO.getPcloudClassifyId(),classifyWelcomeDTO.getRobotType());
        if (ListUtils.isEmpty(robotWelcomeList)) {
            return;
        }
        for (PcloudRobotWelcome robotWelcome:robotWelcomeList) {
            robotWelcome.setRobotType(classifyWelcomeDTO.getRobotType());
            robotWelcome.setIsOpenPushH5url(classifyWelcomeDTO.getIsOpenPushH5url());
            robotWelcome.setWelcomeDuration(classifyWelcomeDTO.getWelcomeDuration());
        }
        pcloudRobotWelcomeDao.batchInsert(robotWelcomeList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRobotClassifyKeywordClassify(PcloudRobotClassify classify) {
        if (classify==null||classify.getId()==null||classify.getKeywordClassifyId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数为空！");
        }
        pcloudRobotClassifyDao.updateRobotClassifyKeywordClassify(classify.getId(),classify.getKeywordClassifyId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSeqNum4RobotClassify(ClassifySeqNumUpdateVO vo) {
        pcloudRobotClassifyDao.updateSeqNum4RobotClassify(vo);
    }

    @Override
    public void testSentry() {
        log.info("info啦啦啦啦啦啦啦啦啦拉拉阿拉啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦拉拉阿拉啦啦啦啦啦啦");
        log.warn("warn啦啦啦啦啦啦啦啦啦拉拉阿拉啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦拉拉阿拉啦啦啦啦啦啦");
        log.error("error啦啦啦啦啦啦啦啦啦拉拉阿拉啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦拉拉阿拉啦啦啦啦啦啦");
    }

    @Override
    public RobotClassifyDTO getClassifyInfo(Long robotType) {
        return pcloudRobotClassifyDao.getClassifyInfo(robotType);
    }

}
