<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { leadApi, channelApi } from '@/api/crm.js'
import { userApi } from '@/api/system.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增线索')
const submitLoading = ref(false)
const followVisible = ref(false)
const assignVisible = ref(false)
const currentLead = ref(null)

const channels = ref([])
const users = ref([])

const searchForm = reactive({ name: '', phone: '', status: '', channel_id: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  id: null, channel_id: '', name: '', phone: '', wechat: '',
  expected_date: '', source: '', remark: ''
})
const isEdit = ref(false)
const formRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
}

const followForm = reactive({ type: 1, content: '', next_follow_at: '' })
const assignForm = reactive({ owner_id: '' })

const statusMap = { 1: '新建', 2: '跟进中', 3: '已转化', 4: '无效' }
const statusType = { 1: 'info', 2: 'warning', 3: 'success', 4: 'danger' }
const followTypeMap = { 1: '电话', 2: '微信', 3: '到店', 4: '其他' }

async function fetchList() {
  loading.value = true
  try {
    const res = await leadApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

async function fetchChannels() {
  try {
    const res = await channelApi.getList({ per_page: 200 })
    channels.value = res.data?.list || res.data?.data || []
  } catch {}
}

async function fetchUsers() {
  try {
    const res = await userApi.getList({ per_page: 200 })
    users.value = res.data?.list || res.data?.data || []
  } catch {}
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() {
  Object.assign(searchForm, { name: '', phone: '', status: '', channel_id: '' })
  handleSearch()
}

function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新增线索'
  Object.assign(form, { id: null, channel_id: '', name: '', phone: '', wechat: '', expected_date: '', source: '', remark: '' })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = '编辑线索'
  const res = await leadApi.getDetail(row.id)
  const d = res.data
  Object.assign(form, { id: d.id, channel_id: d.channel_id || '', name: d.name, phone: d.phone, wechat: d.wechat || '', expected_date: d.expected_date || '', source: d.source || '', remark: d.remark || '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) {
        await leadApi.update(form.id, form)
        ElMessage.success('更新成功')
      } else {
        await leadApi.create(form)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除线索「${row.name}」吗？`, '删除确认', { type: 'warning' })
  await leadApi.delete(row.id)
  ElMessage.success('删除成功')
  fetchList()
}

function openFollow(row) {
  currentLead.value = row
  Object.assign(followForm, { type: 1, content: '', next_follow_at: '' })
  followVisible.value = true
}

async function submitFollow() {
  if (!followForm.content) { ElMessage.warning('请输入跟进内容'); return }
  await leadApi.follow(currentLead.value.id, followForm)
  ElMessage.success('跟进记录已添加')
  followVisible.value = false
  fetchList()
}

function openAssign(row) {
  currentLead.value = row
  assignForm.owner_id = row.owner_id || ''
  assignVisible.value = true
}

async function submitAssign() {
  if (!assignForm.owner_id) { ElMessage.warning('请选择负责人'); return }
  await leadApi.assign(currentLead.value.id, assignForm)
  ElMessage.success('分配成功')
  assignVisible.value = false
  fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => { fetchList(); fetchChannels(); fetchUsers() })
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input v-model="searchForm.name" placeholder="姓名" style="width:160px" clearable @keydown.enter="handleSearch" />
      <el-input v-model="searchForm.phone" placeholder="手机号" style="width:160px" clearable @keydown.enter="handleSearch" />
      <el-select v-model="searchForm.channel_id" placeholder="渠道" clearable style="width:140px">
        <el-option v-for="c in channels" :key="c.id" :label="c.name" :value="c.id" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option label="新建" :value="1" /><el-option label="跟进中" :value="2" />
        <el-option label="已转化" :value="3" /><el-option label="无效" :value="4" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">线索列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增线索</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column prop="name" label="姓名" min-width="100" />
          <el-table-column prop="phone" label="手机号" min-width="130" />
          <el-table-column label="渠道" min-width="100">
            <template #default="{ row }">{{ row.channel?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="expected_date" label="预产期" min-width="110" />
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="负责人" min-width="100">
            <template #default="{ row }">{{ row.owner?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="260" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="success" text @click="openFollow(row)">跟进</el-button>
              <el-button size="small" type="warning" text @click="openAssign(row)">分配</el-button>
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,20,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>

    <!-- Add/Edit -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="姓名" prop="name"><el-input v-model="form.name" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="手机号" prop="phone"><el-input v-model="form.phone" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="微信号"><el-input v-model="form.wechat" /></el-form-item></el-col>
          <el-col :span="12">
            <el-form-item label="渠道">
              <el-select v-model="form.channel_id" placeholder="选择渠道" clearable style="width:100%">
                <el-option v-for="c in channels" :key="c.id" :label="c.name" :value="c.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"><el-form-item label="预产期"><el-date-picker v-model="form.expected_date" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="来源"><el-input v-model="form.source" /></el-form-item></el-col>
          <el-col :span="24"><el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="2" /></el-form-item></el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- Follow -->
    <el-dialog v-model="followVisible" title="添加跟进" width="500px" destroy-on-close>
      <el-form label-width="80px">
        <el-form-item label="跟进方式">
          <el-select v-model="followForm.type" style="width:100%">
            <el-option v-for="(v,k) in followTypeMap" :key="k" :label="v" :value="Number(k)" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进内容"><el-input v-model="followForm.content" type="textarea" :rows="3" /></el-form-item>
        <el-form-item label="下次跟进"><el-date-picker v-model="followForm.next_follow_at" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="followVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFollow">提交</el-button>
      </template>
    </el-dialog>

    <!-- Assign -->
    <el-dialog v-model="assignVisible" title="分配负责人" width="400px" destroy-on-close>
      <el-form label-width="80px">
        <el-form-item label="负责人">
          <el-select v-model="assignForm.owner_id" placeholder="选择负责人" filterable style="width:100%">
            <el-option v-for="u in users" :key="u.id" :label="u.name" :value="u.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAssign">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
