<template>
  <div class="container">
    <a-card :bordered="false">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 4 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item
                  field="name"
                  :label="t('manage.form.name')"
                  label-col-flex="50px"
                >
                  <a-input
                    v-model="formModel.name"
                    :placeholder="t('manage.form.name')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  field="desc"
                  :label="t('manage.form.desc')"
                  label-col-flex="40px"
                >
                  <a-input
                    v-model="formModel.desc"
                    :placeholder="t('manage.form.desc')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider :style="{ height: '35px' }" direction="vertical" />
        <a-col :flex="'42px'">
          <a-space :size="10">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ t('searchTable.form.reset') }}
            </a-button>
            <a-button
              type="primary"
              @click="
                showEditDialog = true;
                userId = 0;
              "
            >
              <template #icon>
                <icon-plus />
              </template>
              {{ t('searchTable.form.add') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        class="table-list"
        row-key="name"
        :loading="loading"
        :pagination="pagination"
        :columns="cloneColumns"
        :data="paginatedData"
        :bordered="false"
        :size="size"
        :scrollbar="true"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #privilege="{ record }">
          {{ getPrivilegeLabel(record.privilege) }}
        </template>

        <template #optional="{ record }">
          <a-button
            status="danger"
            size="mini"
            @click="handleDeleteFun(record.id)"
          >
            {{ t('searchTable.form.delete') }}
          </a-button>
        </template>
      </a-table>
    </a-card>
    <EditDialog
      v-model="showEditDialog"
      :id="userId"
      :privilegeList="privilegeList"
      @updateList="searchTable"
    ></EditDialog>
  </div>
</template>

<script lang="ts" setup name="Manage">
import {
  ref,
  reactive,
  shallowRef,
  h,
  getCurrentInstance,
  computed,
} from 'vue';
import { getUserList, fetchDeleteUser } from '@/api/user';
import type { UserData, UserParams } from '@/api/user';
import { SizeProps, Pagination } from '@/types/global';
import BTag from '@/components/business/b-tag/index.vue';
import type { TableColumnData } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import EditDialog from './components/edit.vue';
import { useI18n } from 'vue-i18n';
// import { privilegeList } from '@/utils/const';
import { Modal } from '@arco-design/web-vue';
import type { AdditionalProp } from '@/api/dict';
import useDictList from '@/hooks/dict-list';
const { t } = useI18n();

const { loading, setLoading } = useLoading(true);
const cloneColumns = computed(() => [
  {
    title: t('searchTable.table.number'),
    dataIndex: 'index',
    slotName: 'index',
  },
  {
    title: t('manage.form.name'),
    dataIndex: 'name',
    slotName: 'name',
  },
  {
    title: t('manage.form.desc'),
    dataIndex: 'desc',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: t('manage.form.permission'),
    dataIndex: 'privilege',
    slotName: 'privilege',
  },
  {
    title: t('searchTable.table.optional'),
    align: 'center',
    slotName: 'optional',
  },
]);
const basePagination: Pagination = {
  current: 1,
  pageSize: 20,
};
const pagination = reactive({
  ...basePagination,
});
const generateFormModel = () => {
  return {
    name: '',
    desc: '',
    privilege: null,
    pageIndex: 1,
    pageSize: 20,
  } as UserParams;
};
const renderData = ref<UserData[]>([] as UserData[]);
const size = ref<SizeProps>('medium');
const formModel = ref<UserParams>(generateFormModel());
const userId = shallowRef<number>(0);
const showEditDialog = shallowRef<boolean>(false);
const this_ = getCurrentInstance()?.appContext.config.globalProperties;
const privilegeList = ref<AdditionalProp[]>([]);
useDictList(['Privilege']).then(res => {
  privilegeList.value.push(...res['Privilege']);
});
const search = () => {
  searchTable();
};
const reset = () => {
  formModel.value = generateFormModel();
};
// 计算分页数据
const paginatedData = computed(() => {
  const start = (formModel.value.pageIndex - 1) * formModel.value.pageSize;
  return renderData.value.slice(start, start + formModel.value.pageSize);
});
function searchTable() {
  setLoading(true);
  getUserList(formModel.value)
    .then(res => {
      formModel.value.pageIndex = 1;
      pagination.current = 1;
      pagination.total = res.data.length;
      renderData.value = res.data;
    })
    .finally(() => {
      setLoading(false);
    });
}
searchTable();
const onPageChange = (current: number) => {
  formModel.value.pageIndex = current;
  pagination.current = current;
  // searchTable();
};
const handleDeleteFun = (id: number) => {
  Modal.warning({
    title: t('modal.warning.title'),
    content: t('modal.warning.content'),
    okText: t('searchTable.form.confirm'),
    onBeforeOk: (done: (closed: boolean) => void) => {
      fetchDeleteUser({ id })
        .then(res => {
          if (res.success) {
            this_?.$message.success(t('message.success'));
            searchTable();
          }
        })
        .finally(() => {
          done(true); // 确定关闭模态框
        });
    },
  });
};
const getPrivilegeLabel = computed(() => {
  return (privilegeValue: string | number) => {
    const privilege = privilegeList.value.find(
      item => item.dictCode === privilegeValue
    );
    return privilege ? t(privilege.name as string) : '-';
  };
});
</script>
<style scoped lang="less">
.container {
  padding: 10px;
}
</style>
