<template>
  <!-- 模板信息页面 -->
  <el-card class="template-info-container">
    <!-- 返回按钮 -->
    <div class="back-container">
      <el-button type="default" size="small" @click="handleBack" class="back-btn">
        返回
      </el-button>
    </div>

    <!-- 数据列表：基于TableModel组件实现 -->
    <div class="table-container">
      <TableModel
        :formLabel="formLabel"
        :showOperation="true"
        :showRightTools="false"
        ref="templateInfoTableRef"
        :columnsList="columnsList"
        :request-api="processedListTemplateInfo"
      >
        <template slot="tableTitle">
          <h3>数据列表</h3>
        </template>
        <template slot="tableActions">
          <el-button
            @click="handleAdd"
            v-hasPermi="['template:info:add']"
            class="add-btn"
          >
            <i class="el-icon-plus"></i> 新建模板
          </el-button>
        </template>

        <!-- 状态开关 -->
        <template slot="useState" slot-scope="{ data }">
          <el-switch
            v-model="data.useState"
            :active-value="'0'"
            :inactive-value="'1'"
            @change="handleStateChange(data)"
          />
        </template>

        <template slot="versionLink" slot-scope="{ data }">
          <span
            class="version-link"
            @click="handleVersionClick(data)"
            v-if="data.currentVersion"
          >
            {{ data.currentVersion }}
          </span>
          <span v-else>--</span>
        </template>

        <!-- 操作按钮：调整更多按钮样式，增加菜单项 -->
        <template slot="handle" slot-scope="{ data }">
          <el-button
            type="text"
            v-hasPermi="['template:info:detail']"
            class="action-btn"
            style="color: #1F72EA;"
            @click="handleDetail(data)"
          >
            解析规则
          </el-button>



          <!-- 更多下拉菜单：调整样式与解析规则按钮保持一致 -->
          <el-dropdown trigger="click" class="more-dropdown">
            <span class="el-dropdown-link action-btn" style="color: #1F72EA;">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
             </span>
            <el-dropdown-menu>
              <!-- 编辑 -->
              <el-dropdown-item
                v-hasPermi="['template:info:edit']"
                @click.native="handleUpdate(data)"
                class="dropdown-item"
              >
                编辑
              </el-dropdown-item>
              <!-- 复制 -->
              <el-dropdown-item
                v-hasPermi="['template:info:copy']"
                @click.native="handleCopy(data)"
                class="dropdown-item"
              >
                复制
              </el-dropdown-item>
              <!-- 发布 -->
              <el-dropdown-item
                v-hasPermi="['template:info:publish']"
                @click.native="handlePublish(data)"
                class="dropdown-item"
                :style="{ color: data.isPublished ? '#999' : '#1F72EA' }"
                :disabled="data.isPublished"
              >
                {{ data.publishStatusText }}
              </el-dropdown-item>
              <!-- 删除 -->
              <el-dropdown-item
                v-hasPermi="['template:info:del']"
                @click.native="handleDelete(data)"
                class="dropdown-item"
                style="color: #DB3E29;"
              >
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </TableModel>
    </div>
  </el-card>
</template>

<script>
import TableModel from '@/components/TableModel2'
import { columnsList, formLabel } from './config'
import { encryptWithSM4, decryptWithSM4 } from '@/utils/sm'
import {
  listTemplateInfo,
  delTemplateInfo,
  updateTemplateInfo,
  copyTemplateInfo,
  publishTemplate
} from '@/api/template/templateInfo/templateInfo'

export default {
  name: 'TemplateInfo',
  components: { TableModel },
  data() {
    return {
      formLabel,
      columnsList,
      industryTypeOptions: []
    }
  },

  created() {
    this.loadIndustryTypeDict()
    this.$nextTick(() => {
      if (this.$refs.templateInfoTableRef) {
        this.$refs.templateInfoTableRef.getTableList()
      }
    })
  },

  methods: {
    handleVersionClick(data) {
      this.$router.push({
        name: 'TemplateHistory', // 这是你将要在 router/index.js 中定义的路由名称
        query: {
          templateId: encryptWithSM4(data.templateId.toString()),
        },
        title: `模板历史详情`
      });
    },

    processedListTemplateInfo(params) {
      return listTemplateInfo(params).then(res => {
        if (res.code === 200 && res.rows && res.rows.length > 0) {
          // 处理发布状态显示文本
          res.rows.forEach(item => {
            if (item.publishedStatus === '1') {
              item.publishStatusText = '已发布'
              item.isPublished = true
            } else {
              item.publishStatusText = '发布'
              item.isPublished = false
            }
          })

          // 去重逻辑
          const groupMap = {}
          res.rows.forEach(item => {
            const key = item.templateId
            if (!groupMap[key]) {
              groupMap[key] = item
            }
          })
          res.rows = Object.values(groupMap)
        }
        return res
      })
    },

    // 返回上一页
    handleBack() {
      const obj = { path: '/template' }
      this.$tab.closeOpenPage(obj)
    },

    // 加载行业类型字典
    loadIndustryTypeDict() {
      this.getDicts('industry_type').then(response => {
        const industryTypeOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictLabel
        }))
        const industryTypeItem = this.formLabel.find(item => item.f_model === 'industryType')
        if (industryTypeItem) {
          industryTypeItem.f_selList = industryTypeOptions
          this.industryTypeOptions = industryTypeOptions
        }
      }).catch(error => {
        console.error('加载行业类型字典失败：', error)
      })
    },

    // 新增模板
    handleAdd() {
      this.$router.push({
        name: 'TemplateForm',
        query: {
          type: encryptWithSM4('add'),
          templateId: encryptWithSM4('')
        },
        title: '新建模板'
      })
    },

    // 编辑模板
    handleUpdate(data) {
      this.$router.push({
        name: 'TemplateForm',
        query: {
          type: encryptWithSM4('edit'),
          templateId: encryptWithSM4((data.templateId ?? '').toString())
        },
        title: '编辑模板'
      })
    },

    // 复制模板
    handleCopy(data) {
      this.$modal.confirm(`是否确认复制“${data.templateName}”模板？`)
        .then(() => {
          copyTemplateInfo({
            templateId: encryptWithSM4(data.templateId.toString())
          }).then(res => {
            if (res.code === 200) {
              this.$modal.msgSuccess('复制成功')
              this.handleQuery()
            } else {
              this.$modal.msgError(res.msg)
            }
          })
        })
    },

    // 发布模板
    handlePublish(data) {
      if (data.isPublished) {
        this.$modal.msgInfo('该模板已发布')
        return
      }

      this.$modal.confirm(`是否确认发布“${data.templateName}”模板？`)
        .then(() => {
          publishTemplate(data.templateId)
            .then(res => {
              if (res.code === 200) {
                this.$modal.msgSuccess('发布成功')
                this.handleQuery()
              } else {
                this.$modal.msgError(res.msg || '发布失败')
              }
            })
            .catch(error => {
              console.error('发布模板请求异常：', error)
              this.$modal.msgError('发布请求异常，请稍后重试')
            })
        })
    },

    // 查看模板详情
    handleDetail(data) {
      this.$router.push({
        name: 'AnalysisRule',
        query: {
          analysisLabelId: encryptWithSM4(data.analysisLabelId.toString()),
          templateId: encryptWithSM4(data.templateId.toString())
        },
        title: '解析规则'
      })
    },

    // 切换模板状态
    handleStateChange(row) {
      const originalState = row.useState
      updateTemplateInfo({
        templateId: row.templateId,
        useState: row.useState
      })
        .then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess('状态更新成功')
            this.handleQuery()
          } else {
            this.$modal.msgError(res.msg)
            row.useState = originalState
          }
        })
        .catch(() => {
          row.useState = originalState
        })
    },

    // 删除模板
    handleDelete(row) {
      this.$modal.confirm(`是否确认删除“${row.templateName}”模板？`)
        .then(() => {
          delTemplateInfo({
            templateId: row.templateId
          }).then(res => {
            if (res.code === 200) {
              this.$modal.msgSuccess('删除成功')
              this.handleQuery()
            } else {
              this.$modal.msgError(res.msg)
            }
          })
        })
    },

    // 刷新列表
    handleQuery() {
      if (this.$refs.templateInfoTableRef) {
        this.$refs.templateInfoTableRef.getTableList()
      }
    }
  }
}
</script>

<style scoped lang="scss">
/* 样式保持不变，新增下拉菜单样式 */
.back-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;

  .back-btn {
    width: 98px;
    height: 36px;
    background: #FFFFFF;
    box-shadow: 0px 4px 8px 0px rgba(76, 76, 76, 0.2);
    border-radius: 4px;
    border: none;
    color: #666;
    font-size: 14px;
    transition: all 0.3s ease;

    &:hover {
      background: #f5f5f5;
      color: #409EFF;
      box-shadow: 0px 6px 12px 0px rgba(76, 76, 76, 0.3);
    }
  }
}

.template-info-container {
  height: calc(100vh - 84px);
  overflow: hidden;
  background: linear-gradient(180deg, #F1F6FF 20%, #E5EFFF 100%);
}

.add-btn {
  width: 121px;
  height: 36px;
  background: #1F72EA;
  box-shadow: 0px 4px 8px 0px rgba(51, 135, 255, 0.5);
  border-radius: 4px;
  border: none;
  color: #fff;
  font-size: 14px;
  transition: all 0.3s;
  margin-right: 10px;

  &:hover {
    background: #4A8BFF;
    box-shadow: 0px 6px 12px 0px rgba(51, 135, 255, 0.6);
  }
}

.action-btn {
  margin-right: 8px;
  color: #1F72EA; /* 改为与解析规则相同的蓝色 */
  font-size: 14px;
  transition: all 0.3s ease;

  &:last-child {
    margin-right: 0;
  }

  /* 统一的hover效果 */
  &:hover {
    color: #4A8BFF; /* 稍浅的蓝色 */
    text-decoration: underline;
  }
}

/* 下拉菜单项样式优化 */
::v-deep .more-dropdown {
  .el-dropdown-menu {
    min-width: 140px; /* 固定下拉框宽度 */
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .dropdown-item {
    padding: 8px 16px;
    font-size: 14px;
    transition: all 0.2s;

    &:hover {
      background-color: #f5f7fa;
      color: #1F72EA;
    }
  }

  /* 确保下拉箭头颜色一致 */
  .el-dropdown-link {
    color: #1F72EA;

    &:hover {
      color: #4A8BFF;
      text-decoration: underline;
    }
  }
}

.el-dropdown-link {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
}

.version-link {
  color: #1F72EA;
  cursor: pointer;
  transition: color 0.3s ease;

  &:hover {
    color: #4A8BFF;
  }
}
</style>
