<template>
  <PageWrapper>
    <el-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" />
    </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"
      >
        <template #tableTitle>
          <el-space>
            <el-button type="primary" @click="handleAdd" v-perm="['sys:level:add']">
              <template #icon>
                <el-icon class="el-input__icon">
                  <PlusOutlined />
                </el-icon>
              </template>
              添加职级
            </el-button>
            <el-button
              type="danger"
              @click="handleDelete()"
              :disabled="!selectionData.length"
              v-perm="['sys:level:batchDelete']"
            >
              <template #icon>
                <el-icon class="el-input__icon">
                  <Delete />
                </el-icon>
              </template>
              删除
            </el-button>
            <el-upload
              ref="upload"
              action="/api/level/import"
              :headers="uploadHeaders"
              :on-error="onError"
              :on-success="onSuccess"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :limit="1"
              v-perm="['sys:level:import']"
            >
              <el-button type="">
                <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:level:export']"
            >
              <template #icon>
                <el-icon class="el-input__icon">
                  <Download />
                </el-icon>
              </template>
              导出
            </el-button>
          </el-space>
        </template>
      </BasicTable>
    </el-card>

    <editDialog
      v-if="editVisible"
      :levelId="levelId"
      v-model:visible="editVisible"
      @success="reloadTable('noRefresh')"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, h, nextTick, defineAsyncComponent } from 'vue';
  import { ColProps, UploadInstance } from 'element-plus';
  import { schemas } from './querySchemas';
  import { useForm } from '@/components/Form/index';
  import { TableAction } from '@/components/Table';
  import { getLevelList, levelDelete, levelBatchDelete, levelExport } from '@/api/system/level';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { message, confirm, loading, closeLoading } from '@/utils/auth';
  import { useUserStore } from '@/store/modules/user';

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

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

  /**
   * 定义查询参数
   */
  const formParams = reactive({
    // 职级名称
    name: '',
    // 职级状态
    status: '',
  });

  /**
   * 上传请求头设置
   */
  const uploadHeaders = reactive({
    authorization: useUserStore().getToken,
  });

  /**
   * 定义操作栏
   */
  const actionColumn = reactive({
    width: 200,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            icon: 'Edit',
            type: 'warning',
            onClick: handleEdit.bind(null, record),
            auth: ['sys:level:update'],
          },
          {
            label: '删除',
            icon: 'Delete',
            type: 'danger',
            onClick: handleDelete.bind(null, record),
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['sys:level:delete'],
          },
        ],
      });
    },
  });

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

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

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

  /**
   * 执行提交表单
   * @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] = '';
    }
  }

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

  /**
   * 执行编辑
   * @param record 参数
   */
  const handleEdit = async (record: Recordable) => {
    levelId.value = record.row.id;
    await nextTick();
    editVisible.value = true;
  };

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

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

  /**
   * 上传之前
   * @param file 文件
   */
  const beforeUpload = (file: UploadFile) => {
    const isLt2M = file.size / 1024 / 1024 < 200;
    if (!isLt2M) {
      message('大小不能超过200MB!', 'error');
      return false;
    }
    if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
      message('请上传.xlsx .xls', 'error');
      return false;
    }
    loading('上传中');
    return true;
  };
  /**
   * 上传成功处理
   * @param file 文件
   */
  const onSuccess = (file: UploadFile) => {
    upload.value!.clearFiles();
    closeLoading();
    if (file.code == 0) {
      message('导入成功,' + file.msg);
      reloadTable();
    } else {
      message(file.msg ? file.msg : '导入失败', 'error');
    }
  };
  /**
   * 上传失败处理
   */
  const onError = () => {
    upload.value!.clearFiles();
    closeLoading();
    message('导入失败', 'error');
  };

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

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