<template>
  <div class="info-section">
    <div class="section-header">
      <span class="section-title"><i class="el-icon-magic-sticker"></i> AI 标签</span>
      <div class="header-actions">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddTag">添加维度</el-button>
      </div>
    </div>
    <div class="section-content" v-loading="loading">
      <div v-if="tagList.length === 0" class="empty-tips">
        <span>暂无标签，点击"添加维度"开始设置</span>
      </div>

      <el-row :gutter="24" v-else>
        <el-col :span="6" v-for="tag in tagList" :key="tag.id" class="tag-col">
          <div class="info-item">
            <span class="info-label">
              {{ tag.propertyName }}
              <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDeleteTag(tag)" style="color: #f56c6c; margin-left: 4px;"></el-button>
            </span>
            <span class="info-value">
              <el-tag
                v-if="tag.propertyValue"
                size="mini"
                @click="handleEditTag(tag)"
                style="cursor: pointer;"
                :type="getIntentionTagType(tag.intention)"
              >
                <span v-if="Array.isArray(tag.propertyValue)">{{ tag.propertyValue.join('、') }}</span>
                <span v-else>{{ tag.propertyValue }}</span>
              </el-tag>
              <span v-else class="no-value">
                未设置
                <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEditTag(tag)" style="margin-left: 4px;">批注</el-button>
              </span>
            </span>
            <div class="tag-extra-info">
              <el-tag v-if="tag.intention" size="mini" effect="plain">
                <i class="el-icon-star-on"></i> {{ getIntentionText(tag.intention) }}
              </el-tag>
              <el-tag v-if="tag.likeRatio !== null && tag.likeRatio !== undefined" size="mini" type="success" effect="plain">
                <i class="el-icon-trend-chart"></i> {{ tag.likeRatio }}%
              </el-tag>
            </div>
          </div>
        </el-col>
      </el-row>
    </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-select
            v-else-if="currentValueType === 'multiSelect'"
            v-model="form.propertyValue"
            placeholder="请选择标签值（可多选）"
            style="width: 100%"
            multiple
            collapse-tags
            clearable
          >
            <el-option label="喜欢" value="喜欢" />
            <el-option label="不喜欢" value="不喜欢" />
            <el-option label="一般" value="一般" />
            <el-option label="观望" value="观望" />
            <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="intention">
          <el-select v-model="form.intention" placeholder="请选择意向程度" style="width: 100%" clearable>
            <el-option label="高意向（80-100%）" value="high" />
            <el-option label="中意向（50-79%）" value="medium" />
            <el-option label="低意向（20-49%）" value="low" />
            <el-option label="无意向（0-19%）" value="none" />
          </el-select>
        </el-form-item>
        <el-form-item label="喜欢占比" prop="likeRatio">
          <el-slider v-model="form.likeRatio" :min="0" :max="100" show-input input-size="small" />
        </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, addOrUpdate } 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,
        intention: null,
        likeRatio: 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();
      }
    },
    'form.likeRatio'(newVal) {
      if (newVal !== null && newVal !== undefined) {
        this.autoSetIntention(newVal);
      }
    }
  },
  methods: {
    autoSetIntention(likeRatio) {
      let intention = null;
      if (likeRatio >= 80) {
        intention = 'high';
      } else if (likeRatio >= 50) {
        intention = 'medium';
      } else if (likeRatio >= 20) {
        intention = 'low';
      } else {
        intention = 'none';
      }
      this.form.intention = intention;
    },
    loadTags() {
      this.loading = true;
      listByCustomerId(this.customerId).then(response => {
        let tagList = response.data || [];
        console.log('加载的标签数据:', tagList);
        tagList.forEach(tag => {
          if (tag.propertyValueType === 'multiSelect' && tag.propertyValue && typeof tag.propertyValue === 'string') {
            tag.propertyValue = tag.propertyValue.split(',');
          }
        });
        this.tagList = tagList;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    loadPropertyTemplates() {
      listPropertyTemplate({ pageNum: 1, pageSize: 100 }).then(response => {
        this.propertyTemplateList = response.rows || [];
      });
    },

    handleAddTag() {
      this.loadPropertyTemplates();
      this.reset();
      this.dialogTitle = "添加标签";
      this.isEdit = false;
      this.dialogVisible = true;
    },
    handleEditTag(tag) {
      this.loadPropertyTemplates();
      let propertyValue = tag.propertyValue;
      if (tag.propertyValueType === 'multiSelect' && propertyValue && typeof propertyValue === 'string') {
        propertyValue = propertyValue.split(',');
      }
      this.form = {
        customerId: tag.customerId,
        propertyId: tag.propertyId,
        propertyName: tag.propertyName,
        propertyValue: propertyValue,
        propertyValueType: tag.propertyValueType,
        tradeType: tag.tradeType,
        intention: tag.intention || null,
        likeRatio: tag.likeRatio || null,
        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.$message.success("删除成功");
        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;
          const requestData = {
            customerId: this.customerId,
            propertyId: this.form.propertyId,
            propertyName: this.form.propertyName,
            propertyValue: Array.isArray(this.form.propertyValue) ? this.form.propertyValue.join(',') : this.form.propertyValue,
            propertyValueType: this.form.propertyValueType,
            tradeType: this.form.tradeType,
            intention: this.form.intention,
            likeRatio: this.form.likeRatio,
            remark: this.form.remark
          };
          
          addOrUpdate(requestData).then(response => {
            if (response.code === 200) {
              this.$message.success("保存成功");
              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,
        intention: null,
        likeRatio: 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;
    },
    getIntentionText(intention) {
      const intentionMap = {
        high: "高意向",
        medium: "中意向",
        low: "低意向",
        none: "无意向"
      };
      return intentionMap[intention] || intention;
    },
    getIntentionTagType(intention) {
      const typeMap = {
        high: "success",
        medium: "warning",
        low: "info",
        none: "danger"
      };
      return typeMap[intention] || "";
    }
  }
};
</script>

<style lang="scss" scoped>
.info-section {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

  .section-header {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    background: #fafbfc;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .section-title {
      font-size: 15px;
      font-weight: 600;
      color: #303133;
      display: flex;
      align-items: center;
      gap: 8px;

      i {
        color: #409eff;
      }
    }

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

  .section-content {
    padding: 20px;
    min-height: 80px;

    .empty-tips {
      text-align: center;
      color: #909399;
      padding: 20px 0;
      font-size: 14px;
    }

    .tag-col {
      margin-bottom: 0;
    }
  }
}

.info-item {
  margin-bottom: 16px;

  .info-label {
    display: block;
    font-size: 12px;
    color: #909399;
    margin-bottom: 6px;
    display: flex;
    align-items: center;
  }

  .info-value {
    font-size: 14px;
    color: #303133;
    display: flex;
    align-items: center;

    .no-value {
      color: #c0c4cc;
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .tag-extra-info {
    margin-top: 6px;
    display: flex;
    align-items: center;
    gap: 8px;
  }
}
</style>
