<script lang="ts" setup name="{{ properCase componentName }}">
import { ElMessage, ElMessageBox } from 'element-plus'
import FormMode from './components/FormMode/Api.vue'
import eventBus from '@/utils/eventBus'
import apiRequest from '@/apiRequest'
import useSettingsStore from '@/log/modules/settings'

const router = useRouter()
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } = usePagination()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()

const data = ref({
  loading: false,
  // 表格是否自适应高度
  tableAutoHeight: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: 'router',
  // 详情
  formModeProps: {
    visible: false,
    id: '',
  },
  // 搜索
  search: {
    title: '',
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: [],
  },
  // 列表数据
  dataList: [],
})

onMounted(() => {
  getDataList()
  if (data.value.formMode === 'router') {
    eventBus.on('get-data-list', () => {
      getDataList()
    })
  }
})

onBeforeUnmount(() => {
  if (data.value.formMode === 'router') {
    eventBus.off('get-data-list')
  }
})

function getDataList() {
  data.value.loading = true
  const params = getParams()
  data.value.search.title && (params.title = data.value.search.title)
  api.get('{{#if relativePath}}{{ relativePath }}/{{/if}}{{ snakeCase moduleName }}/list', {
    baseURL: '/mock/',
    params,
  }).then((res: any) => {
    data.value.loading = false
    data.value.dataList = res.data.list
    pagination.value.total = res.data.total
  })
}

// 每页数量切换
function sizeChange(size: number) {
  onSizeChange(size).then(() => getDataList())
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList())
}

// 字段排序
function sortChange({ prop, order }: { prop: string; order: string }) {
  onSortChange(prop, order).then(() => getDataList())
}

function onCreate() {
  if (data.value.formMode === 'router') {
    if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
      tabbar.open({
        name: 'routerName',
      })
    }
    else {
      router.push({
        name: 'routerName',
      })
    }
  }
  else {
    data.value.formModeProps.id = ''
    data.value.formModeProps.visible = true
  }
}

function onEdit(row: any) {
  if (data.value.formMode === 'router') {
    if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
      tabbar.open({
        name: 'routerName',
        params: {
          id: row.id,
        },
      })
    }
    else {
      router.push({
        name: 'routerName',
        params: {
          id: row.id,
        },
      })
    }
  }
  else {
    data.value.formModeProps.id = row.id
    data.value.formModeProps.visible = true
  }
}

function onDel(row: any) {
  ElMessageBox.confirm(`确认删除「${row.title}」吗？`, '确认信息').then(() => {
    api.post('{{#if relativePath}}{{ relativePath }}/{{/if}}{{ snakeCase moduleName }}/delete', {
      id: row.id,
    }, {
      baseURL: '/mock/',
    }).then(() => {
      getDataList()
      ElMessage.success({
        message: '模拟删除成功',
        center: true,
      })
    })
  }).catch(() => {})
}
</script>

<template>
  <div :class="{ 'absolute-container': data.tableAutoHeight }">
    <page-header title="{{ cname }}管理" />
    <page-main>
      <el-space wrap>
        <el-button type="primary" size="default" @click="onCreate">
          <template #icon>
            <el-icon>
              <svg-icon name="ep:plus" />
            </el-icon>
          </template>
          新增{{ cname }}
        </el-button>
        <el-button v-if="data.batch.enable" size="default" :disabled="!data.batch.selectionDataList.length">
          单个批量操作按钮
        </el-button>
        <el-button-group v-if="data.batch.enable">
          <el-button size="default" :disabled="!data.batch.selectionDataList.length">
            批量操作按钮组1
          </el-button>
          <el-button size="default" :disabled="!data.batch.selectionDataList.length">
            批量操作按钮组2
          </el-button>
        </el-button-group>
      </el-space>
      <search-bar>
        <el-form :model="data.search" size="default" label-width="100px" label-suffix="：">
          <el-row>
            <el-col :span="12">
              <el-form-item label="标题">
                <el-input v-model="data.search.title" placeholder="请输入标题，支持模糊查询" clearable @keydown.enter="currentChange()" @clear="currentChange()" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="currentChange()">
              <template #icon>
                <el-icon>
                  <svg-icon name="i-ep:search" />
                </el-icon>
              </template>
              筛选
            </el-button>
          </el-form-item>
        </el-form>
      </search-bar>
      <el-table v-loading="data.loading" class="list-table" :data="data.dataList" border stripe highlight-current-row height="100%" @sort-change="sortChange" @selection-change="data.batch.selectionDataList = $event">
        <el-table-column v-if="data.batch.enable" type="selection" align="center" fixed />
        <el-table-column prop="title" label="标题" />
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" plain @click="onEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" plain @click="onDel(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="pagination.page" :total="pagination.total" :page-size="pagination.size" :page-sizes="pagination.sizes" :layout="pagination.layout" :hide-on-single-page="false" class="pagination" background @size-change="sizeChange" @current-change="currentChange" />
    </page-main>
    <FormMode v-if="['dialog', 'drawer'].includes(data.formMode)" :id="data.formModeProps.id" v-model="data.formModeProps.visible" :mode="data.formMode" @success="getDataList" />
  </div>
</template>

<style lang="scss" scoped>
.absolute-container {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    margin-bottom: 0;
  }

  .page-main {
    // 让 page-main 的高度自适应
    flex: 1;
    overflow: auto;
    display: flex;
    flex-direction: column;

    .search-container {
      margin-bottom: 0;
    }
  }
}
</style>
