<template>
  <PageWrapper>
    <el-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <el-input v-model="model[field]" />
        </template>
      </BasicForm>
    </el-card>
    <el-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="tableRef"
        :actionColumn="actionColumn"
        @selection-change="onSelectionChange"
        scroll-x="1200"
        virtual-scroll
      >
        <template #tableTitle>
          <el-space>
            <el-button type="primary" @click="addUser" v-perm="['sys:user:add']">
              <template #icon>
                <el-icon style="vertical-align: middle">
                  <plus />
                </el-icon>
              </template>
              新建
            </el-button>

            <el-button
              type="danger"
              @click="handleDelete()"
              :disabled="!selectionData.length"
              v-perm="['sys:user:batchDelete']"
            >
              <template #icon>
                <el-icon class="el-input__icon">
                  <Delete />
                </el-icon>
              </template>
              删除
            </el-button>
            <el-button type="" @click="importVisible = true" v-perm="['sys:user:import']">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Upload />
                </el-icon>
              </template>
              导入
            </el-button>
            <!-- <el-upload
            ref="upload"
            action="/api/user/import"
            :headers="uploadHeaders"
            :on-error="onError"
            :on-success="onSuccess"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :limit="1"
            v-perm="['sys:user:import']"
          >
            <el-button type="primary">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Upload />
                </el-icon>
              </template>
              导入
            </el-button>
          </el-upload> -->
            <el-button
              type=""
              @click="handleExport"
              :loading="exportLoading"
              :disabled="exportLoading"
              v-perm="['sys:user:export']"
            >
              <template #icon>
                <el-icon class="el-input__icon">
                  <Download />
                </el-icon>
              </template>
              导出
            </el-button>
            <el-button type="primary" @click="sendMessage">
              <template #icon>
                <el-icon style="vertical-align: middle">
                  <ChatLineRound />
                </el-icon>
              </template>
              发送消息
            </el-button>
          </el-space>
        </template>
      </BasicTable>
    </el-card>
    <!-- 添加、编辑弹框 -->
    <editDialog
      v-if="editVisible"
      :userId="userId"
      v-model:visible="editVisible"
      @success="reloadTable('noRefresh')"
    />
    <!-- 上传文件 -->
    <userUpload v-if="importVisible" v-model:visible="importVisible" @success="reloadTable()" />
    <!-- 发送WebSocket消息 -->
    <sendMsgDialog v-if="sendMsgVisible" v-model:visible="sendMsgVisible" :receiveId="receiveId" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, nextTick, reactive, ref, defineAsyncComponent } from 'vue';
  import { ColProps } from 'element-plus';
  import { TableAction } from '@/components/Table';
  import { useForm } from '@/components/Form/index';
  import {
    getUserList,
    userDelete,
    userBatchDelete,
    userExport,
    resetPwd,
    getUserDocument,
  } from '@/api/system/user';
  import { message, confirm } from '@/utils/auth';
  import { columns } from './columns';
  import { schemas } from './querySchemas';
  import { downloadByData } from '@/utils/file/download';
  import printJS from 'print-js';

  /**
   * 定义参数
   */
  const userId = ref(0);
  const receiveId = ref('');
  const tableRef = ref();
  const editVisible = ref(false);
  const sendMsgVisible = ref(false);
  const importVisible = ref(false);
  const selectionData = ref([]);
  const exportLoading = ref(false);
  const editDialog = defineAsyncComponent(() => import('./edit.vue'));
  const sendMsgDialog = defineAsyncComponent(() => import('./sendMsg.vue'));
  const userUpload = defineAsyncComponent(() => import('./userUpload.vue'));

  /**
   * 定义查询参数
   */
  const formParams = reactive({
    realname: '',
    role: '',
    status: '',
  });

  /**
   * 定义操作栏
   */
  const actionColumn = reactive({
    width: 400,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction as any, {
        style: 'text',
        actions: [
          {
            label: '编辑',
            icon: 'Edit',
            type: 'warning',
            onClick: handleEdit.bind(null, record),
            auth: ['sys:user:update'],
          },
          {
            label: '删除',
            icon: 'Delete',
            type: 'danger',
            onClick: handleDelete.bind(null, record),
            auth: ['sys:user:delete'],
          },
          {
            label: '重置密码',
            icon: 'Lock',
            type: 'primary',
            onClick: handleResetPassWord.bind(null, record),
            auth: ['sys:user:resetPwd'],
          },
          {
            label: '打印',
            type: 'primary',
            icon: 'Printer',
            onClick: handlePrint.bind(null, record),
          },
        ],
        // dropDownActions: [
        //   {
        //     label: '启用',
        //     key: 'enabled',
        //   },
        //   {
        //     label: '禁用',
        //     key: 'disabled',
        //   },
        // ],
        // select: (key) => {
        //   ElMessage.info(`您点击了，${key} 按钮`);
        // },
      });
    },
  });

  /**
   * 加载数据列表
   */
  const loadDataTable = async (res) => {
    const result = await getUserList({ ...formParams, ...res });
    return result;
  };

  /**
   * 刷新数据列表
   * @param noRefresh 参数
   */
  function reloadTable(noRefresh = '') {
    tableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
  }

  /**
   * 执行添加
   */
  function addUser() {
    userId.value = 0;
    editVisible.value = true;
  }

  /**
   * 执行编辑
   */
  async function handleEdit(record: Recordable) {
    userId.value = record.row.id;
    await nextTick();
    editVisible.value = true;
  }

  /**
   * 执行重置密码
   * @param record 参数
   */
  async function handleResetPassWord(record: Recordable) {
    await confirm('确定重置密码？');
    await resetPwd({ userId: record.row.id });
    message('重置成功');
  }

  /**
   * 执行删除
   * @param record 参数
   */
  async function handleDelete(record: Recordable) {
    let ids = [];
    if (!record) {
      ids = selectionData.value.map(({ id }) => id);
    }
    await confirm('确定要删除？');
    record ? await userDelete(record.row.id) : await userBatchDelete(ids);
    message('删除成功');
    reloadTable();
  }

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

  /**
   * 执行提交表单
   * @param values 参数
   */
  function handleSubmit(values: Recordable) {
    handleReset();
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  /**
   * 执行重置
   */
  function handleReset() {
    for (const key in formParams) {
      formParams[key] = '';
    }
  }

  /**
   * 选项发生变化
   * @param value 参数
   */
  function onSelectionChange(value) {
    selectionData.value = value;
  }

  /**
   * 注册
   */
  const [register, {}] = useForm({
    labelWidth: 80,
    layout: 'horizontal',
    colProps: { span: 6 } as ColProps,
    submitOnReset: true,
    schemas,
  });

  /**
   * 执行导出
   */
  const handleExport = async () => {
    exportLoading.value = true;
    const data = await userExport();
    downloadByData(data, '用户信息.xlsx');
    exportLoading.value = false;
    message('导出成功');
  };

  /**
   * 发送消息
   * 此处写的是Socket消息发送案例，实际业务研发时根据实际需求自行接入模板消息
   */
  const sendMessage = async () => {
    if (selectionData.value.length == 0) {
      message('请选择数据', 'error');
      return;
    }
    let ids = [];
    ids = selectionData.value.map(({ id }) => id);
    receiveId.value = ids.join();
    sendMsgVisible.value = true;
  };
</script>

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