<script setup lang="ts">
import { ILdap, ILdapUserGroup } from '@/model/Users/ldap-interface';
import { ref, PropType, reactive, computed, nextTick, provide } from 'vue';
import { deepClone, getRuleText } from '@/utils/utils';
import { saveLdapGroup } from '../services/ldap.service';
import { SecondAuthorityFail } from '../../models/model';
import { getStoreData, loading, showSuccessMessage } from '@/utils/composition';
import SecondPassword from '@/components/SecondPassword/SecondPassword.vue';
import CustomDrawer from '@/components/CustomDrawer/CustomDrawer.vue';
import LdapGroupDetails from './LdapGroupDetails.vue';

const props = defineProps({
  data: {
    requied: true,
    type: Object as PropType<ILdap>,
    default: () => {
      return {
        Controller: {},
        LdapGroup: [],
        Certificate: {},
      };
    },
  },
  locked: {
    type: Boolean,
    required: true,
    default: false,
  },
});
const isNoPwd = getStoreData('loct', 'nopwd');
const emits = defineEmits(['change']);
const ldapHalfModal = ref();
// 展示的表格数据
const data = computed(() => {
  return props.data.LdapGroup.filter((item: ILdapUserGroup) => {
    return item.Name !== '';
  });
});

const editDrawer = ref();
const ldapDrawerTitle = ref('COMMON_ADD_GROUP');
const openType = ref('');
const secPwd = ref();
let openRow: any = reactive({});

// 传入到 "新增/编辑" 组件的数据
const ldapData: any = reactive({
  type: openType,
  row: openRow,
});
provide('ldapData', ldapData);

// 表头信息
const columns = ref([
  {
    label: 'TABLE_TITLE_NUM',
    prop: 'num',
  },
  {
    label: 'TABLE_TITLE_GROUP_NAME',
    prop: 'userGroup',
  },
  {
    label: 'TABLE_TITLE_ROLE',
    prop: 'role',
  },
  {
    label: 'TABLE_TITLE_LOGIN_INTERFACE',
    prop: 'interface',
  },
  {
    label: 'TABLE_TITLE_FOLDER',
    prop: 'folder',
  },
  {
    label: 'TABLE_TITLE_RULE',
    prop: 'rule',
  },
  {
    label: 'TABLE_TITLE_OPERATOR',
    prop: 'opderator',
  },
]);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);

function handleSizeChange() {}

// 添加，编辑用户组
function openDrawer(type: string, row: ILdapUserGroup) {
  openType.value = type;
  Object.assign(openRow, row);
  ldapDrawerTitle.value = type === 'add' ? 'COMMON_ADD_GROUP' : 'COMMON_EDIT_GROUP';
  editDrawer.value.show();
}

// 过滤出ID最低的组用户数据
function getLowerGroupId(): ILdapUserGroup {
  return props.data.LdapGroup.filter((item: ILdapUserGroup) => item.Name === '').sort(
    (a, b) => a.ID - b.ID,
  )[0];
}

// 删除用户组
function deleteGroup(row: ILdapUserGroup) {
  Object.assign(openRow, row);
  if (!isNoPwd) {
    secPwd.value.show();
  } else {
    closeModal({ reason: true, password: '' });
  }
}

// 关闭划窗，并向上发送change事件，重新刷新LDAP数据
function closeHalfModal() {
  editDrawer.value.hide();
  nextTick(() => {
    emits('change');
  });
}

// 点确定删除LDAP组用户
function closeModal(res: { reason: boolean; password: string }) {
  if (res.reason) {
    const param: any = { LdapGroup: [] };
    let position = 0;
    props.data.LdapGroup.forEach((item, index) => {
      if (openRow.ID === item.ID) {
        position = index;
      }
    });
    while (position > 0) {
      position--;
      const originalData = deepClone(props.data.LdapGroup[position]);
      if (originalData.Name === '') {
        continue;
      }
      delete originalData.ID;
      delete originalData.RoleLabel;
      param.LdapGroup.push({ ...originalData });
    }
    param.LdapGroup.push({ Name: '' } as never);
    loading(true);
    saveLdapGroup(props.data.Url?.control as string, param, res.password)
      .then(
        () => {
          showSuccessMessage();
          secPwd.value.hide();
          emits('change');
        },
        error => {
          const errorCode = error.data.error[0].code;
          if (
            errorCode === SecondAuthorityFail.REAUTHFAILED ||
            errorCode === SecondAuthorityFail.AUTHORIZATIONFAILED
          ) {
            secPwd.value.setErrorId();
            secPwd.value.clearPassword();
          }
        },
      )
      .finally(() => {
        loading(false);
      });
  } else {
    secPwd.value.hide();
  }
}

