<template>
  <TableLayout
    :authorized="$hasPermissions([`cms:template:query`])"
    :fullscreen="fullscreen"
  >
    <!-- 搜索表单 -->
    <template #search-form>
      <SearchForm ref="searchForm" :model="searchForm" :collapse="false">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="searchForm.name" v-trim placeholder="请输入模板名称" @keypress.enter="search"/>
        </el-form-item>
        <template #buttons>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </template>
      </SearchForm>
    </template>
    <!-- 表格和分页 -->
    <template #table-wrap>
      <SearchTable
        v-loading="isWorking.search"
        :data="tableData.list"
        v-model:fullscreen="fullscreen"
        @selection-change="handleSelectionChange"
        @refresh="refresh"
      >
        <template
          v-if="$hasAnyPermissions([
            'cms:template:create',
            'cms:template:delete'
          ])"
          #toolbar
        >
          <el-button
            v-permissions="['cms:template:create']"
            type="primary"
            icon="Plus"
            @click="$refs.operaCmsTemplateWindow.open('新建模板')"
          >新建</el-button>
          <el-button
            v-permissions="['cms:template:delete']"
            type="danger"
            icon="Delete"
            @click="deleteByIdInBatch"
          >删除</el-button>
        </template>
        <el-table-column type="selection" fixed="left" width="55"/>
        <el-table-column prop="name" label="模板名称" min-width="100px"/>
        <el-table-column prop="path" label="模板文件路径" min-width="150px"/>
        <el-table-column prop="accessUri" label="访问路径" min-width="150px"/>
        <el-table-column prop="presetDataCodes" label="模板数据" min-width="150px">
          <template #default="{ row }">
            <TagCellValue :data="getDictLabels(row.presetDataCodes, 'TEMPLATE_DATA_LIST')"/>
          </template>
        </el-table-column>
        <el-table-column label="获取模板数据的参数" min-width="200px">
          <template #default="{ row }">
            <PopoverCellValue :content="getTemplateParameters(row)"/>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200px"/>
        <el-table-column prop="creatorRealName" label="创建人" min-width="100px"/>
        <el-table-column prop="createdAt" label="创建时间" min-width="185px"/>
        <el-table-column prop="updaterRealName" label="更新人" min-width="100px"/>
        <el-table-column prop="updatedAt" label="更新时间" min-width="185px"/>
        <template
          v-if="$hasAnyPermissions([
            'cms:template:update',
            'cms:template:delete'
          ])"
          #buttons="{ row }"
        >
          <el-button
            type="primary"
            icon="EditPen"
            v-permissions="['cms:template:update']"
            @click="$refs.operaCmsTemplateWindow.open(`编辑${row.name}`, row)"
            link
          >编辑</el-button>
          <el-button
            type="danger"
            icon="Delete"
            v-permissions="['cms:template:delete']"
            @click="deleteById(row)"
            link
          >删除</el-button>
        </template>
      </SearchTable>
      <pagination
        :pagination="tableData.pagination"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </template>
    <!-- 新建编辑窗口 -->
    <OperaCmsTemplateWindow
      ref="operaCmsTemplateWindow"
      @success="refresh"
    />
  </TableLayout>
</template>

<script>
import BaseTable from '@/components/base/BaseTable'
import OperaCmsTemplateWindow from '@/components/cms/template/OperaCmsTemplateWindow'

export default {
  extends: BaseTable,
  components: { OperaCmsTemplateWindow },
  data () {
    return {
      // 搜索
      searchForm: {
        name: ''
      }
    }
  },
  methods: {
    /**
     * 获取模板参数
     * @param row 模板行对象
     * @returns {string}
     */
    getTemplateParameters (row) {
      const dataCodes = row.presetDataCodes.split(',').filter(item => item.trim() !== '')
      const requestParam = {
        path: row.path,
        targetUid: '挂载该模板的模块数据唯一标识，如栏目的唯一标识',
        targetType: '挂载该模板的模块名称，如CATEGORY',
        parameters: {}
      }
      for (const dataCode of dataCodes) {
        const dataLabel = this.$d(`TEMPLATE_DATA_LIST.${dataCode}`)
        // 从字典中获取数据项的参数配置
        let dataConfig = this.$dc(`TEMPLATE_DATA_LIST.${dataCode}`)
        if (dataConfig != null && dataConfig.trim() !== '') {
          try {
            dataConfig = JSON.parse(dataConfig)
          } catch (e) {
            this.$tip.warning(`${dataLabel}参数配置有误！`)
            return
          }
          // 如果存在参数则添加
          if (dataConfig.parameters != null && dataConfig.parameters.length > 0) {
            for (const parameter of dataConfig.parameters) {
              // 必填参数，会在挂载模块指定模板时指定参数，无需前端传递，所以这里不再展示
              if (parameter.required) {
                continue
              }
              requestParam.parameters[parameter.name] = parameter.label
            }
          }
        }
      }
      return JSON.stringify(requestParam, null, 2)
    }
  },
  async created () {
    this.config({
      module: '模板',
      api: await import('@/api/cms/template')
    })
    this.search()
  }
}
</script>
