<script lang="ts" setup>
import { ref, reactive, toRefs, provide, computed, watch } from 'vue';
import CustomDrawer from '@/components/CustomDrawer/CustomDrawer.vue';
import { IUserGroup } from '@/model/Users/kerberos-interface';
import KerberosGroupEdit from './KerberosGroupEdit.vue';
import useStore from '@/stores';
import SecondPassword from '@/components/SecondPassword/SecondPassword.vue';
import { getStoreData, loading } from '@/utils/composition';
import { saveGroup } from '../services/kerberos.services';
import { showElMessage, getMessageId, getRuleText, transformRole } from '@/utils/utils';
import { traduction, getErrorTranslate } from '@/utils/language';

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

const props = defineProps({
  data: {
    required: true,
    type: Array,
    default: () => [],
  },
});
const emits = defineEmits(['change']);
const krbHalfModal = ref();

const { data } = toRefs(props);
const tableData = ref([]);
const secPwd = ref();
const editDrawer = ref();
const drawerTitle = ref('COMMON_ADD_GROUP');
let userGroup = reactive({});
const addDisabled = ref(false);
// 是否免密登录
const nopwd = getStoreData('loct', 'nopwd');
// 分页
const currentPage = ref(1);
const pageSize = ref(10);
function handleSizeChange() {}
// 添加，编辑用户组
provide('row', { data: userGroup });
function openDrawer(type: string, row?: IUserGroup) {
  if (row) {
    Object.assign(userGroup, row);
  } else {
    let _row = data.value.find((item: any) => item.groupSID === '');
    if (_row) {
      Object.assign(userGroup, _row);
    }
  }
  drawerTitle.value = type === 'add' ? 'COMMON_ADD_GROUP' : 'COMMON_EDIT_GROUP';
  editDrawer.value.show();
}
// 点击删除用户组
function deleteGroup(row: IUserGroup) {
  Object.assign(userGroup, row);
  if (!nopwd) {
    secPwd.value.show();
  } else {
    deleteReq();
  }
}

function closeHalfModal() {
  editDrawer.value.hide();
  emits('change');
}

// 确认删除用户组
function closeModal(res: { reason: boolean; password: string }) {
  if (res.reason) {
    deleteReq(res.password);
  } else {
    secPwd.value.hide();
  }
}
// 发送删除请求
function deleteReq(pwd?: string) {
  const param: { Group: any[] } = { Group: [] };
  let memberId = userGroup['memberId'];
  while (memberId > 0) {
    param.Group.push({});
    memberId--;
  }
  param.Group.push({ DelGroupFlag: true });
  loading(true);
  if (nopwd) {
    saveGroup(param)
      .then(res => {
        showElMessage('success', traduction('COMMON_SUCCESS'));
      })
      .catch(error => {
        showElMessage('error', traduction('COMMON_FAILED'));
      })
      .finally(() => {
        loading(false);
        emits('change');
      });
  } else {
    saveGroup(param, pwd)
      .then(res => {
        showElMessage('success', traduction('COMMON_SUCCESS'));
        secPwd.value.hide();
      })
      .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') {
            secPwd.value.setErrorId();
            secPwd.value.clearPassword();
          } else {
            secPwd.value.clearPassword();
            showElMessage('error', errorMsg);
          }
        } else {
          showElMessage('error', traduction('COMMON_FAILED'));
        }
      })
      .finally(() => {
        loading(false);
        emits('change');
      });
  }
}

function closeDrawer(reason: boolean) {
  if (!reason) {
    emits('change');
    editDrawer.value.hide();
  } else {
    krbHalfModal.value.save();
  }
}

watch(
  () => props,
  newVal => {
    // 表格数据去掉sid为空的
    tableData.value = data.value.filter((item: any) => {
      return item.groupSID !== '';
    }) as any;
    tableData.value.length === 5 ? (addDisabled.value = true) : (addDisabled.value = false);
  },
  { deep: true },
);
</script>
<template>
  <div class="ker-group">
    <h3 class="group-title">{{ $t('KERBEROS_USER_GROUP') }}</h3>
    <div v-if="!addDisabled" class="add-group">
      <el-button
        id="addKrbGroup"
        v-privil.base.userConfig
        :disabled="isSystemLock"
        @click="openDrawer('add')"
      >
        {{ $t('COMMON_ADD_GROUP') }}
      </el-button>
    </div>
    <el-table id="krbTable" border :data="tableData" resizable>
      <el-table-column
        type="index"
        width="80px"
        :label="$t('TABLE_TITLE_NUM')"
        :resizable="true"
      ></el-table-column>
      <el-table-column :label="$t('TABLE_TITLE_GROUP_NAME')" :resizable="true">
        <template #default="scope">{{ scope.row.groupName }}</template>
      </el-table-column>
      <el-table-column :label="$t('COMMON_GROUP_SID')" :resizable="true">
        <template #default="scope">{{ scope.row.groupSID }}</template>
      </el-table-column>
      <el-table-column :label="$t('TABLE_TITLE_ROLE')" :resizable="true">
        <template #default="scope">{{ transformRole(scope.row.groupRole) }}</template>
      </el-table-column>
      <el-table-column :label="$t('TABLE_TITLE_LOGIN_INTERFACE')" :resizable="true">
        <template #default="scope">
          <el-tag
            v-for="item of scope.row.groupLoginInterface"
            :key="item"
            size="small"
            type="success"
          >
            {{ item }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('TABLE_TITLE_FOLDER')" :resizable="true">
        <template #default="scope">{{ scope.row.groupDomain }}</template>
      </el-table-column>
      <el-table-column :label="$t('TABLE_TITLE_RULE')" :resizable="true">
        <template #default="scope">
          <el-tag v-for="item of scope.row.groupLoginRule" :key="item" size="small" type="success">
            {{ getRuleText(item) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('TABLE_TITLE_OPERATOR')">
        <template #default="scope">
          <el-button
            v-privil.base.userConfig
            class="operator"
            :disabled="isSystemLock"
            type="text"
            @click="openDrawer('edit', scope.row)"
          >
            {{ $t('COMMON_EDIT') }}
          </el-button>
          <el-button
            v-privil.base.userConfig
            class="operator"
            :disabled="isSystemLock"
            type="text"
            @click="deleteGroup(scope.row)"
          >
            {{ $t('COMMON_DELETE') }}
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <img src="@/assets/common/image/no-data.svg" />
        <div>{{ $t('COMMON_NO_DATA') }}</div>
      </template>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      v-if="tableData.length"
      v-model:currentPage="currentPage"
      v-addId.pagination="'kerberosPagination'"
      :page-sizes="[10, 15, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      @size-change="handleSizeChange"
    />
    <CustomDrawer ref="editDrawer" :title="$t(drawerTitle)" @close="closeDrawer">
      <KerberosGroupEdit
        ref="krbHalfModal"
        @enable="editDrawer.enable()"
        @disable="editDrawer.disable()"
        @close="closeHalfModal"
      ></KerberosGroupEdit>
    </CustomDrawer>
    <!-- 删除用户组二次密码确认 -->
    <SecondPassword ref="secPwd" @close="closeModal" />
  </div>
</template>
<style lang="scss" scoped>
.ker-group {
  .el-tag {
    margin-right: 4px;
  }
  .group-title {
    margin-bottom: 16px;
  }
}
.add-group {
  margin-bottom: 16px;
}
.operator {
  min-width: 0;
}
</style>
