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

import com.google.common.collect.Lists;
import com.pcloud.book.applet.biz.AppletGroupManageBiz;
import com.pcloud.book.applet.biz.AppletGroupSearchRecordBiz;
import com.pcloud.book.applet.biz.AppletNewsBiz;
import com.pcloud.book.applet.dao.AppletGroupManageDao;
import com.pcloud.book.applet.dto.AppletGroupManageDTO;
import com.pcloud.book.applet.dto.AppletGroupStatementDTO;
import com.pcloud.book.applet.dto.UpdateAppletGroupManageDTO;
import com.pcloud.book.applet.entity.AppletGroupManage;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.label.LabelConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.group.biz.GroupQrcodeBiz;
import com.pcloud.book.group.dao.BookClassifyBuyRecordDao;
import com.pcloud.book.group.dao.BookQrcodeUserDao;
import com.pcloud.book.group.vo.ClassifyQrcodeVO;
import com.pcloud.book.group.vo.GroupQrcode4ClassifyVO;
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.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.math.BigDecimal;
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);

    @Autowired
    private AppletGroupManageDao appletGroupManageDao;
    @Autowired
    private LabelConsr labelConsr;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private AppletGroupSearchRecordBiz appletGroupSearchRecordBiz;
    @Autowired
    private GroupQrcodeBiz groupQrcodeBiz;
    @Autowired
    private BookQrcodeUserDao bookQrcodeUserDao;
    @Autowired
    private BookClassifyBuyRecordDao bookClassifyBuyRecordDao;
    @Autowired
    private AppletNewsBiz appletNewsBiz;

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

    @Override
    public PageBeanNew getList(String name, Integer currentPage, Integer numPerPage, Long agentId) {
        Map<String,Object> map = new HashMap<>();
        map.put("name", name);
        map.put("agentId", agentId);
        PageBeanNew<AppletGroupManageDTO> recordList = appletGroupManageDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getList");
        if (null == recordList || CollectionUtils.isEmpty(recordList.getRecordList())) {
            return recordList;
        }

        // 平台端共读模板创建修改为选择群分类自更新群 群变更为群分类 需要补充信息
        for (AppletGroupManageDTO appletGroupManageDTO : recordList.getRecordList()) {
            Long classifyId = appletGroupManageDTO.getClassifyId();
            if (classifyId!=null && classifyId !=0 ) {
                String groupQrCode = groupQrcodeBiz.getChangeGroupQrCode(classifyId);
                ClassifyQrcodeVO groupQrcodeInfo = groupQrcodeBiz.getGroupQrcodeInfo(groupQrCode, classifyId);
                appletGroupManageDTO.setUserNumber(groupQrcodeInfo.getUserNumber());
                appletGroupManageDTO.setBookGroupQrcodeId(groupQrcodeInfo.getId());
                appletGroupManageDTO.setGroupPic(groupQrCode);
            }
        }

        // 组装标签名称
        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(Long wechatUserId, Integer recommend, Integer currentPage, Integer numPerPage, Long officialAccountsId) {
        Map<String,Object> map = new HashMap<>();
        map.put("recommend", recommend);
        Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
        map.put("agentId", agentId);
        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);
            Long classifyId = dto.getClassifyId();
            if(classifyId != null && classifyId != 0) {
                String groupQrCode = groupQrcodeBiz.getChangeGroupQrCode(classifyId);
                ClassifyQrcodeVO groupQrcodeInfo = groupQrcodeBiz.getGroupQrcodeInfo(groupQrCode, classifyId);
                dto.setUserNumber(groupQrcodeInfo.getUserNumber());
                dto.setBookGroupQrcodeId(groupQrcodeInfo.getId());
                dto.setGroupPic(groupQrCode);
                dto.setStatus(0);
                // 付费群 查询用户是否已经购买过该群分类
                if (dto.getPrice() != null && dto.getPrice().compareTo(BigDecimal.ZERO) > 0) {
                    GroupQrcode4ClassifyVO userQrcode = bookQrcodeUserDao
                            .getUserQrcode(wechatUserId, dto.getClassifyId());
                    if (userQrcode != null && userQrcode.getGroupQrcodeId() != null) {
                        dto.setStatus(1);
                    }
                }
                //头像列表从缓存里取
                List<String> headUrlList = appletGroupSearchRecordBiz
                        .getHeadUrlList(dto.getUserNumber(), dto.getBookGroupQrcodeId());
                dto.setHeadUrlList(headUrlList);
                List<AppletGroupStatementDTO> statementDTOS = appletGroupSearchRecordBiz
                        .getStatementList(dto.getUserNumber(), headUrlList, dto.getBookGroupQrcodeId());
                dto.setStatementDTOList(statementDTOS);
            }else {
                //头像、对话
                List<String> headUrlList = appletGroupSearchRecordBiz
                        .getHeadUrlList(3, 3l);
                dto.setHeadUrlList(headUrlList);
            }
        }
        return recordList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(List<Long> groupActivityIds, Long agentId) {
        if (null == agentId){
            agentId = 0L;
        }
        if(!ListUtils.isEmpty(groupActivityIds)){
            List<AppletGroupManage> list = Lists.newArrayList();
            Integer maxSeqNum = appletGroupManageDao.getMaxSeqNum(agentId);
            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));
                appletGroupManage.setAgentId(agentId);
                list.add(appletGroupManage);
            }
            try {
                appletGroupManageDao.insert(list);
            } catch (DuplicateKeyException e){
                throw new BookBizException(BookBizException.ERROR,"请勿添加重复数据");
            }
        }
    }

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

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

}