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

import com.pcloud.book.applet.biz.AppletGroupSearchRecordBiz;
import com.pcloud.book.applet.contants.AppletConstants;
import com.pcloud.book.applet.dao.AppletGroupSearchRecordDao;
import com.pcloud.book.applet.dao.AppletGroupStatementDao;
import com.pcloud.book.applet.dto.AppletGroupSearchRecordDTO;
import com.pcloud.book.applet.dto.AppletGroupStatementDTO;
import com.pcloud.book.applet.entity.AppletGroupSearchRecord;
import com.pcloud.book.applet.entity.AppletGroupStatement;
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.dao.GroupQrcodeDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.GroupQrcodeDTO;
import com.pcloud.book.group.enums.JoinGroupTypeEnum;
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.constant.CacheConstant;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import javax.annotation.Resource;

/**
 * (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);

    @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;
    @Autowired
    private GroupQrcodeDao groupQrcodeDao;
    @Autowired
    private AppletGroupStatementDao appletGroupStatementDao;


    @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());
            baseTempletClassify.setVolLabelId(adviserDto.getVolLabelId());
            rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);
        }
        List<GroupActivity4AppletDTO> tishBookSchoolList = new ArrayList<>();
        //本书自带社群
        if (JoinGroupTypeEnum.GROUP_QRCODE.getCode().equals(bookGroupDTO.getJoinGroupType())) {
            List<GroupQrcodeDTO> groupQrcodeDTOS = groupQrcodeDao.getGroupQrcodeListByBookGroupId(bookGroupId);
            if (!ListUtils.isEmpty(groupQrcodeDTOS)) {
                for (GroupQrcodeDTO qrcodeDTO : groupQrcodeDTOS) {
                    GroupActivity4AppletDTO appletDTO = new GroupActivity4AppletDTO();
                    BeanUtils.copyProperties(qrcodeDTO, appletDTO);
                    appletDTO.setName(qrcodeDTO.getGroupName());
                    appletDTO.setDesc(qrcodeDTO.getClassifyIntroduce());
                    appletDTO.setBookGroupId(bookGroupId);
                    appletDTO.setBookGroupQrcodeId(qrcodeDTO.getId());
                    tishBookSchoolList.add(appletDTO);
                }
            }
        }
        //根据分类推荐相关
        List<GroupActivity4AppletDTO> groupActivity4AppletDTOS = pcloudGroupActivityDao.getTishBookSchoolList(baseTempletClassify, 10);
        if (!ListUtils.isEmpty(groupActivity4AppletDTOS)) {
            tishBookSchoolList.addAll(groupActivity4AppletDTOS);
        }
        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 = this.getHeadUrlList(groupActivity4AppletDTO.getUserNumber(), groupActivity4AppletDTO.getBookGroupQrcodeId());
            groupActivity4AppletDTO.setHeadUrlList(headUrlList);
            List<AppletGroupStatementDTO> statementDTOS = this.getStatementList(groupActivity4AppletDTO.getUserNumber(), headUrlList, groupActivity4AppletDTO.getBookGroupQrcodeId());
            groupActivity4AppletDTO.setStatementDTOList(statementDTOS);
        }
        return tishBookSchoolList;
    }

    @Override
    public List<String> getHeadUrlList(Integer userNum, Long groupQrcodeId) {
        List<String> headUrlList = JedisClusterUtils.hgetJson2List(AppletConstants.GROUP_HEAD_URL_REDIS, groupQrcodeId.toString(), String.class);
        if (ListUtils.isEmpty(headUrlList) || (headUrlList.size() < 9 && !userNum.equals(headUrlList.size()))) {
            headUrlList = readerConsr.getRandomHeadUrlList(userNum > 9 ? 9 : userNum);
            JedisClusterUtils.hset2Json(AppletConstants.GROUP_HEAD_URL_REDIS, groupQrcodeId.toString(), headUrlList);
            JedisClusterUtils.expire(AppletConstants.GROUP_HEAD_URL_REDIS, 3600);
        }
        return headUrlList;
    }

    @Override
    public List<AppletGroupStatementDTO> getStatementList(Integer userNum, List<String> headUrlList, Long groupQrcodeId) {
        if (userNum <= 0) {
            return new ArrayList<>();
        }
        List<AppletGroupStatementDTO> statementDTOS = JedisClusterUtils.hgetJson2List(AppletConstants.GROUP_STATEMENT_REDIS, groupQrcodeId.toString(), AppletGroupStatementDTO.class);
        if (ListUtils.isEmpty(statementDTOS) || (statementDTOS.size() < 9 && !userNum.equals(statementDTOS.size()))) {
            statementDTOS = new ArrayList<>();
            userNum = userNum > 50 ? 50 : userNum;//最多50条
            List<String> headUrls = new ArrayList<>();
            headUrls.addAll(headUrlList);
            if (headUrlList.size() < userNum) {
                headUrls.addAll(readerConsr.getRandomHeadUrlList(userNum - headUrlList.size()));
            }
            List<AppletGroupStatement> statementList = appletGroupStatementDao.getRandom(userNum);
            for (int i = 0; i < userNum; i++) {
                AppletGroupStatementDTO statementDTO = new AppletGroupStatementDTO();
                statementDTO.setHeadUrl(headUrls.get(i));
                AppletGroupStatement statement = statementList.get(i);
                statementDTO.setStatement(statement.getStatement());
                statementDTO.setType(statement.getType());
                statementDTO.setDuration(statement.getDuration());
                statementDTOS.add(statementDTO);
            }
            JedisClusterUtils.hset2Json(AppletConstants.GROUP_STATEMENT_REDIS, groupQrcodeId.toString(), statementDTOS);
            JedisClusterUtils.expire(AppletConstants.GROUP_STATEMENT_REDIS, 3600);
        }
        return statementDTOS;
    }

}