<template>
  <div class="ai-tag-container">
    <div class="ai-tag-header">
      <div class="header-left">
        <i class="el-icon-magic-sticker" style="color: #6b5fff; font-size: 18px; margin-right: 6px;"></i>
        <span class="tag-title">AI 标签</span>
        <el-tooltip content="AI 自动打标签" placement="bottom">
          <span class="tag-subtitle">(AI 自动打标签)</span>
        </el-tooltip>
      </div>
      <div class="header-right">
        <el-button type="text" icon="el-icon-plus" size="mini" @click="handleAddTag" style="color: #ff9800;">
          点击增加 AI 标签维度
        </el-button>
        <el-button type="text" icon="el-icon-view" size="mini" @click="toggleView" style="margin-left: 10px;">
          <i class="el-icon-view"></i>
        </el-button>
      </div>
    </div>

    <div class="ai-tag-content" v-loading="loading">
      <div v-if="tagList.length === 0" class="empty-tips">
        <i class="el-icon-info"></i>
        <span>暂无标签，点击"添加标签"开始设置</span>
      </div>

      <div v-else class="tag-list">
        <div v-for="(tag, index) in tagList" :key="tag.id" class="tag-item">
          <div class="tag-name">
            <i class="el-icon-more"></i>
            <span>{{ tag.propertyName }}</span>
          </div>
          <div class="tag-values">
            <el-tag
              v-if="tag.propertyValue"
              size="small"
              closable
              @close="handleDeleteTag(tag)"
              @click="handleEditTag(tag)"
              style="cursor: pointer; margin-right: 8px; margin-bottom: 8px;"
            >
              {{ tag.propertyValue }}
            </el-tag>
            <span v-else class="no-value">未设置</span>
            <el-button
              v-if="!tag.propertyValue"
              type="text"
              size="mini"
              icon="el-icon-edit"
              @click="handleEditTag(tag)"
            >
              批注
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑标签弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标签维度" prop="propertyId">
          <el-select
            v-model="form.propertyId"
            placeholder="请选择标签维度"
            style="width: 100%"
            :disabled="isEdit"
            @change="handlePropertyChange"
          >
            <el-option
              v-for="item in propertyTemplateList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ getValueTypeText(item.valueType) }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签值" prop="propertyValue">
          <el-input
            v-if="currentValueType === 'text'"
            v-model="form.propertyValue"
            placeholder="请输入标签值"
            maxlength="100"
            show-word-limit
          />
          <el-select
            v-else-if="currentValueType === 'select'"
            v-model="form.propertyValue"
            placeholder="请选择标签值"
            style="width: 100%"
            clearable
          >
            <el-option label="是" value="是" />
            <el-option label="否" value="否" />
          </el-select>
          <el-input
            v-else-if="currentValueType === 'number'"
            v-model="form.propertyValue"
            placeholder="请输入数字"
            maxlength="20"
          />
          <el-input
            v-else-if="currentValueType === 'date'"
            v-model="form.propertyValue"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
          <span v-else class="unknown-type">未知的属性类型</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPropertyTemplate } from "@/api/crm/propertyTemplate";
import { listByCustomerId, addOrUpdateByTemplateId, deleteByPropertyId } from "@/api/crm/customerProperty";

