package com.css.simulation.resource.server.app.service;

import api.common.pojo.constants.DictConstants;
import api.common.pojo.constants.LogConstants;
import api.common.pojo.param.system.ClusterParam;
import api.common.pojo.po.system.ClusterPO;
import api.common.pojo.vo.system.ClusterVO;
import api.common.util.ObjectUtil;
import api.common.util.StringUtil;
import com.css.simulation.resource.server.infra.util.AuthUtil;
import com.css.simulation.resource.server.infra.util.PageUtil;
import com.css.simulation.resource.server.infra.util.PoUtil;
import com.css.simulation.resource.server.infra.db.mysql.mapper.ClusterMapper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class ClusterService {

    @Autowired
    ClusterMapper clusterMapper;

    @Autowired
    LogService logService;

    @Autowired
    DictService dictService;


    public PageInfo<ClusterVO> getClusterList(ClusterParam clusterParam) {
        PageUtil.setPageInfo(clusterParam);
        String roleCode = AuthUtil.getCurrentUserRoleCode();
        String useType = AuthUtil.getCurrentUseType();
        String userId = AuthUtil.getCurrentUserId();
        //当前账户为管理员账户，需要查询普通账户，设置roleCode为2
        if (DictConstants.ROLE_CODE_ADMIN.equals(roleCode) || DictConstants.ROLE_CODE_SYSADMIN.equals(roleCode)) {
            clusterParam.setRoleCode(DictConstants.ROLE_CODE_UESR);
        } else if (DictConstants.ROLE_CODE_UESR.equals(roleCode) && DictConstants.USER_TYPE_EXCLUSIVE.equals(useType)) {
            // 当前账户为独占使用的普通账户，需要查询该账户创建的普通账户子账户，设置roleCode为3及当前创建用户id
            clusterParam.setRoleCode(DictConstants.ROLE_CODE_SUBUESR);
            clusterParam.setCreateUserId(userId);
        } else {
            return new PageInfo<>(new ArrayList<>());
        }
        List<ClusterVO> list = clusterMapper.getClusterList(clusterParam);
        for (ClusterVO vo : list) {
            Map<String, String> dictMapByType = dictService.getDictMapByType(DictConstants.USE_TYPE);
            vo.setUseType(dictMapByType.get(vo.getUseType()));
        }
        return new PageInfo<>(list);
    }


    public ClusterPO saveCluster(ClusterPO clusterPO) {
        String id = clusterPO.getId();
        if (ObjectUtil.isNotNull(id)) {
            // 更新，将原纪录is_deleted置为1
            ClusterPO deleteClusterPo = new ClusterPO();
            deleteClusterPo.setId(id);
            PoUtil.initDelPo(deleteClusterPo);
            clusterMapper.deleteById(deleteClusterPo);
        }
        clusterPO.setId(StringUtil.getRandomUUID());
        PoUtil.initAddPo(clusterPO);
        clusterMapper.insert(clusterPO);
        logService.logCluster(LogConstants.SYS_LOG_CLUSTER_INSERT, clusterPO);
        return clusterPO;
    }


    public PageInfo<ClusterVO> getClusterHistory(ClusterParam clusterParam) {
        PageUtil.setPageInfo(clusterParam);
        List<ClusterVO> list = clusterMapper.getClusterHistory(clusterParam);
        return new PageInfo<>(list);
    }


    public HashMap<String, Integer> getClusterNum() {

        ClusterParam clusterParam = new ClusterParam();
        String roleCode = AuthUtil.getCurrentUserRoleCode();
        String useType = AuthUtil.getCurrentUseType();
        String userId = AuthUtil.getCurrentUserId();
        Integer totalSimulationAll;
        Integer totalDynamicAll;
        //当前账户为管理员账户，需要查询普通账户，设置roleCode为2
        if (DictConstants.ROLE_CODE_ADMIN.equals(roleCode) || DictConstants.ROLE_CODE_SYSADMIN.equals(roleCode)) {
            clusterParam.setRoleCode(DictConstants.ROLE_CODE_UESR);
            totalSimulationAll = -1;
            totalDynamicAll = -1;
        } else if (DictConstants.ROLE_CODE_UESR.equals(roleCode) && DictConstants.USER_TYPE_EXCLUSIVE.equals(useType)) {
            // 当前账户为独占使用的普通账户，需要查询该账户创建的普通账户子账户，设置roleCode为3及当前创建用户id
            clusterParam.setRoleCode(DictConstants.ROLE_CODE_SUBUESR);
            clusterParam.setCreateUserId(userId);
            // 查询该普通账户所有的集群数量
            totalSimulationAll = clusterMapper.getSimulationLicenseNum(userId);
            totalDynamicAll = clusterMapper.getDynamicLicenseNum(userId);
        } else {
            throw new RuntimeException("用户类型获取失败。");
        }

        HashMap<String, Integer> resMap = clusterMapper.getClusterNum(clusterParam);
        resMap.put("totalSimulationAll", totalSimulationAll);
        resMap.put("totalDynamicAll", totalDynamicAll);
        return resMap;
    }


    @SneakyThrows
    public int getLicenseNum() {
        try {
            //1 获取当前用户信息
            String roleCode = AuthUtil.getCurrentUserRoleCode();
            String userType = AuthUtil.getCurrentUseType();
            String userId = AuthUtil.getCurrentUserId();
            log.info("当前用户信息为：roleCode - " + roleCode + "，userType - " + userType + "，userId - " + userId);

            //2 获取当前用户使用的集群账户 id
            if (DictConstants.ROLE_CODE_ADMIN.equals(roleCode) || DictConstants.ROLE_CODE_SYSADMIN.equals(roleCode)) { // 管理
                return -1;
            } else if (DictConstants.ROLE_CODE_UESR.equals(roleCode)) { //普通
                ClusterParam clusterParam = new ClusterParam();
                clusterParam.setCreateUserId(userId);
                Integer licenseTotal = clusterMapper.getSimulationLicenseNum(userId);   // 拥有节点
                if (DictConstants.USER_TYPE_EXCLUSIVE.equals(userType)) { // 普通独占
                    if (licenseTotal == null || licenseTotal == 0) {
                        return 0;
                    } else {
                        Integer licenseAssigned = clusterMapper.getAssignedSimLicenseNum(clusterParam);    // 已分配节点
                        return licenseTotal - licenseAssigned;
                    }
                } else if (DictConstants.USER_TYPE_PUBLIC.equals(userType)) {
                    return licenseTotal;
                } else {
                    throw new RuntimeException("普通用户占用类型获取失败。");
                }

            } else if (DictConstants.ROLE_CODE_SUBUESR.equals(roleCode)) {
                int licenseTotal;
                if (DictConstants.USER_TYPE_EXCLUSIVE.equals(userType)) {
                    ClusterParam clusterParam = new ClusterParam();
                    clusterParam.setCreateUserId(userId);
                    licenseTotal = clusterMapper.getSimulationLicenseNum(userId);   // 拥有节点
                } else if (DictConstants.USER_TYPE_PUBLIC.equals(userType)) {
                    //查询父账户
                    userId = AuthUtil.getCreateUserId();
                    ClusterParam clusterParam = new ClusterParam();
                    clusterParam.setCreateUserId(userId);
                    licenseTotal = clusterMapper.getSimulationLicenseNum(userId);   // 拥有节点
                } else {
                    throw new RuntimeException("普通用户子账户占用类型获取失败。");
                }
                return licenseTotal;
            } else {
                throw new RuntimeException("用户类型获取失败。");
            }
        } catch (Exception e) {
            throw new RuntimeException("此用户暂未分配集群");
        }
    }

    public ClusterVO getClusterByUserId() {
        String roleCode = AuthUtil.getCurrentUserRoleCode();
        String useType = AuthUtil.getCurrentUseType();
        String userId = AuthUtil.getCurrentUserId();
        if (DictConstants.ROLE_CODE_ADMIN.equals(roleCode) || DictConstants.ROLE_CODE_SYSADMIN.equals(roleCode)) { //管理员账户
            return null;
        } else if (DictConstants.ROLE_CODE_SUBUESR.equals(roleCode) && DictConstants.USER_TYPE_PUBLIC.equals(useType)) { //公共使用的普通子账户
            //查询父账户
            userId = AuthUtil.getCreateUserId();
        }
        return clusterMapper.getClusterByUserId(userId);
    }


    public ClusterVO getValidClusterInfo(ClusterParam clusterParam) {
        String roleCode = AuthUtil.getCurrentUserRoleCode();
        String useType = AuthUtil.getCurrentUseType();
        String currentUserId = AuthUtil.getCurrentUserId();
        if (DictConstants.ROLE_CODE_UESR.equals(roleCode) && DictConstants.USER_TYPE_EXCLUSIVE.equals(useType)) {
            //当前账户为独占使用的普通账户，其集群配置信息
            ClusterVO clusterVO = clusterMapper.getClusterByUserId(currentUserId);

            //查询当前普通账户分配给其子账户的集群总数量
            clusterParam.setCreateUserId(currentUserId);
            Integer assignedSimLicenseNum = clusterMapper.getAssignedSimLicenseNum(clusterParam);
            Integer assignedDynLicenseNum = clusterMapper.getAssignedDynLicenseNum(clusterParam);

            //当前普通账户的集群总数量减去已分配的数量
            if (ObjectUtil.isNotNull(clusterVO)) {
                int validSimLicenseNum = clusterVO.getNumSimulationLicense();
                int validDynLicenseNum = clusterVO.getNumDynamicLicense();
                if (ObjectUtil.isNotNull(assignedSimLicenseNum) && clusterVO.getNumSimulationLicense() >= assignedSimLicenseNum) {
                    validSimLicenseNum = validSimLicenseNum - assignedSimLicenseNum;
                }
                if (ObjectUtil.isNotNull(assignedDynLicenseNum) && clusterVO.getNumDynamicLicense() >= assignedDynLicenseNum) {
                    validDynLicenseNum = validDynLicenseNum - assignedDynLicenseNum;
                }
                clusterVO.setValidNumSimLicense(validSimLicenseNum);
                clusterVO.setValidNumDynLicense(validDynLicenseNum);

                return clusterVO;
            }

        }
        return null;
    }

}
