<template>
  <el-dialog
    :visible.sync="visibleProxy"
    :show-close="false"
    width="90%"
    :close-on-click-modal="false"
    custom-class="tuoke-list-dialog"
    append-to-body
  >
    <div class="dialog-inner">
      <div class="dialog-header">
        <div class="dialog-title">拓客数据</div>
        <span class="dialog-close" @click="visibleProxy = false"><i class="el-icon-close"></i></span>
      </div>

      <div class="dialog-search">
        <el-form @submit.native.prevent :inline="true" size="small">
          <el-form-item label="拓客时间">
            <el-date-picker v-model="query.expansionTime" type="daterange" value-format="timestamp" format="yyyy-MM-dd" start-placeholder="开始" end-placeholder="结束" style="width:220px" />
          </el-form-item>
          <el-form-item label="拓客活动">
            <el-select v-model="query.eventId" placeholder="请选择" clearable filterable style="width:180px" :loading="eventLoading">
              <el-option v-for="e in eventList" :key="e.id" :label="e.eventName" :value="e.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="顾客姓名">
            <el-input v-model="query.customerName" placeholder="顾客姓名" clearable style="width:140px" />
          </el-form-item>
          <el-form-item label="电话号码">
            <el-input v-model="query.customerPhone" placeholder="电话号码" clearable style="width:140px" />
          </el-form-item>
          <template v-if="showAll">
            <el-form-item label="购买张数">
              <el-input v-model="query.buyNumber" placeholder="购买张数" clearable style="width:120px" />
            </el-form-item>
            <el-form-item label="支付方式">
              <el-select v-model="query.paymentMethod" placeholder="支付方式" clearable style="width:120px">
                <el-option v-for="p in payMethodOptions" :key="p" :label="p" :value="p" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否加微信">
              <el-select v-model="query.isAddWeChat" placeholder="是否加微信" clearable style="width:120px">
                <el-option label="是" value="是" /><el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属战队">
              <el-input v-model="query.teamName" placeholder="战队名称" clearable style="width:130px" />
            </el-form-item>
          </template>
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button @click="reset">重置</el-button>
            <el-button type="text" @click="showAll = !showAll">
              {{ showAll ? '收起' : '展开' }}
              <i :class="showAll ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            </el-button>
          </el-form-item>
        </el-form>
      </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="拓客活动" show-overflow-tooltip>
            <template slot-scope="{ row }">{{ formatEmpty(row.eventName) }}</template>
          </el-table-column>
          <el-table-column prop="expansionUserName" label="拓客人员" show-overflow-tooltip />
          <el-table-column prop="storeName" label="所属门店" show-overflow-tooltip />
          <el-table-column label="拓客时间" width="140">
            <template slot-scope="{ row }">{{ formatDate(row.expansionTime) }}</template>
          </el-table-column>
          <el-table-column prop="customerName" label="顾客姓名" show-overflow-tooltip />
          <el-table-column prop="customerPhone" label="电话号码" show-overflow-tooltip />
          <el-table-column prop="buyNumber" label="购买张数" width="90" />
          <el-table-column prop="paymentMethod" label="支付方式" width="100" />
          <el-table-column prop="isAddWeChat" label="是否加微信" width="110" />
          <el-table-column prop="teamName" label="所属战队" show-overflow-tooltip />
          <el-table-column prop="remarks" label="备注" width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="88" fixed="right" align="center">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="openContact(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>

    <invite-add-dialog
      :visible.sync="contactDialogVisible"
      :customer="contactCustomer"
      :tkbh="contactTkbh"
      @success="handleContactSuccess"
    />
  </el-dialog>
</template>

<script>
import { getTkjlbList } from '@/api/lqTkjlb'
import { getLqEventList } from '@/api/lqEvent'
import InviteAddDialog from '@/components/InviteAddDialog.vue'

