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


import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookBiz;
import com.pcloud.book.book.dao.BookLabelDao;
import com.pcloud.book.book.entity.BookLabel;
import com.pcloud.book.consumer.app.AssistTempletConsr;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.constants.RightsSettingConstant;
import com.pcloud.book.rightsSetting.dao.RightsSettingDAO;
import com.pcloud.book.rightsSetting.dao.check.RightsSettingCheck;
import com.pcloud.book.rightsSetting.dto.RightsSettingDto;
import com.pcloud.book.rightsSetting.entity.RightsSetting;
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.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RightsSettingBizImpl implements RightsSettingBiz {

    @Autowired
    private RightsSettingDAO rightsSettingDAO;
    @Autowired
    private RightsSettingCheck rightsSettingCheck;
    @Autowired
    private BookLabelDao bookLabelDao;
    @Autowired
    private AssistTempletConsr assistTempletConsr;
    @Value("${system.env}")
    private String envStr;

    @Override
    @ParamLog("新增权益设置")
    public Long addRightsSetting(RightsSetting rightsSetting) {
        rightsSettingCheck.rightsSettingCheck(rightsSetting);
        setClassifyAndLabel(rightsSetting);
        RightsSettingDto rightsSettingDto = getByLabel(rightsSetting.getFirstClassify(),rightsSetting.getSecondClassify(),
            rightsSetting.getGradeLabelId(), rightsSetting.getSubjectLabelId());
        if (null != rightsSettingDto){
            throw new BookBizException(BookBizException.ERROR,"已存在相同的权益设置");
        }
        return rightsSettingDAO.insert(rightsSetting);
    }

    private void setClassifyAndLabel(RightsSetting rightsSetting) {
        log.info("对于某些特殊分类做处理");
        Boolean  contain4K12 = false;
        Boolean  contain4Medical = false;
        if ("test".equals(envStr) && ArrayUtils.contains(RightsSettingConstant.K12_TEMPLET_ID_TEST,rightsSetting.getFirstClassify())){
            contain4K12 = true;
        }else if (!"test".equals(envStr) && ArrayUtils.contains(RightsSettingConstant.K12_TEMPLET_ID,rightsSetting.getFirstClassify())){
            contain4K12 = true;
        }
        if (!ArrayUtils.contains(RightsSettingConstant.MEDICAL_INSURANCE_TEMPLET_ID,rightsSetting.getFirstClassify())){
            rightsSetting.setSecondClassify(null);
        }
        if (!contain4K12){
            rightsSetting.setGradeLabelId(null);
            rightsSetting.setSubjectLabelId(null);
        }
    }

    @Override
    @ParamLog("删除权益设置")
    public void deleteRightsSetting(Long id) {
        rightsSettingDAO.deleteByPrimaryKey(id);
    }

    @Override
    @ParamLog("更新权益设置")
    public void updateRightsSetting(RightsSetting rightsSetting) {
        rightsSettingCheck.rightsSettingCheck(rightsSetting);
        setClassifyAndLabel(rightsSetting);
        RightsSettingDto rightsSettingDto = getByLabel(rightsSetting.getFirstClassify(),rightsSetting.getSecondClassify(),
            rightsSetting.getGradeLabelId(), rightsSetting.getSubjectLabelId());
        if (null != rightsSettingDto && !rightsSettingDto.getId().equals(rightsSetting.getId())){
            throw new BookBizException(BookBizException.ERROR,"已存在相同的权益设置");
        }
        rightsSetting.setUpdateTime(new Date());
        rightsSettingDAO.updateByPrimaryKeySelective(rightsSetting);
    }

    @Override
    @ParamLog("获取权益设置")
    public RightsSetting getRightsSetting(Long id) {
        return rightsSettingDAO.selectByPrimaryKey(id);
    }

    @Override
    @ParamLog(value = "获取权益分类分页列表",isAfterReturn = false)
    public PageBeanNew<RightsSettingDto> listRightsSettingPage(Integer currentPage, Integer numPerPage, RightsSetting rightsSetting) {
        Map<String,Object> paramMap = new HashMap<>();
        if (null != rightsSetting.getFirstClassify()){
            setClassifyAndLabel(rightsSetting);
        }
        paramMap.put("firstClassify",rightsSetting.getFirstClassify());
        paramMap.put("secondClassify",rightsSetting.getSecondClassify());
        paramMap.put("gradeLabelId",rightsSetting.getGradeLabelId());
        paramMap.put("subjectLabelId",rightsSetting.getSubjectLabelId());
        PageBeanNew<RightsSettingDto> rightsSettingDtoPageBeanNew = rightsSettingDAO.listPageNew(new PageParam(currentPage,numPerPage),paramMap,"listRightsSettingPage");
        if (null != rightsSettingDtoPageBeanNew && !ListUtils.isEmpty(rightsSettingDtoPageBeanNew.getRecordList())){
            List<RightsSettingDto>  rightsSettingDtos = rightsSettingDtoPageBeanNew.getRecordList();
            setLabelContent(rightsSettingDtos);
        }
        return rightsSettingDtoPageBeanNew;
    }


    private void setLabelContent(List<RightsSettingDto> rightsSettingDtos) {
        log.info("权益设置标签具体内容");
        if (ListUtils.isEmpty(rightsSettingDtos)){
            return;
        }
        List<Long> firstClassifyIds = new ArrayList<>();
        List<Long> secondClassifyIds = new ArrayList<>();
        List<Long> classifyIds = new ArrayList<>();
        List<Long> gradeLabelIds = new ArrayList<>();
        List<Long> subjectLabelIds = new ArrayList<>();
        List<Long> labelIds = new ArrayList<>();
        firstClassifyIds  = rightsSettingDtos.stream().map(e -> e.getFirstClassify()).collect(Collectors.toList());
        secondClassifyIds  = rightsSettingDtos.stream().map(e -> e.getSecondClassify()).collect(Collectors.toList());
        gradeLabelIds  = rightsSettingDtos.stream().map(e -> e.getGradeLabelId()).collect(Collectors.toList());
        subjectLabelIds  = rightsSettingDtos.stream().map(e -> e.getSubjectLabelId()).collect(Collectors.toList());
        if (!ListUtils.isEmpty(firstClassifyIds)){
            classifyIds.addAll(firstClassifyIds);
        }
        if (!ListUtils.isEmpty(secondClassifyIds)){
            classifyIds.addAll(secondClassifyIds);
        }
        if (!ListUtils.isEmpty(gradeLabelIds)){
            labelIds.addAll(gradeLabelIds);
        }
        if (!ListUtils.isEmpty(subjectLabelIds)){
            labelIds.addAll(subjectLabelIds);
        }
        Map<Long, AssistTempletDTO> classifyMap = new HashMap<>();
        Map<Long, BookLabel>  labelMap= new HashMap<>();
        if (!ListUtils.isEmpty(classifyIds)){
            classifyMap = assistTempletConsr.mapByIds4Classify(classifyIds);
        }
        if (!ListUtils.isEmpty(labelIds)){
            labelMap = bookLabelDao.getMapByIds(labelIds);
        }
       for (RightsSettingDto rightsSettingDto : rightsSettingDtos){
           if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getFirstClassify())){
               rightsSettingDto.setFirstClassifyContent(classifyMap.get(rightsSettingDto.getFirstClassify()).getTempletName());
           }
           if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getSecondClassify())){
               rightsSettingDto.setSecondClassifyContent(classifyMap.get(rightsSettingDto.getSecondClassify()).getTempletName());
           }
           if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getGradeLabelId())){
               rightsSettingDto.setGradeLabelIdContent(labelMap.get(rightsSettingDto.getGradeLabelId()).getName());
           }
           if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getSubjectLabelId())){
               rightsSettingDto.setSubjectLabelIdContent(labelMap.get(rightsSettingDto.getSubjectLabelId()).getName());
           }
       }
    }

    @Override
    public RightsSettingDto getByLabel(Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId) {
        //医疗保健分类校验
        if (ArrayUtils.contains(RightsSettingConstant.MEDICAL_INSURANCE_TEMPLET_ID,firstClassify)){
            subjectLabelId=null;
            gradeLabelId=null;
        }
        //k12教育分类校验
        else if ("test".equals(envStr) && ArrayUtils.contains(RightsSettingConstant.K12_TEMPLET_ID_TEST,firstClassify)){
            secondClassify=null;
        }else if (!"test".equals(envStr) && ArrayUtils.contains(RightsSettingConstant.K12_TEMPLET_ID,firstClassify)){
            secondClassify=null;
        }
        else {
            secondClassify=null;
            subjectLabelId=null;
            gradeLabelId=null;
        }
        RightsSettingDto dto = rightsSettingDAO.getByLabel(firstClassify,secondClassify,gradeLabelId,subjectLabelId);
        return dto;
    }

    @Override
    public Integer getUserCount() {
        Integer userCount = 102336;
        String key="BOOK:APPLET:RIGHTS_SETTING_USER_COUNT";
        String value = JedisClusterUtils.get(key);
        if (StringUtil.isEmpty(value)){
            JedisClusterUtils.set(key,userCount.toString(),24*3600);
        }else {
            userCount = Integer.valueOf(value);
        }
        return userCount;
    }
}
