<template>
  <div>
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'gender'">
          <Tag :color="formatDictColor(sysSexOptions, record.gender)">
            {{ formatDictValue(sysSexOptions, record.gender) }}
          </Tag>
        </template>
        <template v-if="column.key === 'lockFlag'">
          <Tag :color="record.lockFlag === '0' ? 'success' : 'error'">
            {{ formatDictValue(sysLockFlagOptions, record.lockFlag) }}
          </Tag>
        </template>
        <template v-if="column.key === 'status'">
          <Tag :color="formatDictColor(sysUserStatus, record.status)">
            {{ formatDictValue(sysUserStatus, record.status) }}
          </Tag>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                auth: ['sys:user:reset'],
                icon: 'icon-key|iconfont',
                tooltip: '重置密码',
                popConfirm: {
                  title: '是否重置密码',
                  placement: 'left',
                  confirm: handleResetPwd.bind(null, record),
                },
              },
              {
                auth: ['sys:user:edit'],
                icon: 'icon-edit|iconfont',
                tooltip: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                auth: ['sys:user:remove'],
                icon: 'icon-delete|iconfont',
                tooltip: '删除',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
      <template #toolbar>
        <a-button
          v-auth="['sys:user:add']"
          type="primary"
          @click="handleCreate"
          preIcon="icon-plus|iconfont"
          >新增</a-button
        >
        <!-- <a-button
          v-auth="['sys:user:export']"
          color="warning"
          @click="handleExport"
          preIcon="ant-design:download-outlined"
          >导出</a-button
        > -->
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { onBeforeMount, ref, watch } from 'vue'; // , watch nextTick,
  import { Tag } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import FormModal from './FormModal.vue';
  import { columns, searchFormSchema } from './data';

  import { sysUserQueryPage, sysUserRemove, sysResetPwd } from '/@/api/sys/sysUserApi';
  import { listDictModel } from '/@/api/common';
  import { formatDictValue, formatDictColor } from '/@/utils';

  const sysStatusOptions = ref([]);
  const sysLockFlagOptions = ref([]);
  const sysSexOptions = ref([]);
  const sysUserStatus = ref([]);

  const props = defineProps({
    nodeId: {
      type: String,
    },
  });
  watch(
    () => props.nodeId,
    (newVal, oldVal) => {
      if (newVal != '0') {
        if (newVal != oldVal) {
          setProps({
            searchInfo: { orgId: newVal, page: 1 },
          });
          reload();
        }
      } else {
        setProps({
          searchInfo: { orgId: undefined, page: 1 },
        });
        reload();
      }
    },
    { deep: true },
  );
  onBeforeMount(async () => {
    sysStatusOptions.value = await listDictModel({ dictCode: 'sys_status' });
    sysLockFlagOptions.value = await listDictModel({ dictCode: 'sys_lock_flag' });
    sysSexOptions.value = await listDictModel({ dictCode: 'sys_sex' });
    sysUserStatus.value = await listDictModel({ dictCode: 'sys_user_status' });
  });

  const { createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, setProps }] = useTable({
    title: '用户列表 ',
    api: sysUserQueryPage,
    rowKey: 'id',
    searchInfo: {},
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      baseColProps: { xs: 24, sm: 12, md: 12, lg: 12, xl: 8 },
      resetButtonOptions: {
        preIcon: 'icon-delete|iconfont',
      },
      submitButtonOptions: {
        preIcon: 'icon-search|iconfont',
      },
    },
    showIndexColumn: false,
    useSearchForm: true,
    bordered: true,
    actionColumn: {
      auth: ['sys:user:reset', 'sys:user:edit', 'sys:user:remove'],
      width: 120,
      title: '操作',
      dataIndex: 'action',
    },
  });

  // 新增按钮事件
  function handleCreate() {
    const record = {};
    openModal(true, {
      record,
      isUpdate: false,
    });
  }

  // 编辑按钮事件
  function handleEdit(record: Recordable) {
    console.log(record);
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    console.log(record);
    await sysUserRemove([record.id]);
    createMessage.success('删除成功！');
    reload();
    // 表格刷新，在refresh-tree事件之后，执行
    // await reload();
  }

  // 弹窗回调事件
  async function handleSuccess() {
    // console.log(isUpdate);
    // console.log(values);
    reload();
    // 表格刷新，在refresh-tree事件之后，执行
    // reload();
  }

  // 刷新表格
  function refresh() {
    reload();
  }

  // 重置密码按钮事件
  async function handleResetPwd(record: Recordable) {
    console.log(record);
    await sysResetPwd([record.id]);
    createMessage.success('密码重置成功');
    reload();
  }
  // 暴露内部方法
  defineExpose({ refresh });
</script>
