<template>
  <div class="app-container portrait-container">

    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消费等级" prop="consumptionLevel">
        <el-select
          v-model="queryParams.consumptionLevel"
          placeholder="请选择消费等级"
          clearable
          size="small"
          style="width: 130px"
        >
          <el-option label="S+" value="S+" />
          <el-option label="S"  value="S" />
          <el-option label="A"  value="A" />
          <el-option label="B"  value="B" />
          <el-option label="C"  value="C" />
          <el-option label="D"  value="D" />
          <el-option label="E"  value="E" />
          <el-option label="代客下单"  value="F" />
        </el-select>
      </el-form-item>
      <el-form-item label="活跃度" prop="activityLevel">
        <el-select
          v-model="queryParams.activityLevel"
          placeholder="请选择活跃度"
          clearable
          size="small"
          style="width: 130px"
        >
          <el-option label="高活跃" value="高活跃" />
          <el-option label="中活跃" value="中活跃" />
          <el-option label="低活跃" value="低活跃" />
          <el-option label="沉默"   value="沉默" />
          <el-option label="流失"   value="流失" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="portraitList" border stripe style="width: 100%">
      <el-table-column label="用户ID" align="center" prop="userId" min-width="130" />

      <el-table-column label="头像" align="center" width="80">
        <template slot-scope="scope">
          <el-avatar
            v-if="scope.row.avatar"
            :src="scope.row.avatar"
            :size="40"
          />
          <el-avatar v-else icon="el-icon-user-solid" :size="40" style="background:#c0c4cc" />
        </template>
      </el-table-column>

      <el-table-column label="昵称" align="center" prop="nickName" min-width="120" show-overflow-tooltip />
      <el-table-column label="手机号" align="center" prop="phone" min-width="160" />

      <el-table-column label="活跃度" align="center" prop="activityLevel" width="110">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.activityLevel"
            :type="activityTagType(scope.row.activityLevel)"
            size="small"
          >{{ scope.row.activityLevel }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="消费等级" align="center" prop="consumptionLevel" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.consumptionLevel" :class="consumptionClass(scope.row.consumptionLevel)" class="level-badge">
            {{ comsumptionLevelMapper[scope.row.consumptionLevel] }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="兴趣标签" align="center" prop="interestTags" min-width="230">
        <template slot-scope="scope">
          <template v-if="scope.row.interestTags">
            <el-tag
              v-for="(tag, idx) in splitTags(scope.row.interestTags)"
              :key="idx"
              type="success"
              size="mini"
              style="margin: 2px;"
            >{{ tag }}</el-tag>
          </template>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="城市" align="center" prop="location" width="110" show-overflow-tooltip />

      <el-table-column label="疗法周期" align="center" min-width="160">
        <template slot-scope="scope">
          <template v-if="scope.row.treatmentCycle">
            <el-button
              v-for="(cycle, idx) in splitTags(scope.row.treatmentCycle)"
              :key="idx"
              size="mini"
              type="primary"
              plain
              style="margin: 2px;"
              @click="openTreatmentDialog(scope.row, cycle)"
            >{{ cycle }}</el-button>
          </template>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" min-width="160">
        <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              plain
              style="margin: 2px;"
              @click="openEditDialog(scope.row)"
            />
        </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="疗法周期详情"
      :visible.sync="treatmentDialog.visible"
      width="620px"
      append-to-body
      custom-class="treatment-dialog"
      @close="closeTreatmentDialog"
    >
      <div v-loading="treatmentDialog.loading" class="treatment-content">
        <!-- 用户信息头部 -->
        <div class="treatment-user-header">
          <el-avatar
            v-if="treatmentDialog.row && treatmentDialog.row.avatar"
            :src="treatmentDialog.row && treatmentDialog.row.avatar"
            :size="48"
          />
          <el-avatar v-else icon="el-icon-user-solid" :size="48" style="background:#909399" />
          <div class="treatment-user-info">
            <div class="user-name">{{ treatmentDialog.row && (treatmentDialog.row.nickName || '—') }}</div>
            <div class="user-phone">{{ treatmentDialog.row && (treatmentDialog.row.phone || '—') }}</div>
          </div>
          <el-tag v-if="treatmentDialog.cycleName" type="warning" style="margin-left: auto;">
            {{ treatmentDialog.cycleName }}
          </el-tag>
        </div>

        <!-- 详情字段 -->
        <el-descriptions
          class="treatment-desc"
          :column="2"
          border
          size="small"
        >
          <el-descriptions-item label="购买时间">
            <span>{{ treatmentDialog.detail.buyTime || '—' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="购买量">
            <span>{{ treatmentDialog.detail.buyQuantity || '—' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="建议单日服用量">
            <span>{{ treatmentDialog.detail.dailyDosage || '—' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="回访时间">
            <span>{{ treatmentDialog.detail.visitTime || '—' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="提醒复购时间">
            <span>{{ treatmentDialog.detail.repurchaseRemindTime || '—' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="推测余量">
            <span>{{ treatmentDialog.detail.estimatedRemaining || '—' }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 空状态 -->
        <div v-if="!treatmentDialog.loading && !hasTreatmentData" class="treatment-empty">
          <i class="el-icon-warning-outline" style="font-size:36px;color:#c0c4cc"></i>
          <p>暂无疗法周期数据</p>
        </div>
      </div>

      <div slot="footer">
        <el-button @click="treatmentDialog.visible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="编辑画像"
      :visible.sync="editDialog.visible"
      width="350px"
      append-to-body
      :close-on-click-modal="false"
      custom-class="user-portrait-dialog"
    >
      <div v-loading="editDialog.loading">
        <el-form :model="editDialog.editForm" ref="editForm" :rules="editDialog.rules" :inline="true" label-width="80px">
          <el-row>
            <el-form-item label="用户ID">
              <el-input v-model="editDialog.editForm.userId" :disabled="true"/>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="昵称">
              <el-input v-model="editDialog.editForm.nickName" :disabled="true"/>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="消费等级" prop="consumptionLevel">
              <el-select
                v-model="editDialog.editForm.consumptionLevel"
                placeholder="请选择消费等级"
                clearable
                style="width: 205px;"
              >
                <el-option label="S+" value="S+" />
                <el-option label="S"  value="S" />
                <el-option label="A"  value="A" />
                <el-option label="B"  value="B" />
                <el-option label="C"  value="C" />
                <el-option label="D"  value="D" />
                <el-option label="E"  value="E" />
                <el-option label="代客下单"  value="F" />
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" size="small" :disabled="editDialog.loading" @click="submitEditInfo">确 认</el-button>
        <el-button size="small" @click="editDialog.visible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listUserPortrait, getUserTreatmentCycle, saveEdit, } from '@/api/app/user/portrait'

export default {
  name: 'UserPortrait',
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      portraitList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        phone: null,
        nickName: null,
        consumptionLevel: null,
        activityLevel: null
      },
      treatmentDialog: {
        visible: false,
        loading: false,
        row: null,
        cycleName: null,
        detail: {
          buyTime: null,
          buyQuantity: null,
          dailyDosage: null,
          visitTime: null,
          repurchaseRemindTime: null,
          estimatedRemaining: null
        }
      },
      comsumptionLevelMapper: {
        'S+': 'S+',
        'S': 'S',
        'A': 'A',
        'B': 'B',
        'C': 'C',
        'D': 'D',
        'E': 'E',
        'F': '代客下单'
      },
      editDialog: {
        loading: false,
        visible: false,
        id: null,
        editForm: {
          id: null,
          userId: null,
          nickName: null,
          consumptionLevel: null,
        },
        rules: {
          consumptionLevel: [
            { required: true, message: '请选择消费等级', trigger: 'change' }
          ]
        },
      },
    }
  },
  computed: {
    hasTreatmentData() {
      const d = this.treatmentDialog.detail
      return Object.values(d).some(v => v !== null && v !== '' && v !== undefined)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 获取列表 */
    getList() {
      this.loading = true
      const params = {}
      if (this.queryParams.pageNum) params.pageNum = this.queryParams.pageNum
      if (this.queryParams.pageSize) params.pageSize = this.queryParams.pageSize
      if (this.queryParams.userId) params.userId = this.queryParams.userId
      if (this.queryParams.phone) params.phone = this.queryParams.phone
      if (this.queryParams.nickName) params.nickName = this.queryParams.nickName
      if (this.queryParams.consumptionLevel) params.consumptionLevel = this.queryParams.consumptionLevel
      if (this.queryParams.activityLevel) params.activityLevel = this.queryParams.activityLevel
      listUserPortrait(params).then(response => {
        this.portraitList = response.rows || []
        this.total = response.total || 0
      }).finally(() => {
        this.loading = false
      })
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 拆分兴趣标签 */
    splitTags(str) {
      if (!str) return []
      return str.split(/[,，]/).map(t => t.trim()).filter(t => t)
    },
    /** 活跃度 tag 颜色 */
    activityTagType(level) {
      const map = {
        '高活跃': 'success',
        '中活跃': '',
        '低活跃': 'warning',
        '沉默': 'info',
        '流失': 'danger'
      }
      for (const key in map) {
        if (level && level.includes(key)) return map[key]
      }
      return 'info'
    },
    /** 消费等级样式 */
    consumptionClass(level) {
      const map = { 'S+': 'level-splus', 'S': 'level-s', 'A': 'level-a', 'F': 'level-a', 'B': 'level-b', 'C': 'level-c' }
      return map[level] || 'level-default'
    },
    /** 打开疗法周期详情（row: 当前行数据，cycleName: 点击的具体周期名称） */
    openTreatmentDialog(row, cycleName) {
      this.treatmentDialog.visible = true
      this.treatmentDialog.row = row
      this.treatmentDialog.cycleName = cycleName || null
      this.treatmentDialog.detail = {
        buyTime: null,
        buyQuantity: null,
        dailyDosage: null,
        visitTime: null,
        repurchaseRemindTime: null,
        estimatedRemaining: null
      }
      if (row.userId) {
        this.treatmentDialog.loading = true
        getUserTreatmentCycle(row.userId, cycleName).then(res => {
          const data = res.data || {}
          this.treatmentDialog.detail = {
            buyTime: data.buyTime || null,
            buyQuantity: data.buyQuantity || null,
            dailyDosage: data.dailyDosage || null,
            visitTime: data.visitTime || null,
            repurchaseRemindTime: data.repurchaseRemindTime || null,
            estimatedRemaining: data.estimatedRemaining || null
          }
        }).catch(() => {
          // 接口暂未对接时不报错
        }).finally(() => {
          this.treatmentDialog.loading = false
        })
      }
    },
    /** 关闭疗法周期弹窗 */
    closeTreatmentDialog() {
      this.treatmentDialog.row = null
      this.treatmentDialog.cycleName = null
    },
    openEditDialog(row) {
      this.editDialog.visible = true;
      this.editDialog.id = row.id;
      this.editDialog.loading = true;
      this.editDialog.editForm['id'] = row.id;
      this.editDialog.editForm['userId'] = row.userId;
      this.editDialog.editForm['nickName'] = row.nickName;
      this.editDialog.editForm['consumptionLevel'] = row.consumptionLevel;
      this.editDialog.loading = false;
    },
    submitEditInfo() {
      this.$refs["editForm"].validate(async (valid) => {
        this.editDialog.visible = true;
        if (valid) {
          await saveEdit(this.editDialog.editForm);
          this.$message.success("修改成功");
          this.$refs['editForm'].resetFields();
          this.$refs['editForm'].clearValidate();
          this.editDialog.visible = false;
          this.getList();
        }
        this.editDialog.visible = false;
      });
    },
  },
}
</script>

<style scoped lang="scss">
.portrait-container {
  padding: 20px;
}

/* 消费等级徽标 */
.level-badge {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 700;
  letter-spacing: 1px;
}
.level-splus { background: #8b0000; color: #fff; }
.level-s     { background: #c0392b; color: #fff; }
.level-a     { background: #e05555; color: #fff; }
.level-b     { background: #f0908a; color: #fff; }
.level-c     { background: #fad4d1; color: #c0392b; }
.level-default { background: #f0f0f0; color: #606266; }

/* 疗法周期弹窗 */
.treatment-content {
  min-height: 120px;
}
.treatment-user-header {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 18px;
  border: 1px solid #ebeef5;
}
.treatment-user-info .user-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}
.treatment-user-info .user-phone {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
.treatment-desc {
  margin-top: 4px;
}
.treatment-empty {
  text-align: center;
  padding: 30px 0 10px;
  color: #c0c4cc;
}
.treatment-empty p {
  margin-top: 8px;
  font-size: 13px;
}

::v-deep  .user-portrait-dialog {

  .el-form-item__label {
    text-align: right !important;
  }

}
</style>
