<template>
  <!-- 搜索 -->
  <a-card class="general-card table-search-card">
    <query-header :model="formModel"
                  label-align="left"
                  @submit="fetchTableData"
                  @reset="fetchTableData"
                  @keyup.enter="() => fetchTableData()">
      #foreach($field in ${table.fields})
      <!-- $field.comment -->
      <a-form-item field="${field.propertyName}" label="${field.comment}">
        #if(${dictMap.containsKey(${field.propertyName})})
        <a-select v-model="formModel.${field.propertyName}"
                  :options="toOptions($dictMap.get(${field.propertyName}).keyField)"
                  placeholder="请选择${field.comment}"
                  allow-clear />
        #else
        #if("$field.propertyType" == "Integer" || "$field.propertyType" == "Long")
        <a-input-number v-model="formModel.${field.propertyName}"
                        placeholder="请输入${field.comment}"
                        allow-clear
                        hide-button />
        #elseif("$field.propertyType" == "Date")
        <a-date-picker v-model="formModel.${field.propertyName}"
                       style="width: 100%"
                       placeholder="请选择${field.comment}"
                       show-time
                       allow-clear />
        #else
        <a-input v-model="formModel.${field.propertyName}"
                 placeholder="请输入${field.comment}"
                 allow-clear />
        #end
        #end
      </a-form-item>
      #end
    </query-header>
  </a-card>
  <!-- 表格 -->
  <a-card class="general-card table-card">
    <template #title>
      <!-- 左侧操作 -->
      <div class="table-left-bar-handle">
        <!-- 标题 -->
        <div class="table-title">
          ${table.comment}列表
        </div>
      </div>
      <!-- 右侧操作 -->
      <div class="table-right-bar-handle">
        <a-space>
          <!-- 新增 -->
          <a-button v-permission="['${package.ModuleName}:${typeHyphen}:create']"
                    type="primary"
                    @click="emits('openAdd')">
            新增
            <template #icon>
              <icon-plus />
            </template>
          </a-button>
          #if($vue.enableRowSelection)
          <!-- 删除 -->
          <a-popconfirm :content="`确认删除选中的 ${selectedKeys.length} 条记录吗?`"
                        position="br"
                        type="warning"
                        @ok="deleteSelectRows">
            <a-button v-permission="['${package.ModuleName}:${typeHyphen}:delete']"
                      type="secondary"
                      status="danger"
                      :disabled="selectedKeys.length === 0">
              删除
              <template #icon>
                <icon-delete />
              </template>
            </a-button>
          </a-popconfirm>
          #end
        </a-space>
      </div>
    </template>
    <!-- table -->
    #if($vue.enableRowSelection)
    <a-table v-model:selected-keys="selectedKeys"
             row-key="id"
    #else
    <a-table row-key="id"
    #end
             ref="tableRef"
             :loading="loading"
             :columns="columns"
             #if($vue.enableRowSelection)
             :row-selection="rowSelection"
             #end
             :data="tableRenderData"
             :pagination="pagination"
             :bordered="false"
             @page-change="(page: number) => fetchTableData(page, pagination.pageSize)"
             @page-size-change="(size: number) => fetchTableData(1, size)">
      #foreach($field in ${table.fields})
      #if(${dictMap.containsKey(${field.propertyName})})
      <!-- $field.comment -->
      <template #${field.propertyName}="{ record }">
        {{ getDictValue($dictMap.get(${field.propertyName}).keyField, record.${field.propertyName}) }}
      </template>
      #end
      #end
      <!-- 操作 -->
      <template #handle="{ record }">
        <div class="table-handle-wrapper">
          <!-- 修改 -->
          <a-button v-permission="['${package.ModuleName}:${typeHyphen}:update']"
                    type="text"
                    size="mini"
                    @click="emits('openUpdate', record)">
            修改
          </a-button>
          <!-- 删除 -->
          <a-popconfirm content="确认删除这条记录吗?"
                        position="left"
                        type="warning"
                        @ok="deleteRow(record)">
            <a-button v-permission="['${package.ModuleName}:${typeHyphen}:delete']"
                      type="text"
                      size="mini"
                      status="danger">
              删除
            </a-button>
          </a-popconfirm>
        </div>
      </template>
    </a-table>
  </a-card>
