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

import com.google.common.collect.Lists;
import com.pcloud.book.applet.dto.AppletGroupManageDTO;
import com.pcloud.book.applet.dto.UpdateAppletGroupManageDTO;
import com.pcloud.book.applet.entity.AppletGroupManage;
import com.pcloud.book.applet.dao.AppletGroupManageDao;
import com.pcloud.book.applet.biz.AppletGroupManageBiz;
import com.pcloud.book.consumer.label.LabelConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
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.StringUtil;
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.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * 学舍群管理(AppletGroupManage)表服务实现类
 *
 * @author zyq
 * @since 2020-04-01 14:05:42
 */
@Service("appletGroupManageBiz")
public class AppletGroupManageBizImpl implements AppletGroupManageBiz {

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

    private static final String GROUP_HEAD_URL_REDIS="BOOK:APPLET:appletGroupManage_groupHeadUrl";
    @Autowired
    private AppletGroupManageDao appletGroupManageDao;
    @Autowired
    private LabelConsr labelConsr;
    @Autowired
    private ReaderConsr readerConsr;

    @Override
    public AppletGroupManage getById(Long id) {
        return appletGroupManageDao.getById(id);
    }

    @Override
    public PageBeanNew getList(String name, Integer currentPage, Integer numPerPage) {
        Map<String,Object> map = new HashMap<>();
        map.put("name", name);
        PageBeanNew<AppletGroupManageDTO> recordList = appletGroupManageDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getList");
        if (null == recordList || CollectionUtils.isEmpty(recordList.getRecordList())) {
            return recordList;
        }
        // 组装标签名称
        List<Long> labelId = Lists.newArrayList();
        for (AppletGroupManageDTO dto : recordList.getRecordList()) {
            labelId.add(dto.getProLabelId());
            labelId.add(dto.getPurLabelId());
            labelId.add(dto.getDepLabelId());
        }
        Map<Long, String> labelName = labelConsr.getLabelName(labelId);
        for (AppletGroupManageDTO dto : recordList.getRecordList()) {
            dto.setPurLabelName(labelName.get(dto.getPurLabelId()));
            dto.setProLabelName(labelName.get(dto.getProLabelId()));
            dto.setDepLabelName(labelName.get(dto.getDepLabelId()));
        }
        // 截取字符串
        for(AppletGroupManageDTO dto : recordList.getRecordList()){
            String filterStr = StringUtilParent.replaceHtml(dto.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            dto.setCutDesc(subStr);
            dto.setQrcodeHeadUrl(readerConsr.getNineHeadUrl());
        }
        return recordList;
    }

    @Override
    public PageBeanNew getList4Applet(Integer recommend, Integer currentPage, Integer numPerPage) {
        Map<String,Object> map = new HashMap<>();
        map.put("recommend", recommend);
        PageBeanNew<AppletGroupManageDTO> recordList = appletGroupManageDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getList4Applet");
        if (null == recordList || CollectionUtils.isEmpty(recordList.getRecordList())) {
            return recordList;
        }
        // 截取字符串
        for(AppletGroupManageDTO dto : recordList.getRecordList()){
            String filterStr = StringUtilParent.replaceHtml(dto.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            dto.setCutDesc(subStr);
            //头像列表从缓存里取
            List<String> headUrlList = JedisClusterUtils.hgetJson2List(GROUP_HEAD_URL_REDIS,dto.getGroupActivityId().toString(),String.class);
            //缓存为空或数量不一致，重新获取
            if (ListUtils.isEmpty(headUrlList) ||
                    (headUrlList.size()<9&&!dto.getUserNumber().equals(headUrlList.size()))){
                headUrlList = readerConsr.getRandomHeadUrlList(dto.getUserNumber()>9?9:dto.getUserNumber());
                JedisClusterUtils.hset2Json(GROUP_HEAD_URL_REDIS,dto.getGroupActivityId().toString(),headUrlList);
                JedisClusterUtils.expire(GROUP_HEAD_URL_REDIS,3600);
            }
            dto.setHeadUrlList(headUrlList);
            dto.setQrcodeHeadUrl(readerConsr.getNineHeadUrl());
        }
        return recordList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(List<Long> groupActivityIds) {
        if(!ListUtils.isEmpty(groupActivityIds)){
            List<AppletGroupManage> list = Lists.newArrayList();
            Integer maxSeqNum = appletGroupManageDao.getMaxSeqNum();
            AppletGroupManage appletGroupManage;
            for (Long groupActivityId : groupActivityIds) {
                appletGroupManage = new AppletGroupManage();
                appletGroupManage.setGroupActivityId(groupActivityId);
                appletGroupManage.setRecommend(0);
                appletGroupManage.setEnable(1);
                appletGroupManage.setSeqNum((maxSeqNum + groupActivityIds.indexOf(groupActivityId) + 1));
                list.add(appletGroupManage);
            }
            try {
                appletGroupManageDao.insert(list);
            } catch (DuplicateKeyException e){
                throw new BizException("请勿添加重复数据");
            }
        }
    }

    @Override
    public void update(UpdateAppletGroupManageDTO updateAppletGroupManageDTO) {
        if(updateAppletGroupManageDTO == null || !NumberUtil.isNumber(updateAppletGroupManageDTO.getId())){
            throw BizException.PARAM_IS_NULL;
        }
        AppletGroupManage appletGroupManage = new AppletGroupManage();
        BeanUtils.copyProperties(updateAppletGroupManageDTO, appletGroupManage);
        appletGroupManageDao.update(appletGroupManage);
    }

    @Override
    public void deleteById(Long id) {
        appletGroupManageDao.deleteById(id);
    }
}