<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="标签名称" prop="qwTagName">
        <el-input v-model="queryParams.qwTagName" placeholder="请输入标签名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">新增绑定</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="bindList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标签ID" align="center" prop="qwTagId" width="200" show-overflow-tooltip />
      <el-table-column label="标签名称" align="center" prop="qwTagName" show-overflow-tooltip />
      <el-table-column label="模板ID" align="center" prop="templateId" width="100" />
      <el-table-column label="模板名称" align="center" prop="templateName" show-overflow-tooltip />
      <el-table-column label="优先级" align="center" prop="priority" width="80" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新增/修改绑定对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="企微标签" prop="qwTagIds">
          <el-select v-model="form.qwTagIds" multiple filterable placeholder="请选择企微标签（可多选）" style="width: 100%;" @change="onTagChange">
            <el-option v-for="tag in tagList" :key="tag.id" :label="tag.name + ' (' + tag.tagId + ')'" :value="tag.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作流模板" prop="templateId">
          <el-select v-model="form.templateId" filterable placeholder="请选择工作流模板" style="width: 100%;" @change="onTemplateChange">
            <el-option v-for="tpl in templateList" :key="tpl.templateId" :label="tpl.templateName" :value="tpl.templateId" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="0" :max="100" placeholder="0-100，越高优先级越高" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTagTemplateBind, addTagTemplateBind, updateTagTemplateBind, delTagTemplateBind } from '@/api/aiAddwxSop/api'
import { listTemplate } from '@/api/aiAddwxSop/api'
import { listTag } from '@/api/qw/tag'

export default {
  name: 'TagTemplateBind',
  data() {
    return {
      showSearch: true,
      loading: false,
      total: 0,
      bindList: [],
      tagList: [],
      templateList: [],
      ids: [],
      title: '',
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qwTagName: null,
        templateName: null
      },
      form: {},
      rules: {
        qwTagIds: [{ required: true, message: '请选择企微标签', trigger: 'change' }],
        templateId: [{ required: true, message: '请选择工作流模板', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
    this.loadTagList()
    this.loadTemplateList()
  },
  methods: {
    getList() {
      this.loading = true
      listTagTemplateBind(this.queryParams).then(response => {
        this.bindList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    loadTagList() {
      listTag({ pageNum: 1, pageSize: 9999 }).then(response => {
        this.tagList = response.rows || []
      })
    },
    loadTemplateList() {
      listTemplate({ status: 1 }).then(response => {
        this.templateList = response.rows || []
      })
    },
    onTagChange(vals) {
      if (vals && vals.length > 0) {
        const names = vals.map(id => {
          const tag = this.tagList.find(t => t.id === id)
          return tag ? tag.name : ''
        }).filter(n => n)
        this.form.qwTagName = names.join('、')
      } else {
        this.form.qwTagName = ''
      }
    },
    onTemplateChange(val) {
      const tpl = this.templateList.find(t => t.templateId === val)
      if (tpl) {
        this.form.templateName = tpl.templateName
      }
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {}
      this.$refs.form && this.$refs.form.resetFields()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bindId)
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增标签模板绑定'
    },
    handleUpdate(row) {
      this.reset()
      this.form = { ...row, qwTagIds: row.qwTagId ? [row.qwTagId] : [] }
      this.open = true
      this.title = '修改标签模板绑定'
    },
    handleDelete(row) {
      this.$confirm('确认删除该绑定关系吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delTagTemplateBind(row.bindId)
      }).then(() => {
        this.getList()
        this.$message.success('删除成功')
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.bindId != null) {
            // 编辑：单标签
            const data = { ...this.form }
            if (data.qwTagIds && data.qwTagIds.length > 0) {
              data.qwTagId = data.qwTagIds[0]
              const tag = this.tagList.find(t => t.id === data.qwTagId)
              data.qwTagName = tag ? tag.name : ''
            }
            updateTagTemplateBind(data).then(() => {
              this.$message.success('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            // 新增：支持多标签批量绑定
            addTagTemplateBind(this.form).then(() => {
              this.$message.success('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    }
  }
}
</script>
