<script setup>
import urlLauncher from '@/plugins/urlLauncher/index.js'

function toInquire(name) {
  if (name === 'marriage') {
    uni.navigateTo({
      url: `/pages/inquire?p=toc_Marriage`,
    })
  }
  else {
    uni.navigateTo({
      url: `/pages/list_${name}`,
    })
  }
}

// 页面加载时生成 30 条通知数据
onMounted(() => {

})
function toHistory() {
  uni.navigateTo({
    url: '/pages/history_query',
  })
}

function launch() {
  uni.getSystemInfo({
    success(res) {
      if (res.uniPlatform === 'app') {
        if (res.osName === 'android') {
          const CustomTabsIntent = plus.android.importClass('androidx.browser.customtabs.CustomTabsIntent')
          const Uri = plus.android.importClass('android.net.Uri')
          const activity = plus.android.runtimeMainActivity()
          const builder = new CustomTabsIntent.Builder()
          const customTabsIntent = builder.build()
          const uri = Uri.parse('https://www.quannengcha.com/inquire/toc_Marriage')
          customTabsIntent.launchUrl(activity, uri)
        }
        else if (res.osName === 'ios') {
          // turnonLight(true)
          testUIAlertController()
          // launchSafariViewController('https://www.quannengcha.com/inquire/toc_Marriage').then((res) => {
          //   console.log('成功打开')
          // })
          // const SFSafariViewController = plus.ios.importClass('SFSafariViewController')
          // const NSURL = plus.ios.import('NSURL')
          // const nsurl = NSURL.URLWithString('https://www.quannengcha.com/inquire/toc_Marriage')
          // const sfsviewController = new SFSafariViewController(nsurl)
          // const currentViewController = plus.ios.currentWebview()
          // // currentViewController().presentViewController(sfsviewController)
          // console.log('sfsviewController', sfsviewController)
          // console.log('currentViewController', currentViewController)
        }
      }
    },
  })
}
/**
 * 在iOS平台通过SFSafariViewController打开指定的URL
 * @param {string} url - 要打开的URL
 * @returns {Promise} - 返回一个 Promise，表示操作的成功或失败
 */
function launchSafariViewController(url) {
  return new Promise((resolve, reject) => {
    // 仅在iOS平台执行
    if (typeof plus === 'undefined' || !plus.os || plus.os.name.toLowerCase() !== 'ios') {
      reject({ success: false, message: '仅支持iOS平台' })
      return
    }

    if (!url) {
      reject({ success: false, message: 'URL缺失' })
      return
    }

    try {
      // 导入必要的iOS类
      const SFSafariViewController = plus.ios.importClass('SFSafariViewController')
      const NSURL = plus.ios.importClass('NSURL')
      const UIApplication = plus.ios.importClass('UIApplication')

      // 创建NSURL实例
      const nsUrl = NSURL.URLWithString(url)
      if (!nsUrl) {
        reject({ success: false, message: '无效的URL' })
        return
      }

      // 创建SFSafariViewController实例并初始化
      // 使用 newObject 并传递初始化方法和参数
      const safariVC = plus.ios.newObject('SFSafariViewController', 'initWithURL:', nsUrl)
      console.log('SFSafariViewController已初始化')

      // 获取UIApplication实例
      const app = UIApplication.sharedApplication()
      const delegate = plus.ios.invoke(app, 'delegate')

      // 尝试通过代理获取窗口
      let window = null
      if (delegate && plus.ios.invoke(delegate, 'window')) {
        window = plus.ios.invoke(delegate, 'window')
        console.log('通过代理获取窗口:', window)
      }

      // 如果无法通过代理获取窗口，则尝试获取keyWindow
      if (!window) {
        window = plus.ios.invoke(app, 'keyWindow')
        console.log('通过keyWindow获取窗口:', window)
      }

      // 如果仍然无法获取窗口，则遍历所有窗口并选择第一个可见的窗口
      if (!window) {
        const windows = plus.ios.invoke(app, 'windows')
        const count = plus.ios.invoke(windows, 'count')
        for (let i = 0; i < count; i++) {
          const tempWindow = plus.ios.invoke(windows, 'objectAtIndex:', i)
          if (plus.ios.invoke(tempWindow, 'isKeyWindow')) {
            window = tempWindow
            console.log('找到可见的窗口:', window)
            break
          }
        }
      }

      // 获取根视图控制器
      let rootVC = null
      if (window) {
        // 使用 plus.ios.invoke 来访问属性
        rootVC = plus.ios.invoke(window, 'rootViewController')
        console.log('rootViewController:', rootVC)
      }

      if (!rootVC) {
        reject({ success: false, message: '无法获取根视图控制器' })
        return
      }

      // 正确调用带有多个参数的选择器，确保选择器字符串正确
      plus.ios.invoke(rootVC, 'presentViewController:animated:completion:', [safariVC, true, null])
      console.log('SFSafariViewController已展示')
      resolve({ success: true })

      // 延迟释放对象，确保视图控制器被正确展示
      setTimeout(() => {
        plus.ios.deleteObject(nsUrl)
        plus.ios.deleteObject(app)
        plus.ios.deleteObject(delegate)
        plus.ios.deleteObject(window)
        plus.ios.deleteObject(rootVC)
        // 不立即删除 safariVC，以避免被提前销毁
      }, 1000)
    }
    catch (e) {
      console.log('错误:', e.message)
      reject({ success: false, message: e.message })
    }
  })
}
function turnonLight(isOn) {
  if (plus.os.name == 'iOS') {
    const avcaptClass = plus.ios.importClass('AVCaptureDevice')
    if (avcaptClass) {
      const device = avcaptClass.defaultDeviceWithMediaType('vide')
      plus.ios.invoke(device, 'lockForConfiguration:', null)
      if (isOn) {
        plus.ios.invoke(device, 'setTorchMode:', 1)
        plus.ios.invoke(device, 'setFlashMode:', 1)
      }
      else {
        plus.ios.invoke(device, 'setTorchMode:', 0)
        plus.ios.invoke(device, 'setFlashMode:', 0)
      }
      plus.ios.invoke(device, 'unlockForConfiguration')
    }
  }
};
/**
 * 在iOS平台通过UIAlertController显示系统提示框
 */
function testUIAlertController() {
  if (plus.os.name.toLowerCase() !== 'ios') {
    console.log('仅支持iOS平台')
    return
  }

  try {
    const UIAlertController = plus.ios.importClass('UIAlertController')
    const UIAlertAction = plus.ios.importClass('UIAlertAction')
    const UIApplication = plus.ios.importClass('UIApplication')

    // 创建UIAlertController实例
    const alert = UIAlertController.alertControllerWithTitleMessagePreferredStyle(
      '测试标题',
      '这是一个测试消息',
      1, // UIAlertControllerStyleAlert
    )

    // 创建UIAlertAction实例
    const okAction = UIAlertAction.actionWithTitleStyleHandler(
      '确定',
      0, // UIAlertActionStyleDefault
      null,
    )

    // 添加动作到alert
    alert.addAction(okAction)

    // 获取UIApplication实例
    const app = UIApplication.sharedApplication()
    const window = plus.ios.invoke(app, 'keyWindow')
    const rootVC = plus.ios.invoke(window, 'rootViewController')

    // 展示alert
    plus.ios.invoke(rootVC, 'presentViewController:animated:completion:', [alert, true, null])

    // 释放对象
    plus.ios.deleteObject(alert)
    plus.ios.deleteObject(okAction)
    plus.ios.deleteObject(app)
    plus.ios.deleteObject(window)
    plus.ios.deleteObject(rootVC)
  }
  catch (e) {
    console.log('错误:', e.message)
  }
}

// 调用该函数，打开一个 URL
</script>

<template>
  <view class="relative h-[165px] p-4">
    <image class="h-full w-full overflow-hidden rounded-xl" src="/static/image/banner.png" @click="launch" />
  </view>
  <view class="relative p-4 pb-4 pt-2">
    <view class="grid grid-cols-2 gap-3">
      <view
        class="relative flex flex-col cursor-pointer rounded-bl-[35px] rounded-br-lg rounded-tl-[35px] rounded-tr-lg bg-white px-4 py-6 shadow-lg"
        @click="toInquire('risk')"
      >
        <view class="min-h-18 gap-2 bg-white px-1">
          <view class="mb-2 flex justify-around">
            <image class="h-12 w-12 flex-shrink-0" src="/static/image/icon_3.png" mode="scaleToFill" />
            <view class="mt-1 max-w-max flex-shrink-0 text-left text-lg text-gray-600 font-bold">
              风险评估
            </view>
          </view>
          <view class="max-w-max text-left text-xs text-gray-600">
            检测个人不良记录、人企关系等
          </view>
        </view>
      </view>
      <view
        class="relative flex flex-col cursor-pointer rounded-bl-lg rounded-br-[35px] rounded-tl-lg rounded-tr-[35px] bg-white px-4 py-6 shadow-lg"
        @click="toInquire('marriage')"
      >
        <view class="min-h-18 gap-2 bg-white px-1">
          <view class="mb-2 flex justify-around">
            <view class="mt-1 max-w-max flex-shrink-0 text-left text-lg text-gray-600 font-bold">
              婚姻报告
            </view>
            <image class="h-12 w-12 flex-shrink-0" src="/static/image/icon_1.png" mode="scaleToFill" />
          </view>
          <view class="max-w-max text-left text-xs text-gray-600">
            核查个人不良，婚姻状态是否未婚、已婚、离婚、离婚冷静期
          </view>
        </view>
      </view>
      <view
        class="relative flex flex-col cursor-pointer rounded-bl-[35px] rounded-br-lg rounded-tl-[35px] rounded-tr-lg bg-white px-4 py-6 shadow-lg"
        @click="toInquire('lawsuit')"
      >
        <view class="min-h-18 gap-2 bg-white px-1">
          <view class="mb-2 flex justify-around">
            <image class="h-12 w-12 flex-shrink-0" src="/static/image/icon_2.png" mode="scaleToFill" />
            <view class="mt-1 max-w-max flex-shrink-0 text-left text-lg text-gray-600 font-bold">
              司法涉诉
            </view>
          </view>
          <view class="max-w-max text-left text-xs text-gray-600">
            查询个人与企业的民事案件、刑事案件、行政案件、非诉保全审查、执行案件、强制清算与破产等司法涉诉记录
          </view>
        </view>
      </view>
      <view
        class="relative flex flex-col cursor-pointer rounded-bl-lg rounded-br-[35px] rounded-tl-lg rounded-tr-[35px] bg-white px-4 py-6 shadow-lg"
        @click="toInquire('verify')"
      >
        <view class="min-h-18 gap-2 bg-white px-1">
          <view class="mb-2 flex justify-around">
            <view class="mt-1 max-w-max flex-shrink-0 text-left text-lg text-gray-600 font-bold">
              核验工具
            </view>
            <image class="h-12 w-12 flex-shrink-0" src="/static/image/icon_4.png" mode="scaleToFill" />
          </view>
          <view class="max-w-max text-left text-xs text-gray-600">
            核验身份证、手机、银行卡、自然人生存状态、学历、人车关系等的查询工具
          </view>
        </view>
      </view>
    </view>
    <view class="mt-4 font-bold">
      更多服务
    </view>
    <view
      class="mt-4 box-border h-14 w-full flex items-center rounded-xl bg-white px-4 text-gray-700 shadow-xl"
      @click="toHistory"
    >
      <image class="mr-4 h-10 w-10" src="/static/image/bg_icon.png" mode="widthFix" />
      <view class="">
        <view class="font-bold">
          我的历史查询记录
        </view>
        <view class="text-xs">
          查询记录有效期为30天
        </view>
      </view>
    </view>
    <view class="shadow-3xl mt-8 w-full">
      <image class="shadow-3xl w-full overflow-hidden rounded-xl" src="/static/image/liu.png" mode="widthFix" />
    </view>
  </view>
  <view class="disclaimer">
    <a href="https://beian.miit.gov.cn">
      备案号：琼ICP备2024038584号-2
    </a>
    <div>
      海南省学宇思网络科技有限公司版权所有
    </div>
  </view>
</template>

<style scoped>
.clip-left {
  clip-path: polygon(0 0, 0 100%, 90% 100%, 0 100%);
}

.clip-right {
  clip-path: polygon(0 0, 0 0, 90% 100%, 0 0);
}
</style>

<route type="home" lang="json">
{
  "layout": "home",
  "style": {
    "navigationStyle": "custom"
  }
}
</route>
