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

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookLabelBiz;
import com.pcloud.book.book.constant.BookConstant;
import com.pcloud.book.book.dao.BookLabelDao;
import com.pcloud.book.book.entity.BookLabel;
import com.pcloud.book.book.enums.BookLabelAuditState;
import com.pcloud.book.book.vo.BookLabelVO;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.common.core.constant.SystemCode;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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;

@Component("bookLabelBiz")

public class BookLabelBizImpl implements BookLabelBiz {

    @Autowired
    private BookLabelDao bookLabelDao;
    @Autowired
    private AdviserConsr adviserConsr;

    @Override
    public void applyBookLabel(BookLabel bookLabel, String systemCode) {
        List<BookLabel> labels = bookLabelDao.getListByType(bookLabel.getType());
        List<String> names = labels.stream().filter(s->s.getName()!=null).map(BookLabel::getName).collect(Collectors.toList());
        if (names.contains(bookLabel.getName())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"标签名称重复或已申请");
        }
        Integer seq = bookLabelDao.getMaxSeqByType(bookLabel.getType());
        if (SystemCode.pcloud.code.equalsIgnoreCase(systemCode)){//平台端直接新增
            bookLabel.setAuditState(BookLabelAuditState.pass.code);
            bookLabel.setSeq(seq+1);
            bookLabelDao.insert(bookLabel);
        } else if (SystemCode.adviser.code.equalsIgnoreCase(systemCode)){//编辑端要审核
            if (StringUtil.isEmpty(bookLabel.getRemark())){
                throw new BookBizException(BookBizException.PARAM_IS_NULL,"缺少标签申请说明");
            }
            bookLabel.setAuditState(BookLabelAuditState.wait.code);
            bookLabel.setSeq(seq+1);
            bookLabelDao.insert(bookLabel);
        }
        JedisClusterUtils.del(BookConstant.BOOK_LABEL_CACHE);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditBookLabel(BookLabelVO bookLabelVO) {
        BookLabel updateLabel = new BookLabel();
        updateLabel.setId(bookLabelVO.getLabelId());
        updateLabel.setAuditState(bookLabelVO.getAuditState());
        if (BookLabelAuditState.update_pass.code.equals(bookLabelVO.getAuditState())){//修改后入库
            List<BookLabel> labels = bookLabelDao.getListByType(bookLabelVO.getType());
            List<String> names = labels.stream().filter(s->s.getName()!=null).map(BookLabel::getName).collect(Collectors.toList());
            if (names.contains(bookLabelVO.getName())){
                throw new BookBizException(BookBizException.PARAM_IS_NULL,"标签名称重复或已申请");
            }
            BookLabel bookLabel = new BookLabel();
            bookLabel.setType(bookLabelVO.getType());
            bookLabel.setName(bookLabelVO.getName());
            bookLabel.setCreateUser(0L);
            bookLabel.setAuditState(BookLabelAuditState.pass.code);
            Integer seq = bookLabelDao.getMaxSeqByType(bookLabel.getType());
            bookLabel.setSeq(seq+1);
            bookLabelDao.insert(bookLabel);
            Long labelId = bookLabel.getId();
            updateLabel.setUpdateLabelId(labelId);
        }
        bookLabelDao.update(updateLabel);
        JedisClusterUtils.del(BookConstant.BOOK_LABEL_CACHE);
    }

    @Override
    public void deleteById(Long labelId) {
        bookLabelDao.deleteById(labelId);
        JedisClusterUtils.del(BookConstant.BOOK_LABEL_CACHE);
    }

    @Override
    public void updateLabelSeq(Long labelId, Integer seq) {
        BookLabel updateLabel = new BookLabel();
        updateLabel.setId(labelId);
        updateLabel.setSeq(seq);
        bookLabelDao.update(updateLabel);
        JedisClusterUtils.del(BookConstant.BOOK_LABEL_CACHE);
    }

    @Override
    public PageBeanNew<BookLabelVO> listAuditPassBookLabel(Integer labelType, Integer currentPage, Integer numPerPage) {
        Map<String,Object> map = new HashMap<>();
        map.put("type", labelType);
        map.put("auditState", BookLabelAuditState.pass.code);
        PageBeanNew<BookLabelVO> pageBeanNew = bookLabelDao.listPageNew(new PageParam(currentPage,numPerPage), map,"listBookLabel");
        return pageBeanNew;
    }

    @Override
    public PageBeanNew<BookLabelVO> listApplyBookLabel(Integer labelType, Integer currentPage, Integer numPerPage, String name,
                                                       String startTime, String endTime, Integer auditState) {
        Map<String,Object> map = new HashMap<>();
        map.put("type", labelType);
        map.put("name", name);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("filterApply", 1);
        map.put("auditState", auditState);
        PageBeanNew<BookLabelVO> pageBeanNew = bookLabelDao.listPageNew(new PageParam(currentPage,numPerPage), map,"listBookLabel");
        if (null ==pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())){
            return new PageBeanNew<>(currentPage,numPerPage,0,new ArrayList<>());
        }
        List<BookLabelVO> list = pageBeanNew.getRecordList();
        List<Long> adviserIds = list.stream().filter(s->s.getCreateUser()>0).map(BookLabelVO::getCreateUser).distinct().collect(Collectors.toList());
        Map<Long, AdviserBaseInfoDto> adviserBaseInfoDtoMap = new HashMap<>();
        if (!ListUtils.isEmpty(adviserIds)){
            adviserBaseInfoDtoMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(adviserIds);
        }
        for (BookLabelVO bookLabelVO:list){
            if (!MapUtils.isEmpty(adviserBaseInfoDtoMap) && adviserBaseInfoDtoMap.containsKey(bookLabelVO.getCreateUser())){
                AdviserBaseInfoDto adviserBaseInfoDto = adviserBaseInfoDtoMap.get(bookLabelVO.getCreateUser());
                if (null!=adviserBaseInfoDto){
                    bookLabelVO.setAdviserName(adviserBaseInfoDto.getPartyName());
                    bookLabelVO.setAgentName(adviserBaseInfoDto.getAgentName());
                    bookLabelVO.setPhoneNum(adviserBaseInfoDto.getPhoneNum());
                }
            }
        }
        return pageBeanNew;
    }

    @Override
    public Map<Long, String> getLabelMapByIds(List<Long> labelIds) {
        if(ListUtils.isEmpty(labelIds)){
            return new HashMap<>();
        }
        List<BookLabel> labelList = bookLabelDao.getByLabelIds(new ArrayList<>(labelIds));
        if(ListUtils.isEmpty(labelList)){
            return  new HashMap<>();
        }
        Map<Long, String> map = labelList.stream().collect(Collectors.toMap(a -> a.getId(), a -> a.getName(), (k1, k2) -> (k2)));
        return map;
    }

    @Override
    public List<BookLabelVO> getLabelByIds(List<Long> labelIds) {
        List<BookLabel> labelList = bookLabelDao.getByLabelIds(labelIds);
        if (ListUtils.isEmpty(labelList)) {
            return new ArrayList<>();
        }
        List<BookLabelVO> labelVOS = new ArrayList<>();
        for (BookLabel bookLabel : labelList) {
            BookLabelVO bookLabelVO = new BookLabelVO();
            BeanUtils.copyProperties(bookLabel, bookLabelVO);
            bookLabelVO.setLabelId(bookLabel.getId());
            labelVOS.add(bookLabelVO);
        }
        return labelVOS;
    }
}
