<template>
  <PageCard>
    <template #toolbar-left>
      <el-input
        v-model="searchQuery"
        placeholder="搜索名称 / 渠道 / 会话ID"
        clearable
        style="width: 260px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="typeFilter" placeholder="全部类型" clearable style="width: 140px">
        <el-option label="单聊" :value="1" />
        <el-option label="群聊" :value="2" />
      </el-select>
    </template>
    <template #toolbar-right>
      <el-button type="primary" @click="openCreateDialog">新增会话</el-button>
    </template>

    <el-table :data="pagedConversations" class="sino-table" @row-click="openDrawer">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="conversationType" label="类型" width="100">
        <template #default="{ row }">
          {{ formatConversationType(row.conversationType) }}
        </template>
      </el-table-column>
      <el-table-column prop="channelType" label="渠道" />
      <el-table-column prop="channelConversationId" label="渠道会话ID" show-overflow-tooltip />
      <el-table-column prop="conversationName" label="名称" />
      <el-table-column prop="ownerAccountId" label="负责人">
        <template #default="{ row }">
          {{ formatAccountName(row.ownerAccountId) }}
        </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="filteredConversations.length"
        layout="total, prev, pager, next"
        background
      />
    </template>

    <el-dialog v-model="dialogVisible" title="新增会话" width="600px">
      <el-form :model="dialogForm" label-width="120px">
        <el-form-item label="会话类型">
          <el-select v-model="dialogForm.conversationType" placeholder="类型" style="width: 100%">
            <el-option label="单聊" :value="1" />
            <el-option label="群聊" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="渠道">
          <el-input v-model="dialogForm.channelType" placeholder="wecom" />
        </el-form-item>
        <el-form-item label="渠道会话ID">
          <el-input v-model="dialogForm.channelConversationId" placeholder="roomid_xxx" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="dialogForm.conversationName" placeholder="群名称" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="dialogForm.ownerAccountId" placeholder="选择负责人账号" style="width: 100%">
            <el-option
              v-for="a in accounts"
              :key="a.id"
              :label="a.accountName"
              :value="a.id"
            />
          </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="120px">
        <el-form-item label="会话类型">
          <el-select v-model="dialogForm.conversationType" placeholder="类型" style="width: 100%">
            <el-option label="单聊" :value="1" />
            <el-option label="群聊" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="渠道">
          <el-input v-model="dialogForm.channelType" placeholder="wecom" />
        </el-form-item>
        <el-form-item label="渠道会话ID">
          <el-input v-model="dialogForm.channelConversationId" :disabled="isEdit" placeholder="roomid_xxx" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="dialogForm.conversationName" placeholder="群名称" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="dialogForm.ownerAccountId" placeholder="选择负责人账号" style="width: 100%">
            <el-option
              v-for="a in accounts"
              :key="a.id"
              :label="a.accountName"
              :value="a.id"
            />
          </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="openBindAccount(currentConversation)">绑定账号</el-button>
          <el-button type="primary" link @click="openBindTags(currentConversation)">绑定标签</el-button>
        </div>
      </div>

      <el-divider />

      <div class="detail-section">
        <div class="section-title">群成员</div>
        <el-table :data="participants" class="sino-table" size="small" max-height="320">
          <el-table-column prop="participantType" label="类型" width="90">
            <template #default="{ row }">
              {{ formatParticipantType(row.participantType) }}
            </template>
          </el-table-column>
          <el-table-column prop="channelUserId" label="渠道用户ID" show-overflow-tooltip />
          <el-table-column prop="personName" label="姓名" show-overflow-tooltip />
          <el-table-column prop="personType" label="人员类型" width="100">
            <template #default="{ row }">
              {{ formatParticipantPersonType(row.personType) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-divider />

      <div class="detail-section">
        <div class="section-title">已绑定标签</div>
        <div v-if="boundTags.length" class="tag-list">
          <el-tag v-for="t in boundTags" :key="t.id" class="tag-item" size="small">
            {{ t.tagName }}
          </el-tag>
        </div>
        <el-empty v-else description="暂无标签" :image-size="60" />
      </div>

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

    <el-dialog v-model="bindAccountVisible" title="绑定账号" width="500px">
      <el-form :model="bindAccountForm" label-width="100px">
        <el-form-item label="账号">
          <el-select v-model="bindAccountForm.accountId" placeholder="选择账号" style="width: 100%">
            <el-option
              v-for="a in filteredBindAccounts"
              :key="a.id"
              :label="a.accountName"
              :value="a.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定类型">
          <el-select v-model="bindAccountForm.bindingType" 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-input-number v-model="bindAccountForm.sortOrder" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindAccountVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBindAccount">确认</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 {
  bindConversationAccount,
  bindConversationTags,
  createConversation,
  deleteConversation,
  listChannelAccounts,
  listConversationParticipants,
  listConversationTags,
  listConversations,
  updateConversation,
} from '@/api/channel'
import { listTags } from '@/api/crm'
import PageCard from '@/components/PageCard.vue'

const conversations = ref<any[]>([])
const accounts = ref<any[]>([])
const tags = ref<any[]>([])

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

const dialogForm = reactive({
  conversationType: 2,
  channelType: 'wecom',
  channelConversationId: '',
  conversationName: '',
  ownerAccountId: undefined as number | undefined,
  status: 1,
})

const searchQuery = ref('')
const typeFilter = ref<number | ''>('')
const currentPage = ref(1)
const pageSize = ref(10)
const drawerVisible = ref(false)
const currentConversation = ref<any>({})
const participants = ref<any[]>([])
const boundTags = ref<any[]>([])

const filteredConversations = computed(() => {
  const q = searchQuery.value.trim().toLowerCase()
  return conversations.value.filter((c) => {
    const matchesQuery =
      !q ||
      [c.conversationName, c.channelType, c.channelConversationId].some((v) =>
        String(v || '').toLowerCase().includes(q)
      )
    const matchesType =
      typeFilter.value === '' || c.conversationType === typeFilter.value
    return matchesQuery && matchesType
  })
})

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

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

function resetDialogForm() {
  dialogForm.conversationType = 2
  dialogForm.channelType = 'wecom'
  dialogForm.channelConversationId = ''
  dialogForm.conversationName = ''
  dialogForm.ownerAccountId = undefined
  dialogForm.status = 1
}

function fillDialogForm(row: any) {
  dialogForm.conversationType = row.conversationType ?? 2
  dialogForm.channelType = row.channelType ?? 'wecom'
  dialogForm.channelConversationId = row.channelConversationId ?? ''
  dialogForm.conversationName = row.conversationName ?? ''
  dialogForm.ownerAccountId = row.ownerAccountId
  dialogForm.status = row.status ?? 1
}

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

function openDrawer(row: any) {
  currentConversation.value = row
  currentBindConversation.value = row
  currentConversationId.value = row.id
  isEdit.value = true
  editingId.value = row.id
  fillDialogForm(row)
  drawerVisible.value = true
  loadParticipants(row.id)
  loadBoundTags(row.id)
}

const accountMap = computed(() => {
  const map = new Map<number, string>()
  for (const a of accounts.value) {
    map.set(a.id, a.accountName)
  }
  return map
})

function formatAccountName(id: number | undefined) {
  if (id == null) return '-'
  return accountMap.value.get(id) || id
}

const filteredBindAccounts = computed(() => {
  const channelType = currentBindConversation.value?.channelType
  if (!channelType) return accounts.value
  return accounts.value.filter((a: any) =>
    a.channelType?.toLowerCase() === channelType?.toLowerCase()
  )
})

function formatConversationType(type: number | undefined) {
  if (type === 1) return '单聊'
  if (type === 2) return '群聊'
  return type ?? '-'
}

function formatParticipantType(type: number | undefined) {
  if (type === 1) return '群主'
  return '成员'
}

function formatParticipantPersonType(type: number | undefined) {
  if (type === 3) return '客户'
  if (type == null) return '-'
  return '内部'
}

async function loadParticipants(conversationId: number | undefined) {
  if (!conversationId) {
    participants.value = []
    return
  }
  try {
    const res: any = await listConversationParticipants(conversationId)
    participants.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e.message)
    participants.value = []
  }
}

async function loadBoundTags(conversationId: number | undefined) {
  if (!conversationId) {
    boundTags.value = []
    return
  }
  try {
    const res: any = await listConversationTags(conversationId)
    boundTags.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e.message)
    boundTags.value = []
  }
}

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

async function loadAccounts() {
  try {
    const res: any = await listChannelAccounts()
    accounts.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.channelType || !dialogForm.channelConversationId) {
    ElMessage.warning('请填写渠道和渠道会话ID')
    return
  }
  try {
    const payload = {
      conversationType: dialogForm.conversationType,
      channelType: dialogForm.channelType,
      channelConversationId: dialogForm.channelConversationId,
      conversationName: dialogForm.conversationName,
      ownerAccountId: dialogForm.ownerAccountId,
      status: dialogForm.status,
    }
    if (isEdit.value && editingId.value != null) {
      await updateConversation(editingId.value, payload)
      ElMessage.success('更新成功')
    } else {
      const res: any = await createConversation(payload)
      conversations.value.unshift(res.data)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    drawerVisible.value = false
    await loadConversations()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleStatusChange(row: any, val: any) {
  try {
    await updateConversation(row.id, {
      conversationType: row.conversationType,
      channelType: row.channelType,
      channelConversationId: row.channelConversationId,
      conversationName: row.conversationName,
      ownerAccountId: row.ownerAccountId,
      status: val,
    })
    ElMessage.success('状态更新成功')
    await loadConversations()
  } catch (e: any) {
    ElMessage.error(e.message)
    await loadConversations()
  }
}

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

const bindAccountVisible = ref(false)
const currentBindConversation = ref<any>(null)
const bindAccountForm = reactive({
  accountId: undefined as number | undefined,
  bindingType: 1,
  sortOrder: 0,
})

function openBindAccount(row: any) {
  currentBindConversation.value = row
  bindAccountForm.accountId = undefined
  bindAccountForm.bindingType = 1
  bindAccountForm.sortOrder = 0
  bindAccountVisible.value = true
}

async function handleBindAccount() {
  if (!bindAccountForm.accountId || !currentBindConversation.value) {
    ElMessage.warning('请选择账号')
    return
  }
  try {
    await bindConversationAccount(currentBindConversation.value.id, bindAccountForm)
    ElMessage.success('绑定成功')
    bindAccountVisible.value = false
    await loadConversations()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

const currentConversationId = ref<number | undefined>()
const bindTagsVisible = ref(false)
const bindTagsForm = reactive({
  tagIds: [] as number[],
})

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

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

onMounted(() => {
  loadConversations()
  loadAccounts()
  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;
}

.detail-section {
  margin-bottom: 8px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  margin-right: 0;
}
</style>
