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

import com.pcloud.book.applet.dto.AppletGroupManageDTO;
import com.pcloud.book.applet.dto.AppletGroupSearchRecordDTO;
import com.pcloud.book.applet.entity.AppletGroupSearchRecord;
import com.pcloud.book.applet.dao.AppletGroupSearchRecordDao;
import com.pcloud.book.applet.biz.AppletGroupSearchRecordBiz;
import com.pcloud.book.book.dao.BookAdviserDao;
import com.pcloud.book.book.dto.BookAdviserDto;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.group.biz.BookGroupClassifyBiz;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.entity.BaseTempletClassify;
import com.pcloud.book.skill.dao.PcloudGroupActivityDao;
import com.pcloud.book.skill.dto.GroupActivity4AppletDTO;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtilParent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (AppletGroupSearchRecord)表服务实现类
 *
 * @author zyq
 * @since 2020-04-01 17:34:47
 */
@Service("appletGroupSearchRecordBiz")
public class AppletGroupSearchRecordBizImpl implements AppletGroupSearchRecordBiz {

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

    private static final String GROUP_HEAD_URL_REDIS="BOOK:APPLET:pcloudGroupActivityBizImpl_groupHeadUrl";

    @Autowired
    private AppletGroupSearchRecordDao appletGroupSearchRecordDao;
    @Autowired
    private BookGroupClassifyBiz bookGroupClassifyBiz;

    @Resource
    private PcloudGroupActivityDao pcloudGroupActivityDao;

    @Autowired
    private RightsSettingBiz rightsSettingBiz;
    @Autowired
    private BookGroupDao bookGroupDao;

    @Autowired
    private BookAdviserDao bookAdviserDao;

    @Autowired
    private ReaderConsr readerConsr;


    @Override
    @ParamLog("通过ID查询单条数据")
    public AppletGroupSearchRecord getById(Long id) {
        return appletGroupSearchRecordDao.getById(id);
    }

    @Override
    @ParamLog("查询多条数据")
    public PageBeanNew getList(Long wechatUserId, Integer isMore, Integer currentPage, Integer numPerPage) {
        Map<String,Object> map = new HashMap<>();
        map.put("wechatUserId", wechatUserId);
        PageBeanNew pageBeanNew = appletGroupSearchRecordDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getList");
        List<AppletGroupSearchRecordDTO> recordList = pageBeanNew.getRecordList();
        if (ListUtils.isEmpty(recordList)){
            return pageBeanNew;
        }
        // 填充分类信息
        for (AppletGroupSearchRecordDTO dto : recordList){
            if(isMore == 1) {
                dto.setClassifyCount(bookGroupClassifyBiz.getClassifyCount(dto.getBookGroupId()));
            } else {
                dto.setClassify4WechatVOList(bookGroupClassifyBiz.listClassify4Wechat(dto.getBookGroupId(), dto.getWechatUserId()));
            }
        }
        return pageBeanNew;
    }

    @Override
    @ParamLog("新增")
    public Long insert(AppletGroupSearchRecord appletGroupSearchRecord) {
        if(!NumberUtil.isNumber(appletGroupSearchRecord.getBookId()) || !NumberUtil.isNumber(appletGroupSearchRecord.getChannelId()) || !NumberUtil.isNumber(appletGroupSearchRecord.getAdviserId())){
            throw BizException.PARAM_DELETION;
        }
        BookGroupDTO bookGroupDTO = bookGroupDao.getDTOByBookId(appletGroupSearchRecord.getBookId(), appletGroupSearchRecord.getChannelId(), appletGroupSearchRecord.getAdviserId());
        if(bookGroupDTO != null && bookGroupDTO.getId() != null && bookGroupDTO.getId() > 0){
            appletGroupSearchRecord.setBookGroupId(bookGroupDTO.getId());
            appletGroupSearchRecordDao.insert(appletGroupSearchRecord);
            return appletGroupSearchRecord.getId();
        }
        return 0L;
    }

    @Override
    @ParamLog("修改")
    public void update(AppletGroupSearchRecord appletGroupSearchRecord) {
        if(appletGroupSearchRecord == null || !NumberUtil.isNumber(appletGroupSearchRecord.getId())){
            throw BizException.PARAM_DELETION;
        }
        appletGroupSearchRecordDao.update(appletGroupSearchRecord);
    }

    @Override
    @ParamLog("删除")
    public void deleteById(Long id) {
        appletGroupSearchRecordDao.deleteById(id);
    }

    @Override
    @ParamLog("删除")
    public void deleteByIds(List<Long> ids) {
        if(ListUtils.isEmpty(ids)){
            throw BizException.PARAM_DELETION;
        }
        appletGroupSearchRecordDao.deleteByIds(ids);
    }

    @Override
    public List<GroupActivity4AppletDTO> getTishBookSchoolList(Long bookGroupId) {
        BookGroupDTO bookGroupDTO = bookGroupDao.getBookBaseInfoById(bookGroupId);
        BookAdviserDto adviserDto = bookAdviserDao.getBase(bookGroupDTO.getBookId(),bookGroupDTO.getChannelId(),bookGroupDTO.getCreateUser());
        BaseTempletClassify baseTempletClassify=new BaseTempletClassify();
        if(adviserDto!=null){
            baseTempletClassify.setFirstClassify(adviserDto.getTempletId());
            baseTempletClassify.setSecondClassify(adviserDto.getSecondTempletId());
            baseTempletClassify.setGradeLabelId(adviserDto.getGraLabelId());
            baseTempletClassify.setSubjectLabelId(adviserDto.getSubLabelId());
            rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);
        }
        //设置头像
        List<GroupActivity4AppletDTO> tishBookSchoolList = pcloudGroupActivityDao.getTishBookSchoolList(baseTempletClassify);
        if(ListUtils.isEmpty(tishBookSchoolList)){
            return new ArrayList<>();
        }
        for (GroupActivity4AppletDTO groupActivity4AppletDTO:tishBookSchoolList) {
            String filterStr = StringUtilParent.replaceHtml(groupActivity4AppletDTO.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            groupActivity4AppletDTO.setCutDesc(subStr);
            //头像列表从缓存里取
            List<String> headUrlList = JedisClusterUtils.hgetJson2List(GROUP_HEAD_URL_REDIS,groupActivity4AppletDTO.getGroupActivityId().toString(),String.class);
            //缓存为空或数量不一致，重新获取
            if (ListUtils.isEmpty(headUrlList) ||
                    (headUrlList.size()<9 && !groupActivity4AppletDTO.getUserNumber().equals(headUrlList.size()))){
                headUrlList = readerConsr.getRandomHeadUrlList(groupActivity4AppletDTO.getUserNumber()>9 ? 9:groupActivity4AppletDTO.getUserNumber());
                JedisClusterUtils.hset2Json(GROUP_HEAD_URL_REDIS,groupActivity4AppletDTO.getGroupActivityId().toString(),headUrlList);
                JedisClusterUtils.expire(GROUP_HEAD_URL_REDIS,3600);
            }
            groupActivity4AppletDTO.setHeadUrlList(headUrlList);
        }

        return tishBookSchoolList;
    }
}