<template>
  <div class="tag-binding">
    <el-card>
      <div slot="header" class="card-header">
        <span>标签-模板绑定管理</span>
        <el-button type="primary" @click="handleAdd">
          <i class="el-icon-plus"></i>新增绑定
        </el-button>
      </div>

      <el-alert
        title="标签绑定说明"
        description="通过配置用户标签与工作流模板的绑定关系，系统可以根据用户标签自动匹配最合适的工作流模板进行跟进。"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 20px"
      />

      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="标签编码">
          <el-input v-model="searchForm.tagCode" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="模板">
          <el-select v-model="searchForm.templateId" placeholder="请选择" clearable style="width: 200px">
            <el-option v-for="t in templateOptions" :key="t.id" :label="t.templateName" :value="t.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <i class="el-icon-search"></i>查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="tagCode" label="标签编码" width="150" />
        <el-table-column prop="tagName" label="标签名称" width="150" />
        <el-table-column prop="templateName" label="绑定模板" min-width="200" />
        <el-table-column prop="priority" label="优先级" width="100" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="row.priority >= 50 ? 'danger' : row.priority >= 30 ? 'warning' : 'info'">
              {{ row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="matchCondition" label="匹配条件" min-width="200" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span v-if="row.matchCondition">{{ formatCondition(row.matchCondition) }}</span>
            <span v-else style="color: #909399">无特殊条件</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="{ row }">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" size="mini" @click="handleTestMatch(row)">测试匹配</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="标签编码" prop="tagCode">
          <el-input v-model="form.tagCode" placeholder="请输入标签编码，如：VIP_USER" />
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="绑定模板" prop="templateId">
          <el-select v-model="form.templateId" placeholder="请选择工作流模板" style="width: 100%">
            <el-option v-for="t in templateOptions" :key="t.id" :label="t.templateName" :value="t.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-slider v-model="form.priority" :max="100" show-input />
        </el-form-item>
        <el-form-item label="匹配条件">
          <el-input v-model="form.matchCondition" type="textarea" :rows="3" placeholder="请输入JSON格式的匹配条件" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 测试匹配对话框 -->
    <el-dialog :visible.sync="testDialogVisible" title="测试标签匹配" width="500px">
      <el-form :model="testForm" label-width="100px">
        <el-form-item label="测试标签">
          <el-input v-model="testForm.tags" type="textarea" :rows="4" placeholder="请输入标签编码，多个标签用逗号分隔" />
        </el-form-item>
      </el-form>
      <div v-if="testResult" style="margin-top: 20px">
        <el-alert :title="testResult.matched ? '匹配成功' : '未匹配'" :type="testResult.matched ? 'success' : 'warning'" :closable="false">
          <div v-if="testResult.matched">
            <p>模板：{{ testResult.templateName }}</p>
            <p>优先级：{{ testResult.priority }}</p>
          </div>
          <div v-else>
            <p>{{ testResult.message }}</p>
          </div>
        </el-alert>
      </div>
      <div slot="footer">
        <el-button @click="testDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleTestMatchSubmit">测试</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { tagBindingApi } from '@/api/company/tagBinding'
import { listWorkflowTemplateByStatus } from '@/api/company/workflowLobster'

export default {
  name: 'TagBinding',
  data() {
    return {
      loading: false,
      tableData: [],
      searchForm: {
        tagCode: '',
        templateId: null
      },
      templateOptions: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        tagCode: '',
        tagName: '',
        templateId: null,
        priority: 0,
        matchCondition: '',
        templateName: ''

      },
      rules: {
        tagCode: [{ required: true, message: '请输入标签编码', trigger: 'blur' }],
        tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
        templateId: [{ required: true, message: '请选择模板', trigger: 'change' }]
      },
      testDialogVisible: false,
      testForm: {
        id: null,
        tags: ''
      },
      testResult: null
    }
  },
  created() {
    this.getList()
    this.loadTemplateOptions()
  },
  methods: {
    async getList() {
      this.loading = true
      try {
        const res = await tagBindingApi.getList(this.searchForm)
        this.tableData = res.data || []
      } catch (error) {
        this.$message.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },
    async loadTemplateOptions() {
      try {
        const res = await listWorkflowTemplateByStatus({ status: 1 })
        this.templateOptions = res.data || []
      } catch (error) {
        this.templateOptions = []
        this.$message.error('获取模板列表失败')
      }
    },
    handleSearch() {
      this.getList()
    },
    handleReset() {
      this.searchForm = {
        tagCode: '',
        templateId: null
      }
      this.handleSearch()
    },
    handleAdd() {
      this.dialogTitle = '新增绑定'
      this.form = {
        id: null,
        tagCode: '',
        tagName: '',
        templateId: null,
        templateName: '',
        priority: 0,
        matchCondition: ''
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.resetFields()
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑绑定'
      this.form = {
        id: row.id,
        tagCode: row.tagCode,
        tagName: row.tagName,
        templateId: row.templateId,
        templateName: row.templateName || '',
        priority: row.priority,
        matchCondition: row.matchCondition
      }
      this.dialogVisible = true
    },
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        const selectedTemplate = this.templateOptions.find(item => item.id === this.form.templateId)
        this.form.templateName = selectedTemplate ? selectedTemplate.templateName : ''
        if (this.form.id) {
          await tagBindingApi.update(this.form.id, this.form)
          this.$message.success('修改成功')
        } else {
          await tagBindingApi.create(this.form)
          this.$message.success('新增成功')
        }
        this.dialogVisible = false
        this.getList()
      } catch (error) {
        if (error !== false) {
          this.$message.error('操作失败')
        }
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该绑定关系吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await tagBindingApi.delete(row.id)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    async handleStatusChange(row) {
      try {
        await tagBindingApi.update(row.id, { status: row.status })
        this.$message.success('状态更新成功')
      } catch (error) {
        this.$message.error('状态更新失败')
        this.getList()
      }
    },
    handleTestMatch(row) {
      this.testForm = {
        id: row.id,
        tags: row.tagCode
      }
      this.testResult = null
      this.testDialogVisible = true
    },
    async handleTestMatchSubmit() {
      try {
        const tags = this.testForm.tags.split(',').map(t => t.trim()).filter(t => t)
        const res = await tagBindingApi.testMatch(this.testForm.id, { tags })
        this.testResult = res.data
      } catch (error) {
        this.$message.error('测试失败')
      }
    },
    formatCondition(condition) {
      try {
        const obj = JSON.parse(condition)
        return Object.entries(obj).map(([k, v]) => `${k}: ${v}`).join(', ')
      } catch {
        return condition
      }
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-form {
  margin-bottom: 20px;
}
</style>