export default {
  name: 'TuokeListDialog',
  components: { InviteAddDialog },
  props: { visible: { type: Boolean, default: false } },
  data() {
    return {
      showAll: false,
      loading: false,
      eventLoading: false,
      eventList: [],
      list: [],
      total: 0,
      contactDialogVisible: false,
      contactCustomer: {},
      contactTkbh: '',
      query: {
        expansionTime: undefined,
        eventId: undefined,
        customerName: undefined,
        customerPhone: undefined,
        buyNumber: undefined,
        paymentMethod: undefined,
        isAddWeChat: undefined,
        teamName: undefined
      },
      listQuery: { currentPage: 1, pageSize: 10, sort: 'desc', sidx: '' },
      payMethodOptions: ['微信', '支付宝', '现金', '银行转账']
    }
  },
  computed: {
    visibleProxy: {
      get() { return this.visible },
      set(v) { this.$emit('update:visible', v) }
    },
    storeId() {
      return this.$store.getters.storeInfo?.storeId || ''
    }
  },
  watch: {
    visible(v) {
      if (v) {
        this.initData()
        this.getEventList()
      }
    }
  },
  methods: {
    formatEmpty(val) {
      if (val === undefined || val === null || String(val).trim() === '') return '无'
      return val
    },
    formatDate(ts) {
      if (!ts) return '-'
      if (typeof ts === 'string' && ts.includes('-')) {
        const part = ts.length >= 10 ? ts.substring(0, 16) : ts
        return part.replace('T', ' ')
      }
      const d = new Date(typeof ts === 'number' ? ts : Number(ts))
      if (isNaN(d.getTime())) return '-'
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const h = String(d.getHours()).padStart(2, '0')
      const min = String(d.getMinutes()).padStart(2, '0')
      return `${y}-${m}-${day} ${h}:${min}`
    },
    buildQueryParams() {
      const params = {
        ...this.listQuery,
        ...this.query,
        storeId: this.storeId
      }
      if (Array.isArray(params.expansionTime) && params.expansionTime.length === 2) {
        params.expansionTime = params.expansionTime.join(',')
      } else {
        delete params.expansionTime
      }
      Object.keys(params).forEach(key => {
        if (params[key] === undefined || params[key] === '' || params[key] === null) {
          delete params[key]
        }
      })
      return params
    },
    async getEventList() {
      this.eventLoading = true
      try {
        const res = await getLqEventList({ page: 1, rows: 500, sord: 'desc' })
        const rows = res.data?.list || []
        this.eventList = rows.map(event => ({
          id: event.id,
          eventName: event.eventNumber ? `${event.eventNumber} - ${event.eventName}` : event.eventName
        }))
      } catch (e) {
        this.eventList = []
      } finally {
        this.eventLoading = false
      }
    },
    async initData() {
      if (!this.storeId) {
        this.$message.warning('未获取到门店信息')
        return
      }
      this.loading = true
      try {
        const res = await getTkjlbList(this.buildQueryParams())
        this.list = res.data?.list || []
        this.total = res.data?.pagination?.total || 0
      } catch (e) {
        this.list = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    search() {
      this.listQuery.currentPage = 1
      this.initData()
    },
    reset() {
      Object.keys(this.query).forEach(k => {
        this.query[k] = undefined
      })
      this.listQuery = { currentPage: 1, pageSize: 10, sort: 'desc', sidx: '' }
      this.initData()
    },
    openContact(row) {
      const memberId = row.memberId || row.MemberId
      if (!memberId) {
        this.$message.warning('该拓客记录未关联会员，无法添加沟通记录')
        return
      }
      this.contactCustomer = {
        id: memberId,
        name: row.customerName || '',
        phone: row.customerPhone || ''
      }
      this.contactTkbh = row.id || ''
      this.contactDialogVisible = true
    },
    handleContactSuccess() {
      this.initData()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .tuoke-list-dialog { max-width: 1600px; margin-top: 3vh !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); backdrop-filter: blur(22px); -webkit-backdrop-filter: blur(22px); }
::v-deep .el-dialog__header { display: none; }
::v-deep .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(219,234,254,0.96); }
.dialog-title { font-size: 17px; font-weight: 600; color: #0f172a; }
.dialog-close { cursor: pointer; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; border-radius: 999px; color: #64748b; transition: all 0.15s; &:hover { background: rgba(0,0,0,0.06); color: #0f172a; } }
.dialog-search { flex-shrink: 0; padding: 12px 22px 4px; }
.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); }
::v-deep .tuoke-list-dialog .el-input__inner { border-radius: 999px; height: 32px; line-height: 32px; border-color: #e5e7eb; background-color: #f9fafb; &:focus { border-color: #2563eb; box-shadow: 0 0 0 1px rgba(37,99,235,0.18); } }
::v-deep .tuoke-list-dialog .el-button--primary { border-radius: 999px; background: #2563eb; border-color: #2563eb; box-shadow: 0 4px 10px rgba(37,99,235,0.35); }
::v-deep .tuoke-list-dialog .el-button--default { border-radius: 999px; }
::v-deep .tuoke-list-dialog .el-form-item { margin-bottom: 8px; }
::v-deep .tuoke-list-dialog .el-form-item__label { white-space: nowrap; }
::v-deep .tuoke-list-dialog .el-range-editor.el-input__inner { border-radius: 999px; }
</style>
