<template>
  <el-dialog
    :visible.sync="visibleProxy"
    :show-close="false"
    width="92%"
    :close-on-click-modal="false"
    custom-class="customer-info-dialog"
    append-to-body
  >
    <div class="dialog-inner">
      <div class="dialog-header">
        <div class="dialog-title-wrap">
          <div class="dialog-title">客户信息</div>
          <div class="dialog-subtitle">{{ filterSummary }}</div>
        </div>
        <span class="dialog-close" @click="visibleProxy = false"><i class="el-icon-close"></i></span>
      </div>

      <div class="type-tabs">
        <button
          v-for="tab in tabList"
          :key="tab.value"
          type="button"
          :class="['type-tab', { 'is-active': currentFilterType === tab.value }]"
          @click="onTabClick(tab.value)"
        >
          <i :class="tabIcon(tab.value)"></i>
          {{ tab.label }}
        </button>
      </div>

      <div v-if="currentFilterType === '3'" class="tier-tabs">
        <span class="tier-tabs-label"><i class="el-icon-data-analysis"></i> 会员分层</span>
        <button
          v-for="tier in tierList"
          :key="tier.value"
          type="button"
          :class="['tier-tab', 'tier-tab--' + (tier.value || 'all'), { 'is-active': memberTier === tier.value }]"
          @click="onTierClick(tier.value)"
        >
          {{ tier.label }}
        </button>
      </div>

      <div class="dialog-search">
        <div class="search-bar">
          <div class="search-input-wrap">
            <i class="el-icon-search search-input-icon"></i>
            <el-input
              v-model="keyword"
              placeholder="输入姓名 / 手机号 / 会员卡号搜索"
              clearable
              class="search-input"
              @keyup.enter.native="search"
              @clear="search"
            />
          </div>
          <div class="search-actions">
            <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button icon="el-icon-refresh-left" @click="reset">重置</el-button>
          </div>
        </div>
      </div>

      <div class="dialog-content">
        <el-table
          v-loading="loading"
          :data="list"
          border
          size="small"
          :header-cell-style="{ background: '#f8fafc', color: '#64748b', fontWeight: 600 }"
        >
          <el-table-column label="客户姓名" min-width="110" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span class="cell-nowrap">
                <i class="el-icon-user cell-icon cell-icon--name"></i>{{ emptyText(row.khmc) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="手机号" width="120" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span class="cell-nowrap">
                <i class="el-icon-phone cell-icon cell-icon--phone"></i>{{ emptyText($maskMobile(row.sjh)) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="客户类型" width="96" align="center">
            <template slot-scope="{ row }">
              <el-tag size="mini" :type="typeTagType(row.khlx)" effect="plain">
                {{ emptyText(row.khlxName || typeLabel(row.khlx)) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="归属门店" min-width="110" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span class="cell-nowrap">
                <i class="el-icon-office-building cell-icon cell-icon--store"></i>{{ emptyText(row.gsmdName) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="健康师" min-width="90" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span class="cell-nowrap">{{ emptyText(row.mainHealthUserName) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="负责顾问" min-width="90" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span class="cell-nowrap">{{ emptyText(row.subHealthUserName) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="消费层级" width="88" align="center">
            <template slot-scope="{ row }">
              <span class="level-badge" :class="'level-badge--' + (row.consumeLevelName || 'D')">
                {{ row.consumeLevelName || 'D' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="注册时间" width="110" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span class="cell-nowrap">{{ formatDate(row.zcsj) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="120" show-overflow-tooltip>
            <template slot-scope="{ row }">{{ emptyText(row.bz) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right" align="left">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="openEdit(row)">编辑</el-button>
              <el-button type="text" size="small" @click="openProfile(row)">档案</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="dialog-footer">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size.sync="listQuery.pageSize"
          :current-page.sync="listQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="initData"
          @current-change="initData"
        />
      </div>
    </div>

    <customer-edit-dialog
      :visible.sync="editVisible"
      :member-id="editMemberId"
      :type-options="editTypeOptions"
      :store-list="storeList"
      :current-store-id="currentStoreId"
      @success="handleEditSuccess"
    />
  </el-dialog>
</template>

<script>
import { getKhxxList, getCustomerTypes } from '@/api/lqKhxx'
import CustomerEditDialog from '@/components/customer-edit-dialog.vue'

const DEFAULT_TABS = [
  { label: '全部', value: '' },
  { label: '线索', value: '0' },
  { label: '新客', value: '1' },
  { label: '散客', value: '2' },
  { label: '会员', value: '3' },
  { label: '归档', value: '4' }
]

// 会员分层（活跃度口径，与门店会员分层统计一致）
const TIER_TABS = [
  { label: '全部', value: '' },
  { label: '常到店', value: 'active' },
  { label: '预警客', value: 'warn' },
  { label: '灰客', value: 'gray' },
  { label: '黑客', value: 'black' },
  { label: '新客', value: 'new' },
  { label: '退款', value: 'refund' }
]

export default {
  name: 'CustomerInfoDialog',
  components: { CustomerEditDialog },
  props: {
    visible: { type: Boolean, default: false },
    currentStoreId: { type: String, default: '' },
    storeList: { type: Array, default: () => [] }
  },
  data() {
    return {
      loading: false,
      keyword: '',
      currentFilterType: '',
      tabList: [...DEFAULT_TABS],
      tierList: [...TIER_TABS],
      memberTier: '',
      list: [],
      total: 0,
      listQuery: { currentPage: 1, pageSize: 20, sort: 'desc', sidx: '' },
      editVisible: false,
      editMemberId: ''
    }
  },
  computed: {
    visibleProxy: {
      get() { return this.visible },
      set(v) { this.$emit('update:visible', v) }
    },
    editTypeOptions() {
      return this.tabList
        .filter(t => t.value !== '')
        .map(t => ({ label: t.label, value: t.value }))
    },
    filterSummary() {
      const tab = this.tabList.find(t => t.value === this.currentFilterType)
      const typeLabel = tab ? tab.label : '全部'
      const parts = [typeLabel]
      if (this.currentFilterType === '3' && this.memberTier) {
        const tier = this.tierList.find(t => t.value === this.memberTier)
        if (tier) parts.push(tier.label)
      }
      parts.push('本店', `共 ${this.total} 人`)
      return parts.join(' · ')
    }
  },
  watch: {
    visible(v) {
      if (v) {
        this.loadCustomerTypes()
        this.initData()
      }
    }
  },
  methods: {
    emptyText(val) {
      if (val === undefined || val === null || String(val).trim() === '') return '无'
      return val
    },
    tabIcon(value) {
      const map = {
        '': 'el-icon-menu',
        0: 'el-icon-connection',
        1: 'el-icon-star-off',
        2: 'el-icon-user',
        3: 'el-icon-medal',
        4: 'el-icon-folder'
      }
      return map[value] || map[String(value)] || 'el-icon-user'
    },
    typeLabel(khlx) {
      const tab = this.tabList.find(t => String(t.value) === String(khlx))
      return tab ? tab.label : '无'
    },
    typeTagType(khlx) {
      const map = { 0: 'info', 1: 'warning', 2: '', 3: 'success', 4: 'info' }
      return map[Number(khlx)] || ''
    },
    formatDate(val) {
      if (!val) return '无'
      const d = new Date(val)
      if (isNaN(d.getTime())) return String(val).substring(0, 10)
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    async loadCustomerTypes() {
      try {
        const res = await getCustomerTypes()
        const rows = res.data || []
        if (rows.length) {
          this.tabList = [
            { label: '全部', value: '' },
            ...rows.map(item => ({
              label: item.description || item.name || item.Description || item.Name,
              value: String(item.value != null ? item.value : item.Value)
            }))
          ]
        }
      } catch (e) {
        this.tabList = [...DEFAULT_TABS]
      }
    },
    buildParams() {
      const params = {
        ...this.listQuery,
        keyWord: this.keyword ? this.keyword.trim() : undefined,
        khlx: this.currentFilterType !== '' ? this.currentFilterType : undefined,
        gsmd: this.currentStoreId || undefined
      }
      // 会员分层筛选（活跃度口径，单店，需门店范围）
      if (this.currentFilterType === '3' && this.memberTier && params.gsmd) {
        params.memberTier = this.memberTier
      }
      Object.keys(params).forEach(key => {
        if (params[key] === undefined || params[key] === '' || params[key] === null) {
          delete params[key]
        }
      })
      return params
    },
    async initData() {
      if (!this.currentStoreId) {
        this.$message.warning('未获取到门店信息')
        return
      }
      this.loading = true
      try {
        const res = await getKhxxList(this.buildParams())
        this.list = res.data?.list || []
        this.total = res.data?.pagination?.total || 0
      } catch (e) {
        this.list = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    onTabClick(value) {
      this.currentFilterType = value
      // 切换客户类型时重置会员分层筛选（分层仅对「会员」有效）
      if (value !== '3') this.memberTier = ''
      this.search()
    },
    onTierClick(value) {
      this.memberTier = this.memberTier === value ? '' : value
      this.search()
    },
    search() {
      this.listQuery.currentPage = 1
      this.initData()
    },
    reset() {
      this.keyword = ''
      this.currentFilterType = ''
      this.memberTier = ''
      this.listQuery = { currentPage: 1, pageSize: 20, sort: 'desc', sidx: '' }
      this.initData()
    },
    openEdit(row) {
      if (!row || !row.id) return
      this.editMemberId = row.id
      this.editVisible = true
    },
    openProfile(row) {
      if (!row || !row.id) return
      this.$emit('profile', {
        id: row.id,
        khmc: row.khmc || '',
        sjh: row.sjh || '',
        dah: row.dah || ''
      })
    },
    handleEditSuccess() {
      this.initData()
      this.$emit('updated')
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .customer-info-dialog {
  max-width: 1680px;
  margin-top: 2vh !important;
  border-radius: 20px;
  padding: 0;
  background: radial-gradient(circle at 0 0, rgba(255, 255, 255, 0.96) 0, rgba(248, 250, 252, 0.98) 40%, rgba(241, 245, 249, 0.98) 100%);
  box-shadow: 0 24px 48px rgba(15, 23, 42, 0.18), 0 0 0 1px rgba(255, 255, 255, 0.9);
  .el-dialog__header { display: none; }
  .el-dialog__body { padding: 0; }
}
.dialog-inner { display: flex; flex-direction: column; max-height: 92vh; }
.dialog-header {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 18px 22px 0;
  padding: 10px 14px;
  border-radius: 14px;
  background: rgba(224, 242, 254, 0.96);
}
.dialog-title-wrap { display: flex; flex-direction: column; gap: 2px; }
.dialog-title { font-size: 17px; font-weight: 600; color: #0f172a; }
.dialog-subtitle { font-size: 12px; color: #64748b; }
.dialog-close {
  cursor: pointer;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 999px;
  color: #64748b;
  &:hover { background: rgba(0, 0, 0, 0.06); color: #0f172a; }
}
.type-tabs {
  flex-shrink: 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px 22px 4px;
}
.type-tab {
  border: 1px solid #e2e8f0;
  background: #fff;
  color: #475569;
  border-radius: 999px;
  padding: 6px 14px;
  font-size: 13px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  transition: all 0.15s;
  i { font-size: 14px; }
  &:hover { border-color: #0ea5e9; color: #0284c7; }
  &.is-active {
    background: linear-gradient(135deg, #0ea5e9, #0284c7);
    border-color: transparent;
    color: #fff;
    box-shadow: 0 4px 10px rgba(14, 165, 233, 0.35);
  }
}
.tier-tabs {
  flex-shrink: 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  padding: 8px 22px 0;
}
.tier-tabs-label {
  font-size: 12px;
  color: #64748b;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  margin-right: 2px;
  i { color: #0ea5e9; }
}
.tier-tab {
  border: 1px solid #e2e8f0;
  background: #fff;
  color: #475569;
  border-radius: 999px;
  padding: 4px 12px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.15s;
  &:hover { border-color: #0ea5e9; color: #0284c7; }
  &.is-active {
    color: #fff;
    border-color: transparent;
    box-shadow: 0 3px 8px rgba(15, 23, 42, 0.18);
  }
  &.tier-tab--all.is-active { background: #64748b; }
  &.tier-tab--active.is-active { background: #22c55e; }
  &.tier-tab--warn.is-active { background: #f59e0b; }
  &.tier-tab--gray.is-active { background: #94a3b8; }
  &.tier-tab--black.is-active { background: #475569; }
  &.tier-tab--new.is-active { background: #0ea5e9; }
  &.tier-tab--refund.is-active { background: #ef4444; }
}
.dialog-search { flex-shrink: 0; padding: 12px 22px 6px; }
.search-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 10px 12px;
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.85);
  border: 1px solid rgba(226, 232, 240, 0.9);
  box-shadow: inset 0 1px 2px rgba(15, 23, 42, 0.03);
}
.search-input-wrap {
  position: relative;
  flex: 1;
  max-width: 420px;
  .search-input-icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
    color: #94a3b8;
    font-size: 15px;
    pointer-events: none;
  }
}
::v-deep .search-input .el-input__inner {
  height: 38px;
  line-height: 38px;
  padding-left: 34px;
  border-radius: 10px;
  border-color: #e2e8f0;
  background: #fff;
  transition: all 0.15s;
  &:focus { border-color: #0ea5e9; box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.12); }
}
.search-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  .el-button { border-radius: 10px; padding: 10px 18px; }
}
.dialog-content { flex: 1; min-height: 0; overflow: auto; padding: 0 22px; }
.dialog-footer {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 10px 22px 14px;
  border-top: 1px solid rgba(229, 231, 235, 0.6);
}
.cell-nowrap { white-space: nowrap; }
.cell-icon { margin-right: 4px; }
.cell-icon--name { color: #0ea5e9; }
.cell-icon--phone { color: #22c55e; }
.cell-icon--store { color: #8b5cf6; }
.level-badge {
  display: inline-block;
  min-width: 24px;
  padding: 0 6px;
  border-radius: 6px;
  font-weight: 600;
  font-size: 12px;
  line-height: 20px;
  background: #f1f5f9;
  color: #64748b;
}
.level-badge--S { background: #fef3c7; color: #b45309; }
.level-badge--A { background: #dbeafe; color: #1d4ed8; }
.level-badge--B { background: #dcfce7; color: #15803d; }
.level-badge--C { background: #f3e8ff; color: #7e22ce; }
::v-deep .customer-info-dialog .el-button--primary {
  border-radius: 999px;
  background: #0284c7;
  border-color: #0284c7;
}
</style>
