<script setup>
import { onMounted, onUnmounted } from 'vue'
import CktDesign from '@chuangkit/chuangkit-design'
import md5 from 'blueimp-md5'
import { useUserStore } from '@/stores/user'
import { uploadFileByUrl } from '@/utils/upload'

const props = defineProps({ kindId: { type: Number, default: 447 } })
const model = defineModel()
const emit = defineEmits(['close', 'save'])

const userStore = useUserStore()

/**
 * 构建签名
 * @param obj 参数对象，对象中的所有属性全部参与签名的生成
 * @returns {string} 签名
 */
const buildSign = (obj) => {
  const signParameterArray = []
  for (const key in obj) {
    signParameterArray.push(`${key}=${obj[key]}`)
  }

  const signPlaintext = signParameterArray.sort().join('&')
  return md5(signPlaintext).toUpperCase()
}

/**
 * 构建2.0版本签名
 * @param appId 第三方企业id
 * @param expireTime 时间戳，取当前时间即可
 * @param userFlag 用户标记
 * @param appSecret 企业密钥
 * @returns {string} 签名
 */
const buildVersion2Sign = (appId, expireTime, userFlag, appSecret) => {
  const signParameterObj = {
    app_id: appId,
    expire_time: expireTime,
    user_flag: userFlag,
    app_secret: appSecret,
  }

  return buildSign(signParameterObj)
}

window.chuangkitComplete = async (result) => {
  console.log(result)
  if (!result.cktMessage) {
    return
  }
  if (result.kind == 2) {
    for (const url of result['source-urls']) {
      const uploadedURL = await uploadFileByUrl(url)
      model.value = uploadedURL
    }
    emit('save', model.value)
  }
  if ([1, 2, 3].includes(result.kind)) {
    emit('close')
  }
}

let cktInstance
function openDesignPage() {
  const appId = '54d9adec77d0402794018d166110f3dd'
  const appSecret = '08097010E0EF4B85EE2B8CE438328249'
  const userFlag = userStore.user.id
  const expireTime = Date.now()
  const sign = buildVersion2Sign(appId, expireTime, userFlag, appSecret)
  const params = {
    app_id: appId,
    expire_time: expireTime,
    user_flag: userFlag,
    device_type: 1,
    kind_id: props.kindId,
    version: '2.0',
    sign: sign,
    enable_authorize: '1',
    taxpayer_name: 'chuangkit',
    taxpayer_phone: '13820659475',
    taxpayer_number: '91120116636067462H',
  }

  cktInstance = new CktDesign(params)
  cktInstance.open()
  console.log(cktInstance)
}

function closeDesignPage() {
  if (cktInstance) {
    cktInstance.close()
  }
}

onMounted(() => openDesignPage())
onUnmounted(() => closeDesignPage())
</script>

<template>
  <div id="ckt-design-page"></div>
</template>
