import { ref } from 'vue'
import { showError, showSuccess } from '@/lib/feedback'
import {
  appointAdminCloudtentaclesVn,
  backAdminCloudtentaclesVn,
  buyAdminCloudtentaclesSku,
  fetchAdminCloudtentaclesAsset,
  fetchAdminCloudtentaclesBindUrl,
  fetchAdminCloudtentaclesCategories,
  fetchAdminCloudtentaclesKnapsack,
  fetchAdminCloudtentaclesSkuList,
  fetchAdminCloudtentaclesVnCode,
  fetchAdminCloudtentaclesVnList,
  generateAdminCloudtentaclesVnLoginCode,
  runAdminCloudtentaclesFullFlow,
  useAdminCloudtentaclesSku,
  verifyAdminCloudtentaclesVnCode,
} from '@/services/admin'

export type CloudtentaclesForm = {
  baseUrl: string
  username: string
  password: string
  phone: string
  code: string
  token: string
  vnKey: string
  vnId: number
  skuId: number
  skuCount: number
  deviceId: string
  deviceType: number
}

export function useCloudtentaclesDebugActions(
  cloudtentaclesForm: { value: CloudtentaclesForm },
  cloudtentaclesResultError: { value: string },
  selectedSourceKey: { value: string },
) {
  const cloudtentaclesDebugLoading = ref(false)
  const cloudtentaclesDebugResult = ref('')

  function buildCloudtentaclesTokenPayload() {
    return {
      baseUrl: cloudtentaclesForm.value.baseUrl.trim() || 'https://123.207.217.176',
      token: cloudtentaclesForm.value.token.trim(),
      deviceId: cloudtentaclesForm.value.deviceId.trim() || '-',
      deviceType: Number(cloudtentaclesForm.value.deviceType || 0),
      sourceKey: selectedSourceKey.value,
    }
  }

  function ensureCloudtentaclesToken() {
    if (!cloudtentaclesForm.value.token.trim()) {
      cloudtentaclesResultError.value = '请先登录或手动填写 token'
      return false
    }
    return true
  }

  function renderCloudtentaclesDebugResult(label: string, data: unknown) {
    cloudtentaclesDebugResult.value = `${label}\n${JSON.stringify(data, null, 2)}`
  }

  async function runCloudtentaclesDebugAction(
    label: string,
    runner: () => Promise<{ data: unknown }>,
  ) {
    cloudtentaclesDebugLoading.value = true
    cloudtentaclesResultError.value = ''

    try {
      const response = await runner()
      renderCloudtentaclesDebugResult(label, response.data)
      showSuccess(`${label}成功`)
    } catch (error) {
      cloudtentaclesResultError.value = error instanceof Error ? error.message : `${label}失败`
      showError(cloudtentaclesResultError.value)
    } finally {
      cloudtentaclesDebugLoading.value = false
    }
  }

  async function handleCloudtentaclesFetchAsset() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('查询余额', () =>
      fetchAdminCloudtentaclesAsset(buildCloudtentaclesTokenPayload()),
    )
  }

  async function handleCloudtentaclesFetchCategories() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('查询分类', () =>
      fetchAdminCloudtentaclesCategories(buildCloudtentaclesTokenPayload()),
    )
  }

  async function handleCloudtentaclesFetchSkuList() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('查询SKU列表', () =>
      fetchAdminCloudtentaclesSkuList(buildCloudtentaclesTokenPayload()),
    )
  }

  async function handleCloudtentaclesBuySku() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('购买SKU', () =>
      buyAdminCloudtentaclesSku({
        ...buildCloudtentaclesTokenPayload(),
        id: Number(cloudtentaclesForm.value.skuId || 0),
        count: Number(cloudtentaclesForm.value.skuCount || 1),
      }),
    )
  }

  async function handleCloudtentaclesUseSku() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('执行发货', () =>
      useAdminCloudtentaclesSku({
        ...buildCloudtentaclesTokenPayload(),
        id: Number(cloudtentaclesForm.value.skuId || 0),
        virtualNumberId: Number(cloudtentaclesForm.value.vnId || 0),
        phone: cloudtentaclesForm.value.phone.trim(),
      }),
    )
  }

  async function handleCloudtentaclesFetchKnapsack() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('查询背包', () =>
      fetchAdminCloudtentaclesKnapsack(buildCloudtentaclesTokenPayload()),
    )
  }

  async function handleCloudtentaclesFetchVnList() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('查询虚拟号列表', () =>
      fetchAdminCloudtentaclesVnList({
        ...buildCloudtentaclesTokenPayload(),
        key: cloudtentaclesForm.value.vnKey.trim(),
      }),
    )
  }

  async function handleCloudtentaclesAppointVn() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('申请虚拟号', async () => {
      const response = await appointAdminCloudtentaclesVn({
        ...buildCloudtentaclesTokenPayload(),
        key: cloudtentaclesForm.value.vnKey.trim(),
      })
      const item = (response.data as { item?: { id?: number; phone?: string } }).item
      if (item?.id) {
        cloudtentaclesForm.value.vnId = Number(item.id)
      }
      if (item?.phone) {
        cloudtentaclesForm.value.phone = String(item.phone)
      }
      return response
    })
  }

  async function handleCloudtentaclesGenerateVnLoginCode() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('生成登录码', () =>
      generateAdminCloudtentaclesVnLoginCode({
        ...buildCloudtentaclesTokenPayload(),
        key: cloudtentaclesForm.value.vnKey.trim(),
        id: Number(cloudtentaclesForm.value.vnId || 0),
      }),
    )
  }

  async function handleCloudtentaclesFetchVnCode() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('获取验证码', async () => {
      const response = await fetchAdminCloudtentaclesVnCode({
        ...buildCloudtentaclesTokenPayload(),
        key: cloudtentaclesForm.value.vnKey.trim(),
        phone: cloudtentaclesForm.value.phone.trim(),
      })
      const code = (response.data as { code?: string }).code
      if (code) {
        cloudtentaclesForm.value.code = String(code)
      }
      return response
    })
  }

  async function handleCloudtentaclesVerifyVnCode() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('校验验证码', () =>
      verifyAdminCloudtentaclesVnCode({
        ...buildCloudtentaclesTokenPayload(),
        key: cloudtentaclesForm.value.vnKey.trim(),
        id: Number(cloudtentaclesForm.value.vnId || 0),
        code: cloudtentaclesForm.value.code.trim(),
      }),
    )
  }

  async function handleCloudtentaclesFetchBindUrl() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('获取兑换链接', () =>
      fetchAdminCloudtentaclesBindUrl({
        ...buildCloudtentaclesTokenPayload(),
        key: cloudtentaclesForm.value.vnKey.trim(),
        id: Number(cloudtentaclesForm.value.vnId || 0),
      }),
    )
  }

  async function handleCloudtentaclesBackVn() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('退还号码', () =>
      backAdminCloudtentaclesVn({
        ...buildCloudtentaclesTokenPayload(),
        key: cloudtentaclesForm.value.vnKey.trim(),
        id: Number(cloudtentaclesForm.value.vnId || 0),
      }),
    )
  }

  async function handleCloudtentaclesRunFullFlow() {
    if (!ensureCloudtentaclesToken()) return
    await runCloudtentaclesDebugAction('完整测试流程', () =>
      runAdminCloudtentaclesFullFlow({
        ...buildCloudtentaclesTokenPayload(),
        skuId: Number(cloudtentaclesForm.value.skuId || 0),
        skuCount: Number(cloudtentaclesForm.value.skuCount || 1),
        vnKey: cloudtentaclesForm.value.vnKey.trim(),
      }),
    )
  }

  return {
    cloudtentaclesDebugLoading,
    cloudtentaclesDebugResult,
    buildCloudtentaclesTokenPayload,
    ensureCloudtentaclesToken,
    handleCloudtentaclesFetchAsset,
    handleCloudtentaclesFetchCategories,
    handleCloudtentaclesFetchSkuList,
    handleCloudtentaclesBuySku,
    handleCloudtentaclesUseSku,
    handleCloudtentaclesFetchKnapsack,
    handleCloudtentaclesFetchVnList,
    handleCloudtentaclesAppointVn,
    handleCloudtentaclesGenerateVnLoginCode,
    handleCloudtentaclesFetchVnCode,
    handleCloudtentaclesVerifyVnCode,
    handleCloudtentaclesFetchBindUrl,
    handleCloudtentaclesBackVn,
    handleCloudtentaclesRunFullFlow,
  }
}
