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

            <a-button
              type="danger"
              @click="handleDelete()"
              :disabled="!selectionData.length"
              v-perm="['sys:level:batchDelete']"
            >
              <template #icon>
                <DeleteOutlined />
              </template>
              删除
            </a-button>
            <a-upload
              ref="upload"
              action="/api/level/import"
              :headers="uploadHeaders"
              @change="handleImport"
              :before-upload="beforeUpload"
              :showUploadList="false"
              v-model:file-list="fileList"
              :maxCount="1"
              v-perm="['sys:level:import']"
            >
              <a-button type="primary">
                <template #icon>
                  <UploadOutlined />
                </template>
                导入
              </a-button>
            </a-upload>
            <a-button
              type="primary"
              @click="handleExport"
              :loading="exportLoading"
              :disabled="exportLoading"
              v-perm="['sys:level:export']"
            >
              <template #icon>
                <DownloadOutlined />
              </template>
              导出
            </a-button>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" @click="handleEdit(record.id)" v-perm="['sys:level:update']">
                <template #icon><EditOutlined /></template>
                编辑
              </a-button>
              <a-button
                type="primary"
                danger
                @click="handleDelete(record.id)"
                v-perm="['sys:level:delete']"
              >
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </BasicTable>
    </a-card>
    <editDialog
      v-if="editVisible"
      :levelId="levelId"
      v-model:visible="editVisible"
      @success="reloadTable('noRefresh')"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, nextTick, reactive, ref, defineAsyncComponent } from 'vue';
  import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    UploadOutlined,
    DownloadOutlined,
  } from '@ant-design/icons-vue';
  import { useForm } from '@/components/Form/index';
  import { getLevelList, levelDelete, levelBatchDelete, levelExport } from '@/api/system/level';
  import { columns } from './columns';
  import { schemas } from './querySchemas';
  import { Modal, message } from 'ant-design-vue';
  import { useUserStore } from '@/store/modules/user';
  import type { UploadChangeParam } from 'ant-design-vue';

  /**
   * 定义参数变量
   */
  const levelId = ref(0);
  const tableRef = ref();
  const editVisible = ref(false);
  const exportLoading = ref(false);
  const selectionData = ref([]);
  const fileList = ref([]);

  /**
   * 导入组件
   */
  const editDialog = defineAsyncComponent(() => import('./edit.vue'));

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

  /**
   * 定义上传头
   */
  const uploadHeaders = reactive({
    authorization: useUserStore().getToken,
  });

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

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

  /**
   * 执行编辑
   * @param id 参数
   */
  async function handleEdit(id) {
    levelId.value = id;
    await nextTick();
    editVisible.value = true;
  }

  /**
   * 执行删除
   * @param id 参数
   */
  async function handleDelete(id) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除？',
      onOk: async () => {
        id ? await levelDelete(id) : await levelBatchDelete(selectionData.value);
        message.success('删除成功');
        reloadTable();
      },
    });
  }

  /**
   * 执行导出
   */
  const handleExport = async () => {
    exportLoading.value = true;
    const data = await levelExport();
    window.open(data);
    exportLoading.value = false;
    message.success('导出成功');
  };

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

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

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

  /**
   * 注册
   */
  const [register, {}] = useForm({
    rowProps: { gutter: [16, 0] },
    colProps: {
      xs: 24,
      sm: 24,
      md: 12,
      lg: 8,
      xl: 6,
    },
    labelCol: { span: 6, offset: 0 },
    schemas,
  });

  /**
   * 执行添加
   */
  const handleAdd = async () => {
    levelId.value = 0;
    await nextTick();
    editVisible.value = true;
  };

  /**
   * 上传之前
   * @param file 文件
   */
  const beforeUpload = (file) => {
    const isLt2M = file.size / 1024 / 1024 < 200;
    if (!isLt2M) {
      message.warning('大小不能超过200MB!');
      return false;
    }
    if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
      message.warning('请上传.xlsx .xls');
      return false;
    }
    return true;
  };

  /**
   * 执行导入
   * @param param0 参数
   */
  const handleImport = ({ file }: UploadChangeParam) => {
    const status = file.status;
    if (status === 'done') {
      let data = file.response;
      if (data.code != 0) {
        message.error(data.msg || '导入失败');
      } else {
        message.success('导入成功');
        reloadTable();
      }
    } else if (status === 'error') {
      message.error('导入失败');
    }
  };
</script>
