<template>
  <div>
    <BasicTable @register="registerTable" @resizeColumn="resizeColumn">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'disable'">
          <Tag :color="record.disable ? 'error' : 'success'">
            {{ commonDict(record.disable, 1) }}
          </Tag>
        </template>
        <template v-if="column.key === 'sysInner'">
          <Tag :color="record.sysInner ? 'success' : 'error'">
            {{ commonDict(record.sysInner, 1) }}
          </Tag>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'icon-edit|iconfont',
                tooltip: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'icon-delete|iconfont',
                tooltip: '删除',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
      <template #search="{ onSearch }">
        <div class="search">
          <a-input-search
            class="table-search-item"
            v-model:value="tableSearch.value1"
            placeholder="请输入姓名"
            @search="onSearch"
          />
          <a-select
            ref="select"
            placeholder="选择病区"
            v-model:value="tableSearch.value2"
            style="width: 120px"
            @change="onSearch"
            class="table-search-item"
          >
            <a-select-option value="1"> <span class="mr-1">病区</span>全部 </a-select-option>
            <a-select-option value="jack"> <span class="mr-1">病区</span>Jack </a-select-option>
            <a-select-option value="lucy"><span class="mr-1">病区</span>Lucy</a-select-option>
            <a-select-option value="Yiminghe"
              ><span class="mr-1">病区</span>yiminghe</a-select-option
            >
          </a-select>
          <a-select
            ref="select"
            placeholder="选择设备"
            v-model:value="tableSearch.value3"
            style="width: 120px"
            @change="onSearch"
            class="table-search-item"
          >
            <a-select-option value="1"> <span class="mr-1">设备</span>全部 </a-select-option>
            <a-select-option value="jack"> <span class="mr-1">设备</span>111 </a-select-option>
            <a-select-option value="lucy"><span class="mr-1">设备</span>222</a-select-option>
            <a-select-option value="Yiminghe"><span class="mr-1">设备</span>333</a-select-option>
          </a-select>
        </div>
      </template>
      <template #toolbar>
        <a-button
          v-auth="['system:sysConfig:add']"
          preIcon="icon-plus|iconfont"
          type="primary"
          @click="handleCreate"
          >新增
        </a-button>
        <!-- <a-button
          v-auth="['system:sysConfig:export']"
          color="warning"
          preIcon="ant-design:download-outlined"
          @click="handleExport"
          >导出
        </a-button> -->
        <a-button
          v-auth="['system:sysConfig:refresh']"
          color="success"
          preIcon="icon-redo|iconfont"
          @click="handleRefresh"
          >刷新缓存
        </a-button>
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { onBeforeMount, reactive } from 'vue';
  import { Tag } from 'ant-design-vue';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import FormModal from './FormModal.vue';
  import { columns, searchBasicFormSchema, searchFormSchema } from './data';

  // import { exportList, fetchList, refresh, removeObj } from '/@/api/modules/system/sysConfigApi';
  import { sysConfigQueryList, sysConfigRemove } from '/@/api/sys/sysConfigApi';
  // import { downloadFile, listDictModel } from '/@/api/common';
  // import { listDictModel } from '/@/api/common';
  import { commonDict } from '/@/utils';
  // import { templateRef } from '@vueuse/core';
  import { useDebounceFn } from '@vueuse/shared';

  defineOptions({
    name: 'sysConfig',
  });

  // const sysStatusOptions = ref([]);
  onBeforeMount(async () => {
    // sysStatusOptions.value = await listDictModel({ dictCode: 'sys_status' });
  });
  const tableSearch = reactive({
    value1: '',
    value2: '1',
    value3: '1',
  });
  const { createMessage, createConfirm } = useMessage();
  const [registerTable, { reload, getCacheColumns, setColumns }] = useTable({
    // 存储需要设置 id 和 storage
    id: 'sys_config',
    storage: true,
    title: '参数列表',
    api: sysConfigQueryList,
    rowKey: 'id',
    columns,
    formConfig: {
      formId: 'sys_config',
      labelWidth: 100,
      schemas: searchFormSchema,
      actionColOptions: {
        xs: 24,
        sm: 12,
        md: 12,
        lg: 8,
      },
      autoSubmitOnEnter: true,
      baseColProps: { xs: 24, sm: 12, md: 12, lg: 8 },
      resetButtonOptions: {
        preIcon: 'icon-delete|iconfont',
      },
      submitButtonOptions: {
        preIcon: 'icon-search|iconfont',
      },
    },
    basicSearch: {
      schemas: searchBasicFormSchema,
      fields: tableSearch,
    },
    showIndexColumn: true,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    actionColumn: {
      auth: ['system:sysConfig:edit', 'system:sysConfig:remove'],
      width: 80,
      title: '操作',
      dataIndex: 'action',
    },
  });
  const [registerModal, { openModal }] = useModal();

  // 新增按钮事件
  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  // 编辑按钮事件
  function handleEdit(record: Recordable) {
    console.log(record);
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    console.log(record);
    await sysConfigRemove([record.id]);
    createMessage.success('删除成功！');
    await reload();
  }

  // 导出按钮事件
  // async function handleExport() {
  //   createConfirm({
  //     iconType: 'warning',
  //     title: '提示',
  //     content: '确认导出？',
  //     onOk: async () => {
  //       const params = getForm().getFieldsValue();
  //       const filepath = await exportList(params);
  //       downloadFile(filepath);
  //     },
  //   });
  // }

  // 刷新缓存按钮事件
  async function handleRefresh() {
    createConfirm({
      iconType: 'warning',
      title: '提示',
      content: '确认刷新所有参数缓存？',
      onOk: async () => {
        await sysConfigQueryList({});
        createMessage.success('刷新成功！');
      },
    });
  }

  // 弹窗回调事件
  async function handleSuccess({ isUpdate, values }) {
    console.log(isUpdate);
    console.log(values);
    await reload();
  }

  const debounceFn = useDebounceFn(async (w, col) => {
    const cacheColumns = await getCacheColumns();
    const columns = cacheColumns.map(ele => {
      if (ele.dataIndex == col.dataIndex) {
        ele.width = w;
      }
      return ele;
    }) as any;
    setColumns(columns);
  }, 1000 * 3);

  // 动态设置宽度
  async function resizeColumn(w, col) {
    col.width = w;
    debounceFn(w, col);
  }
</script>

<style lang="less" scoped>
  .table-search {
    display: flex;
    justify-content: space-between;
    align-items: center;

    &-item {
      margin-right: 10px;
      max-width: 180px;
    }
  }
</style>