</template>

<script lang="ts">
  export default {
    name: '${vue.featureEntityFirstLower}Table'
  };
</script>

<script lang="ts" setup>
  import type { ${vue.featureEntity}QueryRequest, ${vue.featureEntity}QueryResponse } from '@/api/${vue.module}/${vue.feature}';
  import { reactive, ref, onMounted } from 'vue';
  import { batchDelete${vue.featureEntity}, delete${vue.featureEntity}, get${vue.featureEntity}Page } from '@/api/${vue.module}/${vue.feature}';
  import { Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import columns from '../types/table.columns';
  #if($dictMap.entrySet().size() > 0)
  import { #foreach($entry in ${dictMap.entrySet()})${entry.value.keyField}#if($foreach.hasNext), #end#end } from '../types/const';
  #else
  import {} from '../types/const';
  #end
  #if($vue.enableRowSelection)
  import { useTablePagination, useRowSelection } from '@/hooks/table';
  #else
  import { useTablePagination } from '@/hooks/table';
  #end
  #if($dictMap.entrySet().size() > 0)
  import { useDictStore } from '@/store';
  #end

  const emits = defineEmits(['openAdd', 'openUpdate']);

  const pagination = useTablePagination();
  #if($vue.enableRowSelection)
  const rowSelection = useRowSelection();
  #end
  const { loading, setLoading } = useLoading();
  #if($dictMap.entrySet().size() > 0)
  const { toOptions, getDictValue } = useDictStore();
  #end

  #if($vue.enableRowSelection)
  const selectedKeys = ref<number[]>([]);
  #end
  const tableRenderData = ref<${vue.featureEntity}QueryResponse[]>([]);
  const formModel = reactive<${vue.featureEntity}QueryRequest>({
    #foreach($field in ${table.fields})
    ${field.propertyName}: undefined,
    #end
  });

  #if($vue.enableRowSelection)
  // 删除选中行
  const deleteSelectRows = async () => {
    try {
      setLoading(true);
      // 调用删除接口
      await batchDelete${vue.featureEntity}(selectedKeys.value);
      Message.success(`成功删除 ${selectedKeys.value.length} 条数据`);
      selectedKeys.value = [];
      // 重新加载数据
      fetchTableData();
    } catch (e) {
    } finally {
      setLoading(false);
    }
  };

  #end
  // 删除当前行
  const deleteRow = async ({ id }: {
    id: number
  }) => {
    try {
      setLoading(true);
      // 调用删除接口
      await delete${vue.featureEntity}(id);
      Message.success('删除成功');
      // 重新加载数据
      fetchTableData();
    } catch (e) {
    } finally {
      setLoading(false);
    }
  };

  // 添加后回调
  const addedCallback = () => {
    fetchTableData();
  };

  // 更新后回调
  const updatedCallback = () => {
    fetchTableData();
  };

  defineExpose({
    addedCallback, updatedCallback
  });

  // 加载数据
  const doFetchTableData = async (request: ${vue.featureEntity}QueryRequest) => {
    try {
      setLoading(true);
      const { data } = await get${vue.featureEntity}Page(request);
      tableRenderData.value = data.rows;
      pagination.total = data.total;
      pagination.current = request.page;
      pagination.pageSize = request.limit;
      #if($vue.enableRowSelection)
      selectedKeys.value = [];
      #end
    } catch (e) {
    } finally {
      setLoading(false);
    }
  };

  // 切换页码
  const fetchTableData = (page = 1, limit = pagination.pageSize, form = formModel) => {
    doFetchTableData({ page, limit, ...form });
  };

  onMounted(() => {
    fetchTableData();
  });

</script>

<style lang="less" scoped>

</style>
