// 认证所需函数

import { ref } from 'vue'
import { isValidPhoneNumber, isValidChineseIDNumber, isValidBankCard } from '@/utils/index'
import { useLoginStore } from '@/store/login'

// @ts-ignore
import { startEid } from '../../../mp_ecard_sdk/main.js'

import {
  saveBaseInfoApi,
  signCertApi,
  signAgreementApi,
  getETokenApi,
  getETokenResultApi,
  batchCertApi,
  saveBankInfoApi
} from '@/service/modules/auth'

export default function useAuthFn(userInfo: any, radioValue: any, certList: any) {
  const loginStore = useLoginStore()
  // 校验信息
  const checkInfo = () => {
    if (!userInfo.realname) {
      uni.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }
    if (!userInfo.idCardNumber) {
      uni.showToast({
        title: '请输入身份证号',
        icon: 'none'
      })
      return
    }
    if (!isValidChineseIDNumber(userInfo.idCardNumber)) {
      uni.showToast({
        title: '请输入正确的身份证号',
        icon: 'none'
      })
      return
    }
    if (!isValidBankCard(userInfo.bankCardNumber)) {
      uni.showToast({
        title: '请检查银行卡号',
        icon: 'none'
      })
      return
    }
    if (!isValidPhoneNumber(userInfo.bankPhone)) {
      uni.showToast({
        title: '请检查银行绑定手机号',
        icon: 'none'
      })
      return
    }
    if (!radioValue.value) {
      uni.showToast({
        title: '请选择认证渠道',
        icon: 'none'
      })
      return
    }
    return true
  }
  // 保存信息
  const saveBaseInfo = async () => {
    const data = {
      userId: loginStore.currentUserInfo.userId,
      realname: userInfo.realname,
      idCardNumber: userInfo.idCardNumber,
      bankCardNumber: userInfo.bankCardNumber,
      bankPhone: userInfo.bankPhone,
      subjectLocation: radioValue.value
    }
    uni.showLoading({
      title: '保存信息中',
      mask: true
    })
    const res = await saveBaseInfoApi(data)
    if (res.code === 0) {
      loginStore.getUserInfoByCode()
    }
    uni.hideLoading()
  }
  // 签约/增员
  const signCertFn = async () => {
    uni.showLoading({
      title: '信息校验中',
      icon: 'loading',
      mask: true
    })
    const data = {
      userId: loginStore.currentUserInfo.userId,
      subjectLocation: radioValue.value
    }
    const res = await signCertApi(data)
    uni.hideLoading()
    if (res.code === 0) {
      // 如果返回状态为SIGNING 重新发起认证
      if (res.data?.certStatus === 'SIGNING') {
        signCertFn()
      } else {
        // 签署协议弹窗
        signAgreementFn()
      }
    } else {
      // 签约/增员失败 展示原因
      setTimeout(() => {
        uni.showToast({
          title: res.msg || '失败，请重试',
          icon: 'none'
        })
      }, 0)
    }
  }

  const agereementModal = ref()
  const agreemetChecked = ref(false)
  // 签署协议弹窗
  const signAgreementFn = () => {
    if (certList.value) {
      const curr = certList.value.find((item: any) => item.subjectLocation === radioValue.value)
      // 存在agreementUrl直接去认证
      if (curr?.agreementUrl) {
        getETokenAndToVerify()
        return
      }
      agereementModal.value.open()
    }
  }
  const agreementUrl = ref('')
  // 签署协议
  const signAgreeSuccess = async () => {
    uni.showLoading({
      title: '提交信息中',
      mask: true
    })
    const data = {
      userId: loginStore.currentUserInfo.userId,
      agreementUrl: agreementUrl.value,
      subjectLocation: radioValue.value
    }
    const res = await signAgreementApi(data)
    if (res.code === 0) {
      // 签署成功
      // 去走E证通
      getETokenAndToVerify()
    } else {
      uni.showToast({
        title: res.msg || '签署失败',
        icon: 'none',
        duration: 1500
      })
      uni.navigateBack()
    }
    uni.hideLoading()
  }
  // 跳转e证通认证
  const getETokenAndToVerify = async () => {
    // 判断是否已经认证过
    if (loginStore.currentUserInfo.existEidResult) {
      authCertFn()
      return
    }
    const data = {
      realName: userInfo.realname,
      idCard: userInfo.idCardNumber
    }

    const res = await getETokenApi(data)
    if (res.code === 0) {
      const etoken = res.data
      const param = {
        data: {
          token: etoken
        },
        verifyDoneCallback(res: any) {
          console.log('收到核身完成的res', res)
        }
      }
      etoken && startEid(param)
    } else {
      uni.showToast({
        title: '状态获取失败，请重试',
        icon: 'none'
      })
    }
  }

  // e证通返回
  const authBackHandler = async (options: any) => {
    if (options?.path !== 'mp_ecard_sdk/index/index') return
    const { referrerInfo, scene } = options
    if (scene === 1038 && referrerInfo?.appId === 'wx0e2cb0b052a91c92') {
      const { extraData } = referrerInfo
      if (!extraData) {
        return uni.showToast({
          title: '核身失败，请重试',
          icon: 'none',
          duration: 3000
        })
      }
      const { token, verifyDone } = extraData
      if (verifyDone) {
        uni.showLoading({
          title: '核身结果获取中',
          mask: true
        })
        const res = await getETokenResultApi(token)
        uni.hideLoading()
        if (res.code === 0) {
          // 核身成功
          if (res.data.compareCode === 0) {
            uni.showToast({
              title: '核身成功',
              icon: 'none'
            })
            // 认证
            authCertFn()
          } else {
            uni.showToast({
              title: '核身失败',
              icon: 'none'
            })
          }
        } else {
          // 查询结果失败
          uni.showToast({
            title: res.msg || '未查询到结果',
            icon: 'none'
          })
        }
      }
    }
    console.log('options', options)
  }

  // 认证
  const authCertFn = async () => {
    const data = {
      userId: loginStore.currentUserInfo.userId,
      subjectLocation: radioValue.value,
      token: loginStore.currentUserInfo.certToken
    }
    const res = await batchCertApi(data)
    if (res.code === 0) {
      saveBankInfo()
    } else {
      uni.showToast({
        title: res.msg || '提交失败，请重试',
        icon: 'none',
        duration: 3000
      })
    }
    loginStore.getUserInfoByCode()
  }

  // 绑定银行卡
  const saveBankInfo = async () => {
    const data = {
      userId: loginStore.currentUserInfo.userId,
      bankPhone: loginStore.currentUserInfo.bankPhone,
      bankCardNumber: loginStore.currentUserInfo.bankCardNumber
    }
    const res = await saveBankInfoApi(data)
    if (res.code === 0) {
      uni.showToast({
        title: '成功',
        icon: 'none',
        duration: 3000
      })
    }
  }
  return {
    checkInfo,
    saveBaseInfo,
    signCertFn,
    signAgreementFn,
    authCertFn,
    signAgreeSuccess,
    authBackHandler,
    agereementModal,
    agreemetChecked,
    agreementUrl
  }
}
