package com.kcim.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcim.common.constants.NumberConstant;
import com.kcim.common.exception.CostException;
import com.kcim.common.util.BeanUtil;
import com.kcim.dao.mapper.UserResponsibilityRightMapper;
import com.kcim.dao.model.Responsibility;
import com.kcim.dao.model.UserResponsibilityRight;
import com.kcim.dao.repository.UserResponsibilityRightRepository;
import com.kcim.service.CenterService;
import com.kcim.service.ResponsibilityService;
import com.kcim.service.UserResponsibilityRightService;
import com.kcim.vo.CommonParameterVo;
import com.kcim.vo.CostResponsibilityVO;
import com.kcim.vo.UserResponsibilityRightVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.kcim.common.constants.ParameterConstant.USER_REPORT_AUTHOR_ABLE;


/**
 *
 * @author Administrator
 */
@Service("UserResponsibilityRightService")
@Slf4j
@AllArgsConstructor
public class UserResponsibilityRightServiceImpl extends ServiceImpl<UserResponsibilityRightMapper, UserResponsibilityRight> implements UserResponsibilityRightService {


    UserResponsibilityRightRepository repository;
    ResponsibilityService responsibilityService;
    CenterService centerService;

    /**
     * 获取当前用户有权限的责任中心信息
     * @return
     */
    @Override
    public List<UserResponsibilityRight> getUserResponsibilityRight(){
        return  repository.getList();
    }

    /**
     * 获取用户的责任中心权限列表
     * @param responsibilityName
     * @param hideFlag
     * @return
     */
    @Override
    public List<UserResponsibilityRightVO> getUserResponsibilityRights(Long userId,String responsibilityName, Integer hideFlag) {
        List<CostResponsibilityVO> responsibilityList = responsibilityService.getList( );
        //没开启数据权限流程时返回所有
        if(CollectionUtils.isEmpty(responsibilityList))
        {
            throw new CostException("找不到有效的责任中心，请先维护责任中心字典");
        }
        //转成出参对象
        List<UserResponsibilityRightVO> userReportRightVOList = responsibilityList.stream().map(responsibility -> convertToResponsibilityRightVO(responsibility,userId)).collect(Collectors.toList());
        //获取用户有权限的损益报表
        List<UserResponsibilityRight> userResponsibilityRightList = repository.getList();
        if(!CollectionUtils.isEmpty(userResponsibilityRightList)){
            //只取责任中心代码
            List<String> responsibilityCodeList = userResponsibilityRightList.stream().map(UserResponsibilityRight::getResponsibilityCode).distinct().collect(Collectors.toList());
            //设置选择标志
            userReportRightVOList.stream().forEach(responsibility->
                    responsibility.setStatus(responsibilityCodeList.contains(responsibility.getResponsibilityCode())? NumberConstant.ONE:NumberConstant.ZERO));
        }
        return userReportRightVOList;
    }

    /**
     * 转成用户责任中心权限对象
     * @param responsibilityVO
     * @return
     */
    public UserResponsibilityRightVO convertToResponsibilityRightVO(CostResponsibilityVO responsibilityVO, Long userId){
        UserResponsibilityRightVO userResponsibilityRightVO = BeanUtil.convertObj(responsibilityVO, UserResponsibilityRightVO.class);
        userResponsibilityRightVO.setUserId(userId);
        return userResponsibilityRightVO;
    }


    /**
     * 编辑用户损益报表权限
     * @param uerResponsibilityRightVO
     */
    @Override
    public void editUserResponsibilityRight(UserResponsibilityRightVO uerResponsibilityRightVO) {
        UserResponsibilityRight userResponsibilityRight = BeanUtil.convertObj(uerResponsibilityRightVO, UserResponsibilityRight.class);
        if(uerResponsibilityRightVO.getStatus().equals(NumberConstant.ONE)){
            repository.addUserResponsibilityRight(userResponsibilityRight);
        }else{
            repository.deleteUserResponsibilityRight(userResponsibilityRight);
        }
    }

    /**
     * 修改指定用户的责任中心权限
     * @param userId
     * @param responsibilityCode
     * @param status
     */
    @Override
    public void editUserResponsibilityRight(Long userId, String responsibilityCode, Integer status) {
        if(status.equals(NumberConstant.ONE)){
            repository.addUserResponsibilityRight(userId,responsibilityCode);
        }else{
            repository.deleteUserResponsibilityRight(userId,responsibilityCode);
        }
    }

    /**
     * 给用户添加所有损益报表权限
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Throwable.class,propagation = Propagation.REQUIRED)
    public void editAllUserResponsibilityRight(Long userId,Integer allRightFlag) {
        //先移除已有的所有权限
        List<UserResponsibilityRight> userResponsibilityRightList = repository.getListByUserId(userId);
        repository.removeUserResponsibilityRightList(userResponsibilityRightList);
        //新增一条特殊的全部权限则记录
        if(allRightFlag.equals(NumberConstant.ONE)){
            //组装核算单元为0的数据
            repository.addUserResponsibilityRight(userId,String.valueOf(NumberConstant.ZERO));
        }
    }

    /**
     * 获取授权的责任中心
     * @param fullResponsibilityList
     * @return
     */
    @Override
    public List<Responsibility> getAuthorizedResponsibility(List<Responsibility> fullResponsibilityList){
        //开启用户报表数据权限时
        if(IsUserReportRightAble()){
            //获取用户所有有权限的责任中心
            List<UserResponsibilityRight> currentUserResponsibilityRights = this.getUserResponsibilityRight();
            if(CollectionUtils.isEmpty(currentUserResponsibilityRights)){
                throw new CostException("您没有分配责任中心权限，请联系管理员");
            }
            //如果不是分配了全部责任中心权限则过滤没有权限的责任中心
            if(!currentUserResponsibilityRights.stream().anyMatch(userResponsibilityRight->
                    userResponsibilityRight.getResponsibilityCode().equals(NumberConstant.ZERO_S))){
                //筛选出有权限的责任中心对象
                fullResponsibilityList = fullResponsibilityList.stream().filter(responsibility ->
                        currentUserResponsibilityRights.stream().anyMatch(userRight ->
                                userRight.getResponsibilityCode().equals(responsibility.getResponsibilityCode()))).collect(Collectors.toList());
                if(CollectionUtils.isEmpty(fullResponsibilityList)){
                    throw new CostException("您没有对应的责任中心权限，请联系管理员");
                }
            }
        }
        return fullResponsibilityList;
    }

    /**
     * 判断是否开启用户报表权限功能
     * @return
     */
    @Override
    public boolean IsUserReportRightAble(){
        CommonParameterVo parameter = centerService.getParameter(USER_REPORT_AUTHOR_ABLE);
        if (Objects.isNull(parameter)){
            return false;
        }
        String incomeCollectType = parameter.getValue();
        return incomeCollectType.equals(NumberConstant.ONE_S);
    }


}