function closeDrawer(reason: boolean) {
  if (!reason) {
    editDrawer.value.hide();
    emits('change');
  } else {
    ldapHalfModal.value.save();
  }
}
</script>

<template>
  <div class="root-container">
    <div class="right-container ldap-group">
      <p>{{ $t('LDAP_USER_GROUP') }}</p>
      <div v-if="data.length < 5" v-privil.userConfig class="add-group">
        <el-button
          :id="'addLdapGroup'"
          :disabled="props.locked"
          @click="openDrawer('add', getLowerGroupId())"
        >
          {{ $t('COMMON_ADD_GROUP') }}
        </el-button>
      </div>
      <el-table :id="'ldapTable'" :data="data" resizable border>
        <el-table-column :prop="'num'" :label="$t(columns[0].label)" :resizable="true">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column :prop="'userGroup'" :label="$t(columns[1].label)" :resizable="true">
          <template #default="scope">{{ scope.row.Name }}</template>
        </el-table-column>
        <el-table-column :prop="'role'" :label="$t(columns[2].label)" :resizable="true">
          <template #default="scope">{{ scope.row.RoleLabel }}</template>
        </el-table-column>
        <el-table-column :prop="'interface'" :label="$t(columns[3].label)" :resizable="true">
          <template #default="scope">
            <el-tag
              v-for="item of scope.row.LoginInterface"
              :key="item"
              size="small"
              type="success"
              effect="dark"
            >
              {{ item }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :prop="'folder'" :label="$t(columns[4].label)" :resizable="true">
          <template #default="scope">{{ scope.row.Folder }}</template>
        </el-table-column>
        <el-table-column :prop="'rule'" :label="$t(columns[5].label)" :resizable="true">
          <template #default="scope">
            <el-tag
              v-for="item of scope.row.LoginRule"
              :key="item"
              size="small"
              type="success"
              effect="dark"
            >
              {{ getRuleText(item) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :prop="'opderator'" :label="$t(columns[6].label)">
          <template #default="scope">
            <el-button
              :id="'editLdapGroup' + (scope.$index + 1)"
              v-privil.userConfig
              type="text"
              :disabled="props.locked"
              @click="openDrawer('edit', scope.row)"
            >
              {{ $t('COMMON_EDIT') }}
            </el-button>
            <el-button
              :id="'deleteLdapGroup' + (scope.$index + 1)"
              v-privil.userConfig
              type="text"
              :disabled="props.locked"
              @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="data.length"
        v-model:currentPage="currentPage"
        v-addId.pagination="'ldapPagination'"
        :page-sizes="[10, 15, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.length"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 编辑用户组 -->
    <CustomDrawer ref="editDrawer" :title="$t(ldapDrawerTitle)" @close="closeDrawer">
      <LdapGroupDetails
        ref="ldapHalfModal"
        :data="props.data"
        @close="closeHalfModal"
        @enable="editDrawer.enable()"
        @disable="editDrawer.disable()"
      />
    </CustomDrawer>

    <!-- 删除用户组二次密码确认 -->
    <SecondPassword ref="secPwd" @close="closeModal" />
  </div>
</template>

<style lang="scss" scoped>
.ldap-group {
  position: relative;
  padding: 0 34px 24px 34px;
  p {
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: 600;
  }
}
.add-group {
  margin-bottom: 16px;
}
:deep(.el-button) {
  min-width: auto;
}
:deep(.el-pagination) {
  margin-top: 16px;
}
:deep(.el-tag) {
  margin-right: 4px;
}
</style>
