<template>
  <FormPage
    ref="formPage"
    :action-column="actionColumn"
    :default-search-form="defaultSearchForm"
    :left-tools="leftTools"
    :paging="paging">
    <template #searchFormItem="{searchForm}">
      <ElFormItem label="模板名称">
        <ElInput
          v-model="searchForm.tplName"
          placeholder="模板名称"/>
      </ElFormItem>
      <ElFormItem label="前端/后端">
        <ElSelect
          v-model="searchForm.lang"
          placeholder="前端/后端"
        >
          <ElOption
            label="前端"
            value="ts"/>
          <ElOption
            label="后端"
            value="java"/>
        </ElSelect>
      </ElFormItem>
    </template>
    <template #columns>
      <ElTableColumn label="模板名称" prop="tplName"/>

      <ElTableColumn label="前端/后端" prop="lang">
        <template #default="scope">
          <span>{{ scope.row.lang === 'java' ? '后端' : '前端' }}</span>
        </template>
      </ElTableColumn>

      <ElTableColumn label="模板内容" prop="tpl">
        <template #default="{row}:{row:TplTypes.SearchTplResult}">
          <span>{{ (row.tpl != null && (row.tpl?.content?.length ?? 0) > 20) ? row.tpl!.content!.substring(0, 19) + '...' : row.tpl?.content }}</span>
        </template>
      </ElTableColumn>
    </template>
    <TplForm ref="tplForm" @edit-succ="research"/>
  </FormPage>
</template>
<script lang="ts" setup>
import TplApi from '@/pages/sys/gen/tpl/tpl-api.ts'
import TplForm from '@/pages/sys/gen/tpl/TplForm.vue'
import FormPage from '@/components/page/FormPage.vue'
import type {
  ActionColumnType,
  ToolType,
} from '@/components/page/a-page-type.ts'
import type { ComponentExposed } from 'vue-component-type-helpers'

const defaultSearchForm: TplTypes.SearchTplParam = {
  orders: 'lang,tpl_name',
  tpl: {},
}
const tplFormIns = useTemplateRef<InstanceType<typeof TplForm>>('tplForm')

const formPageIns = useTemplateRef<ComponentExposed<typeof FormPage>>('formPage')
const leftTools: ToolType[] = [
  {
    icon: 'Plus',
    label: '新建',
    action() {
      tplFormIns.value?.open()
    },
  },
]
const actionColumn = reactive<ActionColumnType<TplTypes.SearchTplResult>>({
  tableActions: [
    {
      tooltip: '编辑',
      icon: 'Edit',
      action({row}) {
        tplFormIns.value?.open(row)
      },
    },
    {
      icon: 'Delete',
      loading: false,
      type: 'danger',
      tooltip: '删除',
      confirm: {
        title: '是否删除当前数据',
      },
      action({row}) {
        return TplApi.del([ row.id! ])
          .then(() => {
            ElMessage.success('删除成功')
            return true
          })
      },
    },
  ],
})

function research() {
  formPageIns.value?.doSearch()
}

function paging(param: TplTypes.SearchTplParam) {
  return TplApi.paging(param)
}
</script>