export default {
  name: "AiTagPanel",
  props: {
    customerId: {
      type: Number,
      required: true,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      tagList: [],
      propertyTemplateList: [],
      dialogVisible: false,
      dialogTitle: "",
      isEdit: false,
      currentValueType: "text",
      form: {
        customerId: null,
        propertyId: null,
        propertyName: null,
        propertyValue: null,
        propertyValueType: null,
        tradeType: null,
        remark: null
      },
      rules: {
        propertyId: [
          { required: true, message: "请选择标签维度", trigger: "change" }
        ],
        propertyValue: [
          { required: true, message: "请输入标签值", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    if (this.customerId) {
      this.loadTags();
    }
  },
  watch: {
    customerId(newVal) {
      if (newVal) {
        this.loadTags();
      }
    }
  },
  methods: {
    loadTags() {
      this.loading = true;
      listByCustomerId(this.customerId).then(response => {
        this.tagList = response.data || [];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    loadPropertyTemplates() {
      listPropertyTemplate({ pageNum: 1, pageSize: 100 }).then(response => {
        this.propertyTemplateList = response.rows || [];
      });
    },
    toggleView() {
      this.$emit("toggle-view");
    },
    handleAddTag() {
      this.loadPropertyTemplates();
      this.reset();
      this.dialogTitle = "添加标签";
      this.isEdit = false;
      this.dialogVisible = true;
    },
    handleEditTag(tag) {
      this.loadPropertyTemplates();
      this.form = {
        customerId: tag.customerId,
        propertyId: tag.propertyId,
        propertyName: tag.propertyName,
        propertyValue: tag.propertyValue,
        propertyValueType: tag.propertyValueType,
        tradeType: tag.tradeType,
        remark: tag.remark
      };
      this.currentValueType = tag.propertyValueType || "text";
      this.dialogTitle = "编辑标签";
      this.isEdit = true;
      this.dialogVisible = true;
    },
    handleDeleteTag(tag) {
      this.$confirm(`确认删除标签"${tag.propertyName}"吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return deleteByPropertyId(this.customerId, tag.propertyId);
      }).then(() => {
        this.msgSuccess("删除成功");
        this.loadTags();
        this.$emit("tag-change");
      }).catch(() => {});
    },
    handlePropertyChange(propertyId) {
      const template = this.propertyTemplateList.find(item => item.id === propertyId);
      if (template) {
        this.form.propertyName = template.name;
        this.form.propertyValueType = template.valueType;
        this.form.tradeType = template.tradeType;
        this.currentValueType = template.valueType;
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.customerId = this.customerId;
          addOrUpdateByTemplateId(
            this.customerId,
            this.form.propertyId,
            this.form.propertyValue
          ).then(response => {
            this.msgSuccess("保存成功");
            this.dialogVisible = false;
            this.loadTags();
            this.$emit("tag-change");
          });
        }
      });
    },
    reset() {
      this.form = {
        customerId: this.customerId,
        propertyId: null,
        propertyName: null,
        propertyValue: null,
        propertyValueType: null,
        tradeType: null,
        remark: null
      };
      this.currentValueType = "text";
      this.isEdit = false;
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    getValueTypeText(valueType) {
      const typeMap = {
        text: "文本",
        number: "数字",
        date: "日期",
        select: "单选",
        multiSelect: "多选"
      };
      return typeMap[valueType] || valueType;
    }
  }
};
</script>

<style lang="scss" scoped>
.ai-tag-container {
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  .ai-tag-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;

    .header-left {
      display: flex;
      align-items: center;

      .tag-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .tag-subtitle {
        font-size: 12px;
        color: #909399;
        margin-left: 8px;
      }
    }

    .header-right {
      display: flex;
      align-items: center;
    }
  }

  .ai-tag-content {
    min-height: 200px;

    .empty-tips {
      text-align: center;
      color: #909399;
      padding: 40px 0;

      i {
        font-size: 40px;
        display: block;
        margin-bottom: 8px;
      }
    }

    .tag-list {
      .tag-item {
        margin-bottom: 16px;

        .tag-name {
          display: flex;
          align-items: center;
          margin-bottom: 8px;
          font-size: 14px;
          font-weight: 500;
          color: #303133;

          i {
            color: #409eff;
            margin-right: 6px;
            font-size: 12px;
          }
        }

        .tag-values {
          display: flex;
          align-items: center;
          flex-wrap: wrap;

          .no-value {
            color: #c0c4cc;
            font-size: 13px;
          }
        }
      }
    }
  }
}
</style>
