<template>
  <PageCard>
    <template #toolbar-left>
      <el-input
        v-model="searchQuery"
        placeholder="搜索姓名 / 手机 / 编码"
        clearable
        style="width: 260px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="personTypeFilter" placeholder="全部类型" clearable style="width: 140px">
        <el-option label="内部人员" :value="1" />
        <el-option label="供应商人员" :value="2" />
        <el-option label="客户" :value="3" />
        <el-option label="司机" :value="4" />
      </el-select>
    </template>
    <template #toolbar-right>
      <el-button type="primary" @click="openCreateDialog">新增联系人</el-button>
    </template>

    <el-table :data="pagedPersons" class="sino-table" @row-click="openDrawer">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="personCode" label="编码" />
      <el-table-column prop="personName" label="姓名" />
      <el-table-column prop="phone" label="手机" />
      <el-table-column prop="personType" label="类型" width="120">
        <template #default="{ row }">
          {{ formatPersonType(row.personType) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <div class="status-cell" @click.stop>
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val: any) => handleStatusChange(row, val)"
            />
            <span class="status-text">{{ row.status === 1 ? '启用' : '禁用' }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <template #pagination>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="filteredPersons.length"
        layout="total, prev, pager, next"
        background
      />
    </template>

    <el-dialog v-model="dialogVisible" title="新增联系人" width="600px">
      <el-form :model="dialogForm" label-width="100px">
        <el-form-item label="编码">
          <el-input v-model="dialogForm.personCode" placeholder="人员编码" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="dialogForm.personName" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input v-model="dialogForm.phone" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="dialogForm.personType" placeholder="类型" style="width: 100%">
            <el-option label="内部人员" :value="1" />
            <el-option label="供应商人员" :value="2" />
            <el-option label="客户" :value="3" />
            <el-option label="司机" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="dialogForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <el-drawer v-model="drawerVisible" title="联系人详情" size="520px">
      <el-form :model="dialogForm" label-width="100px">
        <el-form-item label="编码">
          <el-input v-model="dialogForm.personCode" placeholder="人员编码" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="dialogForm.personName" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input v-model="dialogForm.phone" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="dialogForm.personType" placeholder="类型" style="width: 100%">
            <el-option label="内部人员" :value="1" />
            <el-option label="供应商人员" :value="2" />
            <el-option label="客户" :value="3" />
            <el-option label="司机" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="dialogForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <el-divider />

      <div class="relation-section">
        <div class="section-title">关联信息</div>
        <div class="relation-actions">
          <el-button type="primary" link @click="openIdentities(currentPerson)">管理渠道身份</el-button>
          <el-button type="primary" link @click="openBindTags(currentPerson)">绑定标签</el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDelete(currentPerson)">删除</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-drawer>

    <el-dialog v-model="identitiesVisible" title="渠道身份" width="700px">
      <el-table :data="identities" class="sino-table" border style="margin-bottom: 16px;">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="channelType" label="渠道" />
        <el-table-column prop="channelUserId" label="渠道用户ID" />
        <el-table-column prop="channelUserName" label="渠道用户名" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button link type="danger" size="small" @click="handleDeleteIdentity(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-divider />
      <el-form :model="identityForm" label-width="100px">
        <el-form-item label="渠道">
          <el-input v-model="identityForm.channelType" placeholder="wecom" />
        </el-form-item>
        <el-form-item label="渠道用户ID">
          <el-input v-model="identityForm.channelUserId" placeholder="渠道用户ID" />
        </el-form-item>
        <el-form-item label="渠道用户名">
          <el-input v-model="identityForm.channelUserName" placeholder="渠道用户名" />
        </el-form-item>
        <el-form-item label="主体ID">
          <el-input-number v-model="identityForm.subjectId" :min="0" :controls="false" placeholder="主体ID" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="identitiesVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleCreateIdentity">新增身份</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="bindTagsVisible" title="绑定标签" width="500px">
      <el-form :model="bindTagsForm" label-width="80px">
        <el-form-item label="标签">
          <el-select v-model="bindTagsForm.tagIds" multiple placeholder="选择标签" style="width: 100%">
            <el-option
              v-for="t in tags"
              :key="t.id"
              :label="t.tagName"
              :value="t.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindTagsVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBindTags">确认</el-button>
      </template>
    </el-dialog>
  </PageCard>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  bindPersonTags,
  createPerson,
  createPersonIdentity,
  deletePerson,
  deletePersonIdentity,
  listPersonIdentities,
  listPersons,
  listTags,
  updatePerson,
} from '@/api/crm'
import PageCard from '@/components/PageCard.vue'

const persons = ref<any[]>([])
const tags = ref<any[]>([])

const dialogVisible = ref(false)
const isEdit = ref(false)
const editingId = ref<number | null>(null)

const dialogForm = reactive({
  personCode: '',
  personName: '',
  phone: '',
  personType: 3,
  status: 1,
})

const searchQuery = ref('')
const personTypeFilter = ref<number | ''>('')
const currentPage = ref(1)
const pageSize = ref(10)
const drawerVisible = ref(false)
const currentPerson = ref<any>({})

const filteredPersons = computed(() => {
  const q = searchQuery.value.trim().toLowerCase()
  return persons.value.filter((p) => {
    const matchesQuery =
      !q ||
      [p.personName, p.phone, p.personCode].some((v) =>
        String(v || '').toLowerCase().includes(q)
      )
    const matchesType =
      personTypeFilter.value === '' || p.personType === personTypeFilter.value
    return matchesQuery && matchesType
  })
})

const pagedPersons = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredPersons.value.slice(start, start + pageSize.value)
})

watch([searchQuery, personTypeFilter], () => {
  currentPage.value = 1
})

function resetDialogForm() {
  dialogForm.personCode = ''
  dialogForm.personName = ''
  dialogForm.phone = ''
  dialogForm.personType = 3
  dialogForm.status = 1
}

function fillDialogForm(row: any) {
  dialogForm.personCode = row.personCode ?? ''
  dialogForm.personName = row.personName ?? ''
  dialogForm.phone = row.phone ?? ''
  dialogForm.personType = row.personType ?? 3
  dialogForm.status = row.status ?? 1
}

function openCreateDialog() {
  isEdit.value = false
  editingId.value = null
  resetDialogForm()
  dialogVisible.value = true
}

function openDrawer(row: any) {
  currentPerson.value = row
  currentPersonId.value = row.id
  isEdit.value = true
  editingId.value = row.id
  fillDialogForm(row)
  drawerVisible.value = true
}

function formatPersonType(type: number | undefined) {
  if (type === 3) return '客户'
  if (type === 1 || type === 2 || type === 4) return '员工'
  return '未知'
}

async function loadPersons() {
  try {
    const res: any = await listPersons()
    persons.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function loadTags() {
  try {
    const res: any = await listTags()
    tags.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleSave() {
  if (!dialogForm.personName) {
    ElMessage.warning('请填写姓名')
    return
  }
  try {
    const payload = {
      personCode: dialogForm.personCode,
      personName: dialogForm.personName,
      phone: dialogForm.phone,
      personType: dialogForm.personType,
      status: dialogForm.status,
    }
    if (isEdit.value && editingId.value != null) {
      await updatePerson(editingId.value, payload)
      ElMessage.success('更新成功')
    } else {
      const res: any = await createPerson(payload)
      persons.value.unshift(res.data)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    drawerVisible.value = false
    await loadPersons()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleStatusChange(row: any, val: any) {
  try {
    await updatePerson(row.id, {
      personCode: row.personCode,
      personName: row.personName,
      phone: row.phone,
      personType: row.personType,
      status: val,
    })
    ElMessage.success('状态更新成功')
    await loadPersons()
  } catch (e: any) {
    ElMessage.error(e.message)
    await loadPersons()
  }
}

async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm(
      `确定删除联系人「${row.personName || row.personCode}」吗？`,
      '删除确认',
      { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' }
    )
    await deletePerson(row.id)
    ElMessage.success('删除成功')
    drawerVisible.value = false
    await loadPersons()
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error(e.message || '删除失败')
    }
  }
}

const identitiesVisible = ref(false)
const identities = ref<any[]>([])
const currentPersonId = ref<number | undefined>()
const identityForm = reactive({
  channelType: '',
  channelUserId: '',
  channelUserName: '',
  subjectId: undefined as number | undefined,
})

function resetIdentityForm() {
  identityForm.channelType = ''
  identityForm.channelUserId = ''
  identityForm.channelUserName = ''
  identityForm.subjectId = undefined
}

async function openIdentities(row: any) {
  currentPersonId.value = row.id
  identitiesVisible.value = true
  resetIdentityForm()
  await loadIdentities()
}

async function loadIdentities() {
  if (!currentPersonId.value) return
  try {
    const res: any = await listPersonIdentities(currentPersonId.value)
    identities.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleCreateIdentity() {
  if (!currentPersonId.value) return
  if (!identityForm.channelType || !identityForm.channelUserId) {
    ElMessage.warning('请填写渠道和渠道用户ID')
    return
  }
  try {
    const payload: any = {
      channelType: identityForm.channelType,
      channelUserId: identityForm.channelUserId,
      channelUserName: identityForm.channelUserName,
    }
    if (identityForm.subjectId != null) {
      payload.subjectId = identityForm.subjectId
    }
    await createPersonIdentity(currentPersonId.value, payload)
    ElMessage.success('新增成功')
    resetIdentityForm()
    await loadIdentities()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleDeleteIdentity(row: any) {
  if (!currentPersonId.value) return
  try {
    await ElMessageBox.confirm('确定删除该渠道身份吗？', '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deletePersonIdentity(currentPersonId.value, row.id)
    ElMessage.success('删除成功')
    await loadIdentities()
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error(e.message || '删除失败')
    }
  }
}

const bindTagsVisible = ref(false)
const bindTagsForm = reactive({
  tagIds: [] as number[],
})

function openBindTags(row: any) {
  currentPersonId.value = row.id
  bindTagsForm.tagIds = []
  bindTagsVisible.value = true
}

async function handleBindTags() {
  if (!currentPersonId.value) return
  try {
    await bindPersonTags(currentPersonId.value, { tagIds: bindTagsForm.tagIds })
    ElMessage.success('绑定成功')
    bindTagsVisible.value = false
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

onMounted(() => {
  loadPersons()
  loadTags()
})
</script>

<style scoped>
.relation-section {
  margin-top: 8px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #0F172A;
  margin-bottom: 12px;
}

.relation-actions {
  display: flex;
  gap: 16px;
}
</style>
