<template>
  <PageCard>
    <template #toolbar-left>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索账号 / 名称"
        clearable
        style="width: 240px"
      />
      <el-select v-model="filterStatus" placeholder="全部状态" clearable style="width: 140px">
        <el-option label="启用" :value="1" />
        <el-option label="禁用" :value="0" />
      </el-select>
    </template>
    <template #toolbar-right>
      <el-button type="primary" @click="openCreateDialog">新增账号</el-button>
    </template>

    <el-table :data="pagedAccounts" class="sino-table" @row-click="handleRowClick">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="accountType" label="类型" width="140">
        <template #default="{ row }">
          {{ accountTypeLabel(row.accountType) }}
        </template>
      </el-table-column>
      <el-table-column prop="channelType" label="渠道" width="100">
        <template #default="{ row }">
          {{ channelLabel(row.channelType) }}
        </template>
      </el-table-column>
      <el-table-column prop="accountId" label="账号ID" show-overflow-tooltip />
      <el-table-column prop="accountName" label="名称" show-overflow-tooltip />
      <el-table-column prop="loginStatus" label="登录状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.loginStatus === 1 ? 'success' : 'info'" size="small">
            {{ row.loginStatus === 1 ? '已登录' : '未登录' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="在线状态" width="160">
        <template #default="{ row }">
          <div class="online-status">
            <span class="status-dot" :class="row.onlineStatus === 1 ? 'online' : 'offline'" />
            {{ row.onlineStatus === 1 ? '在线' : '离线' }}
          </div>
          <div v-if="row.lastHeartbeat" class="heartbeat">{{ row.lastHeartbeat }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="90">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            size="small"
            @click.stop
            @change="(val: any) => handleStatusChange(row, val)"
          />
        </template>
      </el-table-column>
    </el-table>

    <template #pagination>
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="filteredAccounts.length"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, 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.accountType" placeholder="类型">
            <el-option label="企微内部账号" :value="1" />
            <el-option label="企微应用" :value="2" />
            <el-option label="pywechat 个人号" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="渠道">
          <el-input v-model="dialogForm.channelType" placeholder="wecom" />
        </el-form-item>
        <el-form-item label="所属主体">
          <el-select v-model="dialogForm.subjectId" placeholder="选择主体" clearable>
            <el-option
              v-for="s in subjects"
              :key="s.id"
              :label="s.subjectName"
              :value="s.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账号ID">
          <el-input v-model="dialogForm.accountId" placeholder="账号唯一标识" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="dialogForm.accountName" placeholder="名称" />
        </el-form-item>
        <el-form-item label="会话存档">
          <el-switch v-model="dialogForm.sessionArchiveEnabled" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="Server Host">
          <el-input v-model="dialogForm.serverHost" placeholder="服务地址" />
        </el-form-item>
        <el-form-item label="扩展信息">
          <el-input v-model="dialogForm.extInfo" type="textarea" :rows="3" placeholder="JSON 扩展信息" />
        </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="420px">
      <div class="drawer-body">
        <div class="drawer-actions">
          <el-button size="small" type="primary" @click="handleInit(currentAccount)">初始化</el-button>
          <el-button size="small" @click="handleSyncContacts(currentAccount)">同步联系人</el-button>
          <el-button size="small" @click="handleSync(currentAccount)">同步会话</el-button>
          <el-button size="small" @click="handleRefreshStatus(currentAccount)">刷新状态</el-button>
        </div>
        <el-form :model="drawerForm" label-width="120px">
          <el-form-item label="账号类型">
            <el-select v-model="drawerForm.accountType" placeholder="类型">
              <el-option label="企微内部账号" :value="1" />
              <el-option label="企微应用" :value="2" />
              <el-option label="pywechat 个人号" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="渠道">
            <el-input v-model="drawerForm.channelType" placeholder="wecom" />
          </el-form-item>
          <el-form-item label="所属主体">
            <el-select v-model="drawerForm.subjectId" placeholder="选择主体" clearable>
              <el-option
                v-for="s in subjects"
                :key="s.id"
                :label="s.subjectName"
                :value="s.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="账号ID">
            <el-input v-model="drawerForm.accountId" placeholder="账号唯一标识" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="drawerForm.accountName" placeholder="名称" />
          </el-form-item>
          <el-form-item label="会话存档">
            <el-switch v-model="drawerForm.sessionArchiveEnabled" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="Server Host">
            <el-input v-model="drawerForm.serverHost" placeholder="服务地址" />
          </el-form-item>
          <el-form-item label="扩展信息">
            <el-input v-model="drawerForm.extInfo" type="textarea" :rows="3" placeholder="JSON 扩展信息" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="drawer-footer">
          <el-button type="danger" plain @click="handleDelete(currentAccount)">删除</el-button>
          <div class="drawer-footer-right">
            <el-button @click="drawerVisible = false">取消</el-button>
            <el-button type="primary" @click="handleDrawerSave">保存</el-button>
          </div>
        </div>
      </template>
    </el-drawer>

    <el-dialog v-model="initDialogVisible" title="初始化结果" width="480px">
      <div v-if="initResult">
        <el-result
          :icon="initResult.success ? 'success' : 'warning'"
          :title="initResult.success ? '初始化成功' : '初始化失败'"
          :sub-title="initResult.message"
        />
        <div v-if="initResult.qrCodeUrl" class="qr-code">
          <p>请使用微信扫描二维码登录：</p>
          <el-image :src="initResult.qrCodeUrl" fit="contain" style="width: 200px; height: 200px" />
        </div>
      </div>
    </el-dialog>
  </PageCard>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listChannelSubjects } from '@/api/channelSubject'
import {
  createChannelAccount,
  listChannelAccounts,
  updateChannelAccount,
  deleteChannelAccount,
  updateChannelAccountStatus,
  getChannelAccountStatus,
  initChannelAccount,
  syncChannelAccountContacts,
  syncChannelAccountConversations,
} from '@/api/channelAccount'
import { getSyncTask } from '@/api/syncTask'
import PageCard from '@/components/PageCard.vue'

const accounts = ref<any[]>([])
const subjects = ref<any[]>([])
const dialogVisible = ref(false)

const dialogForm = reactive({
  accountType: 1,
  channelType: 'wecom',
  subjectId: undefined as number | undefined,
  accountId: '',
  accountName: '',
  sessionArchiveEnabled: 0,
  serverHost: '',
  extInfo: '',
})

const drawerVisible = ref(false)
const currentAccount = ref<any>({})
const drawerForm = reactive({
  accountType: 1,
  channelType: 'wecom',
  subjectId: undefined as number | undefined,
  accountId: '',
  accountName: '',
  sessionArchiveEnabled: 0,
  serverHost: '',
  extInfo: '',
})

const searchKeyword = ref('')
const filterStatus = ref<number | ''>('')
const page = ref(1)
const pageSize = ref(10)

const filteredAccounts = computed(() => {
  let list = accounts.value
  const kw = searchKeyword.value.trim().toLowerCase()
  if (kw) {
    list = list.filter(
      (item) =>
        (item.accountId || '').toLowerCase().includes(kw) ||
        (item.accountName || '').toLowerCase().includes(kw)
    )
  }
  if (filterStatus.value !== '') {
    list = list.filter((item) => item.status === filterStatus.value)
  }
  return list
})

const pagedAccounts = computed(() => {
  const start = (page.value - 1) * pageSize.value
  return filteredAccounts.value.slice(start, start + pageSize.value)
})

const initDialogVisible = ref(false)
const initResult = ref<any>(null)

function resetDialogForm() {
  dialogForm.accountType = 1
  dialogForm.channelType = 'wecom'
  dialogForm.subjectId = undefined
  dialogForm.accountId = ''
  dialogForm.accountName = ''
  dialogForm.sessionArchiveEnabled = 0
  dialogForm.serverHost = ''
  dialogForm.extInfo = ''
}

function resetDrawerForm() {
  drawerForm.accountType = 1
  drawerForm.channelType = 'wecom'
  drawerForm.subjectId = undefined
  drawerForm.accountId = ''
  drawerForm.accountName = ''
  drawerForm.sessionArchiveEnabled = 0
  drawerForm.serverHost = ''
  drawerForm.extInfo = ''
}

function fillDrawerForm(row: any) {
  drawerForm.accountType = row.accountType ?? 1
  drawerForm.channelType = row.channelType ?? 'wecom'
  drawerForm.subjectId = row.subjectId
  drawerForm.accountId = row.accountId ?? ''
  drawerForm.accountName = row.accountName ?? ''
  drawerForm.sessionArchiveEnabled = row.sessionArchiveEnabled ?? 0
  drawerForm.serverHost = row.serverHost ?? ''
  drawerForm.extInfo = row.extInfo ?? ''
}

function openCreateDialog() {
  resetDialogForm()
  dialogVisible.value = true
}

function handleRowClick(row: any) {
  currentAccount.value = row
  fillDrawerForm(row)
  drawerVisible.value = true
}

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

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

async function handleSave() {
  try {
    await createChannelAccount(dialogForm)
    ElMessage.success('创建成功')
    dialogVisible.value = false
    await loadAccounts()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleDrawerSave() {
  if (!currentAccount.value?.id) return
  try {
    await updateChannelAccount(currentAccount.value.id, drawerForm)
    ElMessage.success('更新成功')
    drawerVisible.value = false
    await loadAccounts()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleDelete(row: any) {
  if (!row?.id) return
  try {
    await ElMessageBox.confirm('确认删除该渠道账号？', '提示', { type: 'warning' })
    await deleteChannelAccount(row.id)
    ElMessage.success('删除成功')
    drawerVisible.value = false
    await loadAccounts()
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error(e.message)
    }
  }
}

async function handleStatusChange(row: any, val: any) {
  try {
    await updateChannelAccountStatus(row.id, { status: val })
    ElMessage.success('状态更新成功')
    await loadAccounts()
  } catch (e: any) {
    ElMessage.error(e.message)
    await loadAccounts()
  }
}

async function handleInit(row: any) {
  try {
    const res: any = await initChannelAccount({
      channelType: row.channelType,
      accountType: row.accountType,
      accountId: row.id,
      subjectId: row.subjectId,
      config: {},
    })
    initResult.value = res.data || null
    initDialogVisible.value = true
    if (initResult.value?.success) {
      await loadAccounts()
      await handleSyncContacts(row)
      await handleSync(row)
    }
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function pollTask(taskId: number, label: string) {
  const maxAttempts = 60
  for (let i = 0; i < maxAttempts; i++) {
    await new Promise((resolve) => setTimeout(resolve, 2000))
    try {
      const res: any = await getSyncTask(taskId)
      const task = res.data
      if (!task) continue
      if (task.taskStatus === 2) {
        ElMessage.success(`${label}同步完成，共 ${task.syncedCount ?? 0} 条`)
        return
      }
      if (task.taskStatus === 3) {
        ElMessage.error(`${label}同步失败：${task.errorMessage || '未知错误'}`)
        return
      }
    } catch (e: any) {
      // ignore polling error
    }
  }
  ElMessage.warning(`${label}同步时间较长，请稍后到列表查看`)
}

async function handleSyncContacts(row: any) {
  try {
    const res: any = await syncChannelAccountContacts(row.id)
    const taskId = res.data?.id
    if (taskId) {
      ElMessage.info('客户同步任务已提交')
      await pollTask(taskId, '客户')
    }
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleSync(row: any) {
  try {
    const res: any = await syncChannelAccountConversations(row.id)
    const taskId = res.data?.id
    if (taskId) {
      ElMessage.info('群聊同步任务已提交')
      await pollTask(taskId, '群聊')
    }
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleRefreshStatus(row: any) {
  try {
    const res: any = await getChannelAccountStatus(row.id)
    const idx = accounts.value.findIndex((a) => a.id === row.id)
    if (idx >= 0) {
      accounts.value[idx] = { ...accounts.value[idx], ...res.data }
    }
    ElMessage.success('状态已刷新')
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

function accountTypeLabel(type: number) {
  const map: Record<number, string> = {
    1: '企微内部账号',
    2: '企微应用',
    3: 'pywechat 个人号',
  }
  return map[type] || type
}

function channelLabel(type: string) {
  const map: Record<string, string> = {
    wecom: '企微',
    wechat_personal: '个微',
    dingtalk: '钉钉',
    feishu: '飞书',
    ivr: 'IVR',
  }
  return map[type] || type
}

onMounted(() => {
  loadAccounts()
  loadSubjects()
})
</script>

<style scoped>
.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}
.status-dot.online {
  background-color: #67c23a;
}
.status-dot.offline {
  background-color: #909399;
}
.heartbeat {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
.drawer-body {
  padding: 20px;
}
.drawer-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 8px;
}
.drawer-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
.drawer-footer-right {
  display: flex;
  gap: 8px;
}
.qr-code {
  text-align: center;
  margin-top: 12px;
}
</style>
