<template>
  <div>
    <n-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="basicTableRef"
        :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :autoScrollX="true">
        <template #tableTitle>
          <n-space>
            <n-button type="primary" @click="handleAdd" v-perm="['sys:user:add']">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              新建
            </n-button>

            <n-button type="error" @click="handleDelete" :disabled="!rowKeys.length" v-perm="['sys:user:batchDelete']">
              <template #icon>
                <n-icon>
                  <DeleteOutlined />
                </n-icon>
              </template>
              删除
            </n-button>
            <n-button @click="importVisible = true" v-perm="['sys:user:import']">
              <template #icon>
                <n-icon>
                  <ToTopOutlined />
                </n-icon>
              </template>
              导入
            </n-button>
            <n-button @click="handleExport" :loading="exportLoading" :disabled="exportLoading"
              v-perm="['sys:user:export']">
              <template #icon>
                <n-icon>
                  <DownloadOutlined />
                </n-icon>
              </template>
              导出
            </n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>
    <editDialog ref="createModalRef" :userId="userId" v-if="editVisible" v-model:visible="editVisible"
      @success="reloadTable('noRefresh')" />

    <userUpload v-if="importVisible" v-model:visible="importVisible" @success="reloadTable()" />
  </div>
</template>

<script lang="ts" setup>
import { h, nextTick, reactive, ref, unref } from 'vue';
import { useMessage, useDialog } from 'naive-ui';
import { TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Form/index';
import {
  getUserList,
  userDelete,
  userBatchDelete,
  userExport,
  resetPwd,
  getUserDocument,
} from '@/api/system/user';
import { columns } from './columns';
import {
  PlusOutlined,
  DeleteOutlined,
  LockOutlined,
  DownloadOutlined,
  PrinterOutlined,
  ToTopOutlined,
  FormOutlined
} from '@vicons/antd';
import CreateModal from './CreateModal.vue';
import editDialog from './edit.vue';
import userUpload from './userUpload.vue';
import { basicModal, useModal } from '@/components/Modal';
import { downloadByData } from '@/utils/file/download';
import { schemas } from './querySchemas';
import { renderIcon } from '@/utils';
import printJS from 'print-js';

const message = useMessage();
const dialog = useDialog()
const basicTableRef = ref();
const createModalRef = ref();
const editVisible = ref(false);
const userId = ref(0);
const rowKeys = ref([]);
const importVisible = ref(false)
const exportLoading = ref(false);

const showModal = ref(false);
const formParams = reactive({
  name: '',
  status: '',
});

const actionColumn = reactive({
  width: 400,
  title: '操作',
  align: 'center',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '编辑',
          icon: renderIcon(FormOutlined),
          type: 'warning',
          onClick: handleEdit.bind(null, record),
          auth: ['sys:user:update'],
        },
        {
          label: '删除',
          icon: renderIcon(DeleteOutlined),
          type: 'error',
          onClick: handleDelete.bind(null, record),
          auth: ['sys:user:delete'],
        },
        {
          label: '重置密码',
          icon: renderIcon(LockOutlined),
          type: 'info',
          onClick: handleResetPassword.bind(null, record),
          auth: ['sys:user:resetPwd'],
        },
        {
          label: '打印',
          type: 'info',
          icon: renderIcon(PrinterOutlined),
          onClick: handlePrint.bind(null, record),
        },
      ],
      select: (key) => {
        message.info(`您点击了，${key} 按钮`);
      },
    });
  },
});

function addTable() {
  showModal.value = true;
}

const loadDataTable = async (res) => {
  rowKeys.value = []
  const result = await getUserList({ ...formParams, ...res });
  return result;
};

function onCheckedRow(keys) {
  rowKeys.value = keys;
}

function reloadTable(noRefresh = '') {
  basicTableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
}

function handleSubmit(values: Recordable) {
  for (const key in formParams) {
    formParams[key] = '';
  }
  for (const key in values) {
    formParams[key] = values[key];
  }
  reloadTable();
}

function handleReset(values: Recordable) {
  for (const key in formParams) {
    formParams[key] = '';
  }
  for (const key in values) {
    formParams[key] = values[key];
  }
  reloadTable();
}

const [register, { }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});


/**
 * 执行重置密码
 * @param id 参数
 */
const handleResetPassword = (record) => {
  console.log(rowKeys.value)
  dialog.warning({
    title: '提示',
    content: '确定重置密码？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      await resetPwd({ userId: record.id });
      message.success('重置成功');
    },
  })
}
/**
* 执行添加
*/
const handleAdd = async () => {
  userId.value = 0;
  editVisible.value = true;
  await nextTick();
  createModalRef.value.openModal();
};
/**
* 执行编辑
*/
async function handleEdit(record: Recordable) {
  userId.value = record.id;
  editVisible.value = true;
  await nextTick();
  createModalRef.value.openModal();
}
/**
 * 执行删除
 * @param id 参数
 */
async function handleDelete(record) {
  dialog.warning({
    title: '提示',
    content: '确定要删除？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      record.id ? await userDelete(record.id) : await userBatchDelete(rowKeys.value);
      message.success('删除成功');
      reloadTable();
    },
  })
}
/**
 * 执行导出
 */
const handleExport = async () => {
  exportLoading.value = true;
  const data = await userExport();
  downloadByData(data, '用户信息.xlsx');
  exportLoading.value = false;
  message.success('导出成功');
};

/**
 * 执行打印
 * @param id 参数
 */
const handlePrint = async (record) => {
  const res = await getUserDocument(record.id);
  printJS({
    printable: res.fileUrl,
    type: 'pdf',
    showModal: true,
  });
};
</script>

<style lang="less" scoped></style>
