<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :title="title"
    :footer="null"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
  >
    <ele-pro-table
      ref="tableRef"
      row-key="id"
      :datasource="datasource"
      :columns="columns"
      :pagination="false"
    >
      <template #toolbar>
        <a-space>
          <a-input-search
            allow-clear
            v-model:value="where.keywords"
            placeholder="请输入门店关键词"
            style="width: 240px"
            @search="reload"
            @pressEnter="reload"
          />
        </a-space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="done(record)">选择</a-button>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import type {
    ColumnItem,
    DatasourceFunction
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { EleProTable } from 'ele-admin-pro';
  import useSearch from '@/utils/use-search';
  import { pageShopStore } from '@/api/shop/shopStore';
  import type { ShopStoreParam } from '@/api/shop/shopStore/model';
  import type { ShopStore } from '@/api/shop/shopStore/model';

  defineProps<{
    visible: boolean;
    title?: string;
  }>();

  const emit = defineEmits<{
    (e: 'done', data: ShopStore): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const { where } = useSearch<ShopStoreParam>({
    id: undefined,
    keywords: ''
  });

  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  const columns = ref<ColumnItem[]>([
    { title: 'ID', dataIndex: 'id', width: 90 },
    { title: '门店名称', dataIndex: 'name' },
    { title: '电话', dataIndex: 'phone', width: 160 },
    { title: '地址', dataIndex: 'address' },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center',
      hideInSetting: true
    }
  ]);

  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    return pageShopStore({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  const reload = () => {
    tableRef?.value?.reload({ page: 1, where: where as ShopStoreParam });
  };

  const done = (record: ShopStore) => {
    updateVisible(false);
    emit('done', record);
  };
</script>

