<template>
  <web-view class="webview" @message="webLoad" style="flex: 1;" :src="config.h5Url"></web-view>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { onExit, onShow } from "@dcloudio/uni-app";
import config from "../../config"
import { operateSQLite } from '../../utils/sqlite.js'
onShow(() => {
  // const { statusBarHeight } = uni.getSystemInfoSync()
  // const wv1 = plus.webview.getWebviewById("custom-webview");
  // let wv = null;
  // if (wv1) {
  //   wv = wv1;
  // } else {
  //   wv = plus.webview.create(config.h5Url, "custom-webview", {
  //     top: statusBarHeight,
  //     bottom: 0,
  //   });
  // }
  // var pages = getCurrentPages();
  // var page = pages[pages.length - 1];
  // var currentWebview = page.$getAppWebview();


  
})
import { Communication } from '../../utils/communication.js';
const commun = new Communication()
const shareH5 = () => {
  uni.share({
    provider: 'weixin',
    scene: "WXSceneSession",
    type: 0,// 5代表分享为小程序
    imageUrl: 'https://th.bing.com/th?id=ORMS.41c34644e7e67f95a14620e77064b5d9&pid=Wdp&w=268&h=140&qlt=90&c=1&rs=1&dpr=1&p=0', // 必填
    title: '分享的标题',
    href: 'https://www.baidu.com/',
    success: function (res) {
      console.log("success:" + JSON.stringify(res));
    },
    fail: function (err) {
      console.log("fail:" + JSON.stringify(err));
    }
  });
}
//#ifdef APP-ANDROID
import {
  registerRequestPermissionTipsListener,
  unregisterRequestPermissionTipsListener,
  setRequestPermissionTips
} from "@/uni_modules/uni-registerRequestPermissionTips"

const PermissionTips = {
  "android.permission.READ_PHONE_STATE": "<h4 style=\"font-size:40px;\">正在读取网络状态权限</h4><font color=#cccccc>通讯录权限不会获取任何信息,请注意通讯录权限不会获取任何信息,请注意通讯录权限不会获取任何信息,请注意</font>",
  "android.permission.CAMERA": "<h4 style=\"font-size:40px;\">正在访问相机权限</h4><font color=#cccccc>需要扫描二维码或拍照,是否允许打开相机?</font>",
  "android.permission.WRITE_EXTERNAL_STORAGE": "<h4 style=\"font-size:40px;\">正在读取相册权限</h4><font color=#cccccc>我们需要获取访问您设备相册的权限,以便您能够选择并上传图片或视频到我们的应用中。</font>",
  "android.permission.ACCESS_FINE_LOCATION": "<h4 style=\"font-size:40px;\">正在访问位置权限</h4><font color=#cccccc>需要获取您的位置信息,以便您能够进行考勤打卡。</font>",
  "android.permission.ACCESS_COARSE_LOCATION": "<h4 style=\"font-size:40px;\">正在访问位置权限</h4><font color=#cccccc>需要获取您的位置信息,以便您能够进行考勤打卡。</font>"
}
onExit(() => {
  unregisterRequestPermissionTipsListener()
})

const brand = uni.getSystemInfoSync().deviceBrand
setRequestPermissionTips(PermissionTips)
registerRequestPermissionTipsListener({
  onRequest: (e) => {
    console.log('onRequest', e)
  },
  onConfirm: (e) => {
    // commun.sendToH5('permission-application', { action: 'open-permission', data: e });
  },
  onComplete: (e) => {
    commun.sendToH5('permission-application', { action: 'close-permission', data: e });

    // 华为手机在权限禁止之后,再次申请权限不会出现权限申请框。此时应该引导用户去系统设置开启此权限,不应该频繁申请。
    if (brand.toLowerCase() === "huawei") {
      const tips = {}
      let hasDeniedPermission = false
      for (let k in PermissionTips) {
        if (e[k] !== "denied") {
          tips[k] = PermissionTips[k]
        } else {
          hasDeniedPermission = true
        }
      }
      setRequestPermissionTips(tips) // 更新弹框提醒,防止华为手机不出现权限申请框时权限提醒框闪烁的情况
      if (hasDeniedPermission)
        uni.showModal({
          content: "权限已经被拒绝,请前往设置中开启"
        })
    }
  }
})
//#endif
const webLoad = (e) => {
  const message = e.detail.data?.[0] || '';
  commun.handleMessage(message);
};
function initializeWebView() {
  const currentWebview = getCurrentPages().pop().$getAppWebview()
  commun.setWebView(currentWebview.children()[0])
}
//load-complete 注册函数
commun.registerHandler('load-complete', () => {

  initializeWebView()
  const { statusBarHeight } = uni.getSystemInfoSync()
  commun.webViewObj.setStyle({
    top: statusBarHeight,
    bottom: 0,
  })

})

commun.registerHandler('getLocation', (data) => {
  uni.getLocation({
    type: 'gcj02',
    geocode: true,
    isHighAccuracy: true,
    ...data,
    success: (res) => {
      console.log('getLocation', res)
      commun.sendToH5('getLocation', res);
    },
  })
})
commun.registerHandler('goCard', async (data) => {
  await getCard(data.phone)
})

commun.registerHandler('createPushMessage', async (data) => {
  uni.createPushMessage(JSON.parse(decodeURIComponent(data)))
})

commun.registerHandler('operateSQLite', async (data) => {
  operateSQLite(data)
})

commun.registerHandler('VideoPicker', async () => {
  console.error('=======BASE==VideoPicker')
  console.error(uni.getSystemInfoSync().osName)
  if (uni.getSystemInfoSync().osName === 'ios') {
    //调用IOS原生视频多选插件
    uni
      .requireNativePlugin('VideoPickerUniPlugin-VideoPickerModule')
      .pickVideos(
        { maxCount: 9 },
        (res) => {
          console.log('选中的视频列表:', res.videoList)
          let allWebview = plus.webview.all()
          allWebview.forEach((webview) => {
            if (webview.id === 'chat') {
              //找到聊天的webview
              console.log('找到聊天的webview', webview)
              webview.evalJS(
                `getBaseMulVideo('${encodeURIComponent(
                  JSON.stringify(res.videoList),
                )}')`,
              )
            }
          })
        },
        (ret) => {
          console.error('调用异步方法 ' + ret)
        },
      )
  } else {
    //调用安卓原生视频多选插件
    uni.requireNativePlugin('VideoPicker').pickVideos(
      { maxCount: 9 },
      (res) => {
        console.log('选中的视频:', res.paths)
        let allWebview = plus.webview.all()
        allWebview.forEach((webview) => {
          if (webview.id === 'chat') {
            //找到聊天的webview
            console.log('找到聊天的webview', webview)
            webview.evalJS(
              `getBaseMulVideo('${encodeURIComponent(
                JSON.stringify(res.paths),
              )}')`,
            )
          }
        })
      },
      (err) => {
        console.error('选择失败:', err)
      },
    )
  }
})

// 获取电子名片
async function getCard(phone) {
  uni.request({
    url: 'https://blockchain.szjixun.cn/api/e_card/info-phone',
    method: 'POST',
    data: {
      phone: phone
    },
    success: (res) => {
      const resData = res.data.data
      uni.share({
        provider: 'weixin',
        scene: "WXSceneSession",
        type: 5,// 5代表分享为小程序
        imageUrl: 'https://e-cdn.fontree.cn/fonchain-main/prod/image/139/avatar/ababc42c-7654-47f8-b22b-29dc589c71f0.png', // 必填
        title: `${resData.name}的电子名片`,
        miniProgram: {
          id: "gh_97094c34debd",
          path: `/pages/mine/index?uid=${resData.uid}&userType=${resData.userType}`,
          type: 0,
          webUrl: `/pages/mine/index?uid=${resData.uid}&userType=${resData.userType}`,
        },
        success: function (res) {
          console.log("success:" + JSON.stringify(res));
        },
        fail: function (err) {
          console.log("fail:" + JSON.stringify(err));
        }
      });
    },
    fail: (err) => {
      console.log('getCard', err)
    }
  })

}
</script>

<style></style>