<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { createConnection, updateConnection, getWechatAuth } from '../api'
import type { DetailsProp, PlatformItem, ConfigAttribute } from '../types'

const StepOne = defineAsyncComponent(() => import('../components/StepOne.vue'))
const StepTwo = defineAsyncComponent(() => import('../components/StepTwo.vue'))
const WechatVideo = defineAsyncComponent(() => import('../components/WechatVideo.vue'))

const props = defineProps<{ data?: DetailsProp }>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const platformList: PlatformItem[] = [
  {
    type: '1',
    type_name: '公众号',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '' },
      // { label: '公众号类型', prop: 'type', value: '' },
      // { label: '授权方昵称', prop: 'nikeName', value: '' }
    ],
    async onBeforeNext(stepActive) {
      if (stepActive === 2) {
        const res = await handleSubmit()
        const { data } = await getWechatAuth({ connection_id: res.id, redirect_uri: location.href, auth_type: 1 })
        location.href = 'https://webapp-pub.ezijing.com/auth.html?redirect_uri=' + encodeURIComponent(data.url)
        return false
      }
      return true
    },
  },
  {
    type: '2',
    type_name: '钉钉',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '钉钉' },
      { label: 'AgentId', prop: 'agentId', value: '8441459810' },
      { label: 'AppKey', prop: 'appKey', value: 'dingigucs3beqlotpf24' },
      { label: 'AppSecret', prop: 'appSecret', value: '6dNRvuOzvX_xq5N9tFdjepdf3FeooN25yUZK6ammDbPUVq9sfdXD-sKUg' },
    ],
  },
  {
    type: '3',
    type_name: '小鹅通',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '小鹅通' },
      { label: 'app_id', prop: 'app_id', value: 'appc4bolgenF58' },
      { label: 'client_id', prop: 'client_id', value: '_5e7f809dd6317_qSMuUoAi?type=2SDK' },
      { label: 'secret_key', prop: 'secret_key', value: 'xiao_5ac1dd24803ae_GtfAOxiS1pdf3FeooN2huhu92WRE52S-SkOh' },
    ],
  },
  {
    type: '4',
    type_name: '问卷星',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '问卷星' },
      { label: 'AppKey', prop: 'appKey', value: '82286f9c5114dc2bda214cd9567dodc' },
      { label: 'AppSecret', prop: 'appSecret', value: 'pages/wjxqList/wjxqList?activityId= P251FBP' },
    ],
  },
  { type: '5', type_name: '今日头条', config_attributes: [{ label: '连接名称', prop: 'name', value: '今日头条' }] },
  {
    type: '6',
    type_name: '抖音',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '抖音' },
      { label: '应用类别', prop: 'dyInput1', value: '短视频分享与社交平台' },
      { label: '授权域回调', prop: 'dyInput2', value: 'https://douyin.xiaokefu.com.cn/douYin/push/19872884' },
      {
        label: '网站应用简介',
        prop: 'dyInput3',
        value:
          '不仅是下载抖音应用程序的官方渠道，也是一个展示抖音最新动态、功能更新和推广活动的平台。用户可以通过官网了解抖音的特色功能、查看热门视频、参与互动活动，以及获取帮助和教程等。官网还为创作者和企业提供了一个展示空间，让他们了解如何利用抖音平台进行内容创作、品牌推广和电子商务等。',
      },
      { label: '应用官网', prop: 'dyInput4', value: 'https://www.douyin.com' },
      { label: '联系人姓名', prop: 'dyInput5', value: '清控紫荆（北京）教育股份有限公司' },
    ],
  },
  {
    type: '7',
    type_name: '微博',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '微博' },
      { label: 'AppKey', prop: 'appKey', value: '1206405345' },
      { label: 'AppSecret', prop: 'appSecret', value: '6a6095e113cd28fde6e14c7b7145c5c5' },
    ],
  },
  {
    type: '8',
    type_name: '小红书',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '小红书' },
      { label: 'AppKey', prop: 'appKey', value: '6c1dd8dd64d074d56124c751f6bc240b' },
      { label: 'AppSecret', prop: 'appSecret', value: '' },
    ],
  },
  {
    type: '9',
    type_name: '邮箱',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '邮箱' },
      { label: 'client_id', prop: 'client_id', value: 'swanzhong' },
      { label: 'client_secret', prop: 'client_secret', value: '563a8c6a89d2368194c1c7889c508b34' },
      { label: 'token URL', prop: 'token', value: 'openapi/user/get' },
      { label: 'API URL', prop: 'apiUrl', value: 'openapi/user/check' },
    ],
  },
  {
    type: '10',
    type_name: '短信',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '短信' },
      { label: 'client_id', prop: 'client_id', value: 'FbFgN2of-mlc' },
      { label: 'SdkAppId', prop: 'sdkAppId', value: 'CV3X1%2FJG7mdNZm03l9puvwPAktmfw1aj8XvBb6sm696MqoW57' },
      { label: 'token URL', prop: 'token', value: 'https://oauth-login.cloud.ali.com/oauth2/v3/token' },
      { label: 'API URL', prop: 'apiUrl', value: 'oauth2v3wPAktm' },
    ],
  },
  { type_name: '内部消息', type: '11', config_attributes: [{ label: '连接名称', prop: 'name', value: '内部消息' }] },
  {
    type: '12',
    type_name: '自定义',
    config_attributes: [
      { label: '连接名称', prop: 'name', value: '自定义' },
      { label: 'APP类型', prop: 'appType', value: '自定义' },
      { label: 'AppId', prop: 'appId', value: 'Custom App ID' },
    ],
  },
  {
    type: '13',
    type_name: '紫荆表单',
    icon: '99',
    config_attributes: [{ label: '连接名称', prop: 'name', value: '紫荆表单' }],
  },
  {
    type: '14',
    type_name: '小程序',
    icon: '100',
    config_attributes: [{ label: '连接名称', prop: 'name', value: '小程序' }],
    async onBeforeNext(stepActive) {
      if (stepActive === 2) {
        const res = await handleSubmit()
        const { data } = await getWechatAuth({ connection_id: res.id, redirect_uri: location.href, auth_type: 2 })
        location.href = data.url
        return false
      }
      return true
    },
  },
  {
    icon: 'mall',
    type: '15',
    type_name: '紫荆商城',
    config_attributes: [{ label: '连接名称', prop: 'name', value: '紫荆商城' }],
  },
  {
    icon: 'wechatVideo',
    type: '16',
    type_name: '视频号',
    config_attributes: [{ label: '连接名称', prop: 'name', value: '视频号' }],
    async onBeforePrev(stepActive) {
      if (stepActive == 2) {
        return wechatVideoRef.value?.handlePrev()
      }
      return true
    },
    async onBeforeNext(stepActive) {
      if (stepActive == 2) {
        return wechatVideoRef.value?.handleNext()
      }
      return true
    },
  },
]

// 请求参数
const params: { type: string; config_attributes: ConfigAttribute[] } = reactive({ type: '1', config_attributes: [] })
watchEffect(() => {
  if (!props.data) return
  const { type, config_attributes } = props.data
  let attributes = []
  if (Array.isArray(config_attributes)) {
    attributes = config_attributes
  } else if (typeof config_attributes === 'string') {
    attributes = JSON.parse(config_attributes)
  }
  Object.assign(params, { type, config_attributes: attributes })
})

const selectedItem = computed(() => platformList.find((item) => item.type === params.type))

const defaultStepActive = props.data?.id ? 2 : 1
const stepActive = ref(defaultStepActive)
const stepLength = 3

function handleChange(data: PlatformItem) {
  params.config_attributes = data.config_attributes || []
}

// 上一步
async function handlePrev() {
  if (selectedItem.value?.onBeforePrev) {
    const next = await selectedItem.value?.onBeforePrev(stepActive.value, selectedItem.value)
    if (!next) return
  }
  stepActive.value--
}

// 下一步
async function handleNext() {
  const isEmpty = params.config_attributes.find((item) => item.value === '')
  if (isEmpty && stepActive.value === 2) {
    ElMessage('请填写完整')
    return
  }
  if (selectedItem.value?.onBeforeNext) {
    const next = await selectedItem.value?.onBeforeNext(stepActive.value, selectedItem.value)
    if (!next) return
  }
  stepActive.value++
}

// 第三步成功弹窗
function handleTest() {
  const typeName = selectedItem.value?.type_name
  if (typeName) ElMessageBox.alert(`成功连接${typeName}`, '提示', { confirmButtonText: 'OK' })
}

// 提交
async function handleSubmit() {
  if (props.data?.id) {
    await updateConnection({ id: props.data.id, ...params })
    return props.data
  } else {
    const res = await createConnection(params)
    return res.data.detail
  }
}
async function handleSave() {
  await handleSubmit()
  ElMessage({ message: props.data?.id ? '保存成功' : '修改成功', type: 'success' })
  emit('update')
  emit('update:modelValue', false)
}

const wechatVideoRef = ref<any>(null)
</script>

<template>
  <el-dialog
    class="connect-form"
    :title="props.data?.id ? '编辑连接' : '新建连接'"
    :close-on-click-modal="false"
    width="1050px"
    @closed="$emit('update:modelValue', false)">
    <el-tabs v-model="stepActive" class="demo-tabs">
      <!-- 第一步 -->
      <el-tab-pane disabled lazy label="选择连接类型" :name="1" v-if="!props.data?.id">
        <StepOne :platformList="platformList" v-model="params.type" @change="handleChange"></StepOne>
      </el-tab-pane>
      <!-- 第二步 -->
      <el-tab-pane disabled lazy label="配置连接信息" :name="2">
        <template v-if="selectedItem">
          <WechatVideo
            ref="wechatVideoRef"
            v-model="params.config_attributes"
            v-if="params.type === '16'"></WechatVideo>
          <StepTwo :platform="selectedItem" v-model="params.config_attributes" v-else></StepTwo>
        </template>
      </el-tab-pane>
      <el-tab-pane disabled lazy label="测试连接" :name="3">
        <el-button type="primary" @click="handleTest">测试连接</el-button>
      </el-tab-pane>
    </el-tabs>
    <div class="button-flex">
      <el-button type="primary" @click="handlePrev" v-if="stepActive !== defaultStepActive">上一步</el-button>
      <el-button type="primary" @click="handleNext" v-if="stepActive < stepLength">下一步</el-button>
      <el-button type="primary" @click="handleSave" v-if="stepActive === stepLength">保存</el-button>
    </div>
  </el-dialog>
</template>
<style lang="scss">
.connect-form {
  .el-dialog__body {
    padding-top: 10px;
  }
}
.button-flex {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}
</style>
