<template>
  <PageWrapper title="导出示例" content="可以选择导出格式">
    <el-card :bordered="false" class="mt-3 proCard">
      <BasicTable
        title="表格列表"
        titleTooltip="这是一个提示"
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="tableRef"
        :actionColumn="actionColumn"
        @checked-row-change="onCheckedRow"
      >
        <template #toolbar>
          <el-button type="primary" @click="openModal">导出数据</el-button>
        </template>
      </BasicTable>
    </el-card>

    <basicModal @register="modalRegister" ref="modalRef" @ok="okModal">
      <template #default>
        <BasicForm
          @register="register"
          @submit="handleSubmit"
          @reset="handleReset"
          class="basicForm"
        />
      </template>
    </basicModal>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, unref, ref, h } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { basicModal, useModal } from '@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { getTableList } from '@/api/table/list';
  import { columns } from '../../comp/table/basicColumns';
  import { jsonToSheetXlsx } from '@/components/Excel';
  import { ElMessageBox, ElMessage } from 'element-plus';

  const schemas: FormSchema[] = [
    {
      field: 'filename',
      component: 'Input',
      label: '文件名',
      labelMessage: '导出的文件以该名称命名',
      componentProps: {
        placeholder: '请输入文件名称',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: true, message: '请输入导出的文件名称', trigger: ['blur'] }],
    },
    {
      field: 'bookType',
      component: 'Select',
      label: '文件类型',
      componentProps: {
        placeholder: '请选择文件类型',
        options: [
          {
            label: 'xlsx',
            value: 'xlsx',
          },
          {
            label: 'html',
            value: 'html',
          },
          {
            label: 'csv',
            value: 'csv',
          },
          {
            label: 'txt',
            value: 'txt',
          },
        ],
        onChange: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: true, message: '请选择文件类型', trigger: ['change'] }],
    },
  ];

  const tableRef = ref();
  const modalRef = ref();
  const tableData = ref();

  const params = reactive({
    pageSize: 5,
    name: 'xiaoMa',
  });

  const [modalRegister, { openModal }] = useModal({
    title: '导出数据',
  });

  const [register, { submit }] = useForm({
    labelWidth: 120,
    layout: 'horizontal',
    // submitButtonText: '提交预约',
    showActionButtonGroup: false,
    schemas,
  });

  const actionColumn = reactive({
    width: 150,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: createActions(record),
      });
    },
  });

  async function okModal() {
    const formRes = await submit();
    if (formRes) {
      modalRef.value.closeModal();
      ElMessage.success('提交成功');
    } else {
      ElMessage.error('验证失败，请填写完整信息');
      modalRef.value.setSubLoading(false);
    }
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }

  function createActions(record) {
    return [
      {
        label: '删除',
        onClick: handleDelete.bind(null, record),
        // 根据业务控制是否显示 isShow 和 auth 是并且关系
        ifShow: () => {
          return true;
        },
        // 根据权限控制是否显示: 有权限，会显示，支持多个
        auth: ['basic_list'],
      },
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        ifShow: () => {
          return true;
        },
        auth: ['basic_list'],
      },
    ];
  }

  const loadDataTable = async (res) => {
    const result = await getTableList({ ...params, ...res });
    tableData.value = result.list;
    return result;
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function handleDelete(record) {
    console.log(record);
    ElMessageBox.confirm(`您想删除${record.name}`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        ElMessage.success('删除成功');
      })
      .catch(() => {});
  }

  function handleEdit(record) {
    console.log(record);
    ElMessage.success('您点击了编辑按钮');
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    // 默认Object.keys(data[0])作为header
    const { filename, bookType } = values;
    jsonToSheetXlsx({
      data: unref(tableData),
      filename: `${filename.split('.').shift()}.${bookType}`,
      write2excelOpts: {
        bookType,
      },
    });
    ElMessage.success(JSON.stringify(values));
  }
</script>

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