<script lang="ts" setup>
import { reactive, ref, inject, watch, onMounted, computed } from 'vue';
import { traduction, getErrorTranslate } from '@/utils/language';
import LoginRules from '@/components/LoginRules/LoginRules.vue';
import { ILoginRule, IKerberosSaveData } from '@/pages/User/models/type';
import { saveGroup } from '../services/kerberos.services';
import { showElMessage, getMessageId } from '@/utils/utils';
import useStore from '@/stores';
import { getStoreData } from '@/utils/composition';
import { BaseValidators } from '@/validators/base-validators';
import { loading } from '@/utils/composition';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
import Schema from 'async-validator';
import { getPermissionManagementData } from '../../Security/securtyPages/PermissionManagement/permission-management.server';

const store = useStore();
const pwdMaxLen = getStoreData('loct', 'pml');
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});

const rules: any = {
  groupName: [
    BaseValidators.Required({ message: traduction('VALIDTOR_FORMAT_ERROR') }),
    BaseValidators.NotAllWhiteSpace(),
    BaseValidators.MaxLength255(),
  ],
  groupDomain: [BaseValidators.MaxLength255()],
  groupSID: [BaseValidators.Required({ message: traduction('VALIDTOR_FORMAT_ERROR') })],
};
const groupFolderState = ref(false);
// 是否免密登录
const nopwd = getStoreData('loct', 'nopwd');
const userPasswordMsg = ref('');
defineExpose({
  save,
});

const rawRoleOptions = [
  {
    value: 'Administrator',
    label: traduction('COMMON_ROLE_ADMINISTRATOR'),
  },
  {
    value: 'Operator',
    label: traduction('COMMON_ROLE_OPERATOR'),
  },
  {
    value: 'Common User',
    label: traduction('COMMON_ROLE_COMMONUSER'),
  },
  {
    value: 'Custom Role 1',
    label: traduction('COMMON_ROLE_CUSTOMROLE1'),
  },
  {
    value: 'Custom Role 2',
    label: traduction('COMMON_ROLE_CUSTOMROLE2'),
  },
  {
    value: 'Custom Role 3',
    label: traduction('COMMON_ROLE_CUSTOMROLE3'),
  },
  {
    value: 'Custom Role 4',
    label: traduction('COMMON_ROLE_CUSTOMROLE4'),
  },
  {
    value: 'Custom Role 5',
    label: traduction('COMMON_ROLE_CUSTOMROLE5'),
  },
  {
    value: 'Custom Role 6',
    label: traduction('COMMON_ROLE_CUSTOMROLE6'),
  },
  {
    value: 'Custom Role 7',
    label: traduction('COMMON_ROLE_CUSTOMROLE7'),
  },
  {
    value: 'Custom Role 8',
    label: traduction('COMMON_ROLE_CUSTOMROLE8'),
  },
  {
    value: 'Custom Role 9',
    label: traduction('COMMON_ROLE_CUSTOMROLE9'),
  },
  {
    value: 'Custom Role 10',
    label: traduction('COMMON_ROLE_CUSTOMROLE10'),
  },
  {
    value: 'Custom Role 11',
    label: traduction('COMMON_ROLE_CUSTOMROLE11'),
  },
  {
    value: 'Custom Role 12',
    label: traduction('COMMON_ROLE_CUSTOMROLE12'),
  },
  {
    value: 'Custom Role 13',
    label: traduction('COMMON_ROLE_CUSTOMROLE13'),
  },
  {
    value: 'Custom Role 14',
    label: traduction('COMMON_ROLE_CUSTOMROLE14'),
  },
  {
    value: 'Custom Role 15',
    label: traduction('COMMON_ROLE_CUSTOMROLE15'),
  },
  {
    value: 'Custom Role 16',
    label: traduction('COMMON_ROLE_CUSTOMROLE16'),
  },
];

const roleOptions = ref<typeof rawRoleOptions>([]);

const row: any = inject('row');
const interfaceList = reactive(['Web', 'Redfish']);
let type = '';

let userLoginPwd = ref('');
let baseFormData = {};

const userGroup = reactive({
  groupName: '',
  groupSID: '',
  groupRole: rawRoleOptions[2].value,
  groupLoginInterface: [...interfaceList],
  groupLoginRule: [],
  groupDomain: '',
  memberId: 0,
});
// 初始化
async function init(rowData: any) {
  const roleData: any = await getPermissionManagementData();
  const supportedRoles = (roleData?.Members ?? [])
    .filter((item: any) => item.Name.includes('CustomRole'))
    .map((item: any) => item.Name.split('CustomRole').pop());
  roleOptions.value = rawRoleOptions.filter(item => 
    !item.value.includes('Custom') || supportedRoles.includes(item.value.split(' ').pop()));
  userPasswordMsg.value = '';
  userLoginPwd.value = '';
  // 如果name为空则是添加
  userGroup.groupName = rowData.data.groupName;
  userGroup.groupDomain = rowData.data.groupDomain;
  userGroup.groupSID = rowData.data.groupSID;
  userGroup.groupLoginRule = [...rowData.data.groupLoginRule] as any;
  userGroup.memberId = rowData.data.memberId;
  if (rowData.data.groupName === '') {
    type = 'add';
  } else {
    type = 'edit';
    userGroup.groupRole = rowData.data.groupRole;
    userGroup.groupLoginInterface = [...rowData.data.groupLoginInterface];
  }
  // 保存基础数据
  baseFormData = {
    groupName: rowData.data.groupName,
    groupDomain: rowData.data.groupDomain,
    groupSID: rowData.data.groupSID,
    groupRole: rowData.data.groupRole,
    groupLoginRule: [...rowData.data.groupLoginRule],
    groupLoginInterface: [...rowData.data.groupLoginInterface],
    memberId: rowData.data.memberId,
  };
}
function groupNameChange() {
  computeSaveState();
}
function groupFolder() {
  computeSaveState();
}
function sidChange() {
  computeSaveState();
}
function roleChange() {
  computeSaveState();
}
function interFace() {
  computeSaveState();
}
function pwdChange() {
  userPasswordMsg.value = '';
  computeSaveState();
}

const emits = defineEmits(['close', 'enable', 'disable']);
const formSchema = new Schema(rules);
let formState = true;
// 计算保存按钮状态
function computeSaveState() {
  formSchema.validate(userGroup, (errors, fields) => {
    if (errors) {
      formState = false;
    } else {
      formState = true;
    }
  });
  let isChange = false;
  for (let key in userGroup) {
    if (userGroup[key] !== row.data[key] && typeof userGroup[key] === 'string') {
      isChange = true;
    }
  }
  if (
    JSON.stringify(userGroup.groupLoginInterface.sort()) !==
    JSON.stringify(baseFormData['groupLoginInterface'].sort())
  ) {
    isChange = true;
  }
  if (
    JSON.stringify(userGroup.groupLoginRule.sort()) !==
    JSON.stringify(baseFormData['groupLoginRule'].sort())
  ) {
    isChange = true;
  }
  const isPwdValid = nopwd || userLoginPwd.value.length > 0;
  const state = !(isPwdValid && isChange && formState);
  if (state) {
    emits('disable');
  } else {
    emits('enable');
  }
}

// 保存数据
function save() {
  const params = getChangedData();
  loading(true);
  saveGroup(params, userLoginPwd.value)
    .then(res => {
      showElMessage('success', traduction('COMMON_SUCCESS'));
      emits('close');
    })
    .catch(error => {
      const errorId = getMessageId(error.data);
      if (errorId instanceof Array && errorId.length > 0) {
        const errorMsg = getErrorTranslate(errorId[0].code as string);
        if (errorId[0].code === 'ReauthFailed' || errorId[0].code === 'AuthorizationFailed') {
          userPasswordMsg.value = traduction('COMMON_SECONDPWD_ERROR');
        } else {
          showElMessage('error', errorMsg);
        }
      } else {
        showElMessage('error', traduction('COMMON_FAILED'));
      }
    })
    .finally(() => {
      userLoginPwd.value = '';
      loading(false);
      computeSaveState();
    });
}

// 编辑新增时,组装变化的数据
function getChangedData(): { Group: IKerberosSaveData[] } {
  const param: { Group: Array<any> } = { Group: [] };
  const temp: IKerberosSaveData = {};
  let memberId = row.data.memberId;
  while (memberId > 0) {
    param.Group.push({});
    memberId--;
  }
  if (type === 'add') {
    temp.LoginRule = userGroup.groupLoginRule;
    temp.LoginInterface = [...userGroup.groupLoginInterface];
    temp.Name = userGroup.groupName;
    temp.Domain = userGroup.groupDomain;
    temp.SID = userGroup.groupSID;
    temp.RoleID = userGroup.groupRole;
  } else {
    if (userGroup.groupSID !== baseFormData['groupSID']) {
      temp.SID = userGroup.groupSID;
    }
    if (
      JSON.stringify(userGroup.groupLoginRule.sort()) !==
      JSON.stringify(baseFormData['groupLoginRule'].sort())
    ) {
      temp.LoginRule = [...userGroup.groupLoginRule.sort()];
    }
    if (
      JSON.stringify(userGroup.groupLoginInterface.sort()) !==
      JSON.stringify(baseFormData['groupLoginInterface'].sort())
    ) {
      temp.LoginInterface = [...userGroup.groupLoginInterface.sort()];
    }
    if (userGroup.groupName !== baseFormData['groupName']) {
      temp.Name = userGroup.groupName;
    }
    if (userGroup.groupDomain !== baseFormData['groupDomain']) {
      temp.Domain = userGroup.groupDomain;
    }
    if (userGroup.groupRole !== baseFormData['groupRole']) {
      temp.RoleID = userGroup.groupRole;
    }
  }
  param.Group.push(temp);
  return param;
}

// 修改登录规则
function loginRuleChange(val: any) {
  const ruleArr: any[] = [];
  Object.keys(val).forEach(key => {
    if (val[key]) {
      ruleArr.push(key);
    }
  });
  userGroup.groupLoginRule.length = 0;
  ruleArr.forEach(item => {
    userGroup.groupLoginRule.push(item as never);
  });
  computeSaveState();
}

onMounted(() => {
  init(row);
});

watch(
  () => row,
  newVal => {
    init(newVal);
  },
  { deep: true },
);
</script>

<template>
  <div id="userTemplate" class="group-container">
    <el-form label-width="auto" :model="userGroup" :rules="rules" label-position="left">
      <!-- 组名 -->
      <el-form-item :label="$t('COMMON_GROUP')" prop="groupName" class="is-required">
        <el-input
          v-model="userGroup.groupName"
          v-addId.input="'krbGroupName'"
          v-clearable
          clearable
          maxlength="255"
          @input="groupNameChange"
        >
          <template #suffix>
            <ErrorIcon />
            <ClearableIcon />
          </template>
        </el-input>
      </el-form-item>
      <!-- 组应用文件夹 -->
      <el-form-item prop="groupDomain" :label="$t('COMMON_GROUP_FOLDER_NAME')">
        <el-popover
          v-model:visible="groupFolderState"
          :content="$t('COMMON_GROUP_FOLDER_TIP')"
          width="320px"
          placement="top"
          trigger="focus"
          trigger-keys
        >
          <template #reference>
            <el-input
              v-model="userGroup.groupDomain"
              v-addId.input="'krbUserFolder'"
              v-clearable
              clearable
              maxlength="255"
              @input="groupFolder"
              @focus="groupFolderState = true"
              @blur="groupFolderState = false"
            >
              <template #suffix>
                <ErrorIcon />
                <ClearableIcon />
              </template>
            </el-input>
          </template>
        </el-popover>
      </el-form-item>
      <!-- 组SID -->
      <el-form-item :label="$t('COMMON_GROUP_SID')" class="is-required">
        <el-input
          v-model="userGroup.groupSID"
          v-addId.input="'krbSid'"
          v-clearable
          clearable
          maxlength="255"
          @input="sidChange"
        >
          <template #suffix>
            <ErrorIcon />
            <ClearableIcon />
          </template>
        </el-input>
      </el-form-item>
      <!-- 角色 -->
      <el-form-item :label="$t('COMMON_ROLE')">
        <el-select
          v-model="userGroup.groupRole"
          v-addId.input="'krbGroupRole'"
          :teleported="false"
          :disabled="isSystemLock"
          @change="roleChange"
        >
          <el-option
            v-for="(item, index) in roleOptions"
            :id="'ruleItem' + index"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 登录规则 -->
      <el-form-item :label="$t('COMMON_LOGIN_RULE')">
        <LoginRules
          id="krbGroupRule"
          :show-type="'pullDown'"
          :check-list="userGroup.groupLoginRule"
          @login-rule-change="loginRuleChange"
        ></LoginRules>
      </el-form-item>
      <!-- 登录接口 -->
      <el-form-item :label="$t('COMMON_LOGIN_INTERFACE')">
        <el-checkbox-group
          id="krbGroupInterface"
          v-model="userGroup.groupLoginInterface"
          :disabled="isSystemLock"
          @change="interFace"
        >
          <el-checkbox
            v-for="item in interfaceList"
            :key="item"
            v-addId.checkbox="item + 'ck'"
            :label="item"
          >
            {{ item }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 当前登录密码 -->
      <el-form-item
        v-if="!nopwd"
        :label="$t('COMMON_LOGIN_PASSWORD')"
        class="is-required"
        :error="userPasswordMsg"
      >
        <el-input
          v-model="userLoginPwd"
          v-addId.input="'krbGroupSecondPassword'"
          v-clearable
          clearable
          :disabled="isSystemLock"
          type="password"
          autocomplete="new-password"
          :maxlength="pwdMaxLen"
          :placeholder="$t('COMMON_PASSWORD_PLACEHOLDER')"
          @input="pwdChange"
        >
          <template #suffix>
            <ErrorIcon />
            <ClearableIcon />
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.group-container {
  padding: 0 24px 72px 24px;

  :deep(.el-form-item__content) {
    max-width: 320px;
  }

  .el-select {
    width: 100%;
  }

  :deep(.is-required) {
    .el-form-item__label::before {
      content: '*';
      position: absolute;
      font-size: 12px;
      color: var(--o-form-require-color) !important;
      margin-right: 0 !important;
    }
  }
}
</style>
