<script setup>
import { getTicket } from '/@/views/test/api';
import sha1 from 'js-sha1';

// 生成时间戳
const stamp = Date.now();
const URL = 'http://asset.zositechc.cn/web/';
let jsapiTicket = '';
let signatureStr = '';
let signature = '';

// 生成随机字符串
function generateRandomString(length) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

// 异步获取 jsapiTicket
async function fetchJsapiTicket() {
  try {
    const response = await getTicket();
    jsapiTicket = response.data;
    generateSignatureStr(jsapiTicket);
  } catch (error) {
    console.error('Error==>', error);
  }
}

// 生成 signatureStr 字符串
function generateSignatureStr(ticket) {
  const nonceStr = generateRandomString(10);
  signatureStr = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${stamp}&url=${URL}`;
  // console.log("(index.vue: 37)=> signatureStr", signatureStr);
  signature = sha1(signatureStr);
  // console.log("(index.vue: 39)=> signature", signature);
}

// 在组件挂载时获取 jsapiTicket
onMounted(async () => {
  await fetchJsapiTicket();
});

// 配置企业微信 JS-SDK
window.wx.config({
  beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
  debug: true, // 在测试没问题之后，关闭debug模式，防止弹窗
  appId: 'ww467ec1685e8262e6', // 必填，企业微信的corpID
  timestamp: stamp, // 必填，生成签名的时间戳
  nonceStr: generateRandomString(10), // 必填，生成签名的随机串
  signature: signature, // 假设签名已经从后端获取
  jsApiList: ['agentConfig', 'saveApprovalSelectedItems', 'getApprovalSelectedItems'], // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
});
//
// 错误处理
window.wx.error((e) => {
  e && alert(JSON.stringify(e));
});
</script>


<template>

</template>
