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.common.util.PageUtils;
import com.kcim.dao.mapper.UserReportRightMapper;
import com.kcim.dao.model.UserReportRight;
import com.kcim.dao.model.UserResponsibilityRight;
import com.kcim.dao.repository.UserReportRightRepository;
import com.kcim.service.CenterService;
import com.kcim.service.UserReportRightService;
import com.kcim.service.UserResponsibilityRightService;
import com.kcim.vo.DictDataVo;
import com.kcim.vo.UserInfoVO;
import com.kcim.vo.UserReportRightVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

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

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


/**
 * 用户报表权限
 * @author
 */
@Service("UserReportRightService")
@Slf4j
@AllArgsConstructor
public class UserReportRightServiceImpl extends ServiceImpl<UserReportRightMapper, UserReportRight> implements UserReportRightService {

    private final CenterService centerService;
    private UserReportRightRepository repository;
    private UserResponsibilityRightService userResponsibilityRightService;

    /**
     * 获取用户有权限的损益报表
     * @return
     */
    @Override
    public DictDataVo getUserReports() {
        DictDataVo dictDataVo = centerService.getDict(PROFIT_REPORT_TYPE);
        //没开启数据权限流程时返回所有
        if(!IsUserReportRightAble())
        {
            return dictDataVo;
        }
        List<UserReportRight> userReportRight = repository.getList();
        if(CollectionUtils.isEmpty(userReportRight)){
            throw new CostException("您没有分分配损益报表权限，请联系管理员");
        }
        //筛选出有权限的责任中心对象
        List<DictDataVo> dictDataVoList = dictDataVo.getDataVoList().stream().filter(dictData ->
                userReportRight.stream().anyMatch(userRight ->
                        userRight.getReportCode().equals(dictData.getCode()))).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(dictDataVoList)){
            throw new CostException("您没有对应的损益报表权限，请联系管理员");
        }
        //只返回有权限的损益报表
        dictDataVo.setDataVoList(dictDataVoList);
        return dictDataVo;
    }


    /**
     * 获取用户列表
     * @param userName
     * @return
     */
    @Override
    public Object getUserList(Integer current, Integer pageSize, String userName) {
        List<UserInfoVO> centerUserInfo = centerService.getCenterUserInfo(userName);
        //判断是否有维护过责任中心权限
        List<UserResponsibilityRight> userResponsibilityRight = userResponsibilityRightService.getUserResponsibilityRight();
        if(!CollectionUtils.isEmpty(userResponsibilityRight)){
            //获取所有用户ID并去重
            List<Long> userList = userResponsibilityRight.stream().map(UserResponsibilityRight::getUserId).distinct().collect(Collectors.toList());
            //找出所有配置过责任中心权限的用户
            List<UserInfoVO> userInfoVOS = centerUserInfo.stream().filter(userInfo -> userList.contains(userInfo.getId())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(userInfoVOS)){
                //设置是否配置标识
                userInfoVOS.stream().forEach(userInfo ->userInfo.setUserStatus(NumberConstant.ONE));
            }
        }
        //判断是否有维护过损益报表权限
        List<UserReportRight> userReportRight = repository.getList();
        if(!CollectionUtils.isEmpty(userReportRight)){
            //获取所有用户ID并去重
            List<Long> userList = userReportRight.stream().map(UserReportRight::getUserId).distinct().collect(Collectors.toList());
            //找出所有配置过损益报表权限的用户
            List<UserInfoVO> userInfoVOS = centerUserInfo.stream().filter(userInfo ->userList.contains(userInfo.getId())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(userInfoVOS)){
                //设置是否配置标识
                userInfoVOS.stream().forEach(userInfo ->userInfo.setUserStatus(NumberConstant.ONE));
            }
        }
        PageUtils pageUserInfo = new PageUtils(new ArrayList<>(), NumberConstant.ZERO,pageSize,current);
        if(CollectionUtils.isEmpty(centerUserInfo)){
            return pageUserInfo;
        }
        pageUserInfo = new PageUtils(centerUserInfo, centerUserInfo.size(), pageSize, current);
        return pageUserInfo;
    }

    /**
     * 获取用户有权限的损益报表列表
     * @param userId
     * @param reportName
     * @param hideFlag
     * @return
     */
    @Override
    public List<UserReportRightVO> getUserReportRights(Long userId,String reportName, Integer hideFlag) {
        DictDataVo dictDataVo = centerService.getDict(PROFIT_REPORT_TYPE);
        //没开启数据权限流程时返回所有
        if(!ObjectUtils.isEmpty(dictDataVo)||CollectionUtils.isEmpty(dictDataVo.getDataVoList()))
        {
            throw new CostException("找不到有效的损益报表，请先维护损益报表字典");
        }
        //转成出参对象
        List<UserReportRightVO> userReportRightVOList = dictDataVo.getDataVoList().stream().map(dataVo -> convertToReportRightVO(dataVo,userId)).collect(Collectors.toList());
        //获取用户有权限的损益报表
        List<UserReportRight> userReportRight = repository.getList();
        if(!CollectionUtils.isEmpty(userReportRight)){
            //只取reportCode
            List<String> reportCodeList = userReportRight.stream().map(UserReportRight::getReportCode).distinct().collect(Collectors.toList());
            //设置选择标志
            userReportRightVOList.stream().forEach(userReport->
                    userReport.setStatus(reportCodeList.contains(userReport.getReportCode())?NumberConstant.ONE:NumberConstant.ZERO));
        }
        return userReportRightVOList;
    }


    /**
     * 编辑用户损益报表权限
     * @param userReportRightVO
     */
    @Override
    public void editUserReportRight(UserReportRightVO userReportRightVO) {
        UserReportRight userReportRight = BeanUtil.convertObj(userReportRightVO, UserReportRight.class);
        if(userReportRightVO.getStatus().equals(NumberConstant.ONE)){
            repository.addUserReportRight(userReportRight);
        }else{
            repository.deleteUserReportRight(userReportRight);
        }
    }

    /**
     * 修改指定用户的损益报表权限
     * @param userId
     * @param reportCode
     * @param status
     */
    @Override
    public void editUserReportRight(Long userId, String reportCode, Integer status) {
        if(status.equals(NumberConstant.ONE)){
            repository.addUserReportRight(userId,reportCode);
        }else{
            repository.deleteUserReportRight(userId,reportCode);
        }
    }

    /**
     * 转成损益报表出参对象
     * @param dictDataVo
     * @return
     */
    public UserReportRightVO convertToReportRightVO(DictDataVo dictDataVo,Long userId){
        UserReportRightVO userReportRightVO=new UserReportRightVO();
        userReportRightVO.setReportCode(dictDataVo.getCode());
        userReportRightVO.setReportName(dictDataVo.getName());
        userReportRightVO.setUserId(userId);
        return userReportRightVO;
    }

    /**
     * 判断是否开启用户报表权限功能
     * @return
     */
    public boolean IsUserReportRightAble(){
        String parameterValue = centerService.getParameterValue(USER_REPORT_AUTHOR_ABLE);
        if (parameterValue.isEmpty()){
            return false;
        }
        return parameterValue.equals(NumberConstant.ONE_S);
    }
}
