<template>
    <app-view class="g-form">
        <template #header>
            <app-navbar title="合同签署" />
        </template>
        <div class="g-form__container">
            <CellGroup inset>
                <Cell title="姓名" :value="customername" />
                <Cell title="手机号码" :value="mobile2" />
                <Cell title="证件号码" :value="decryptAES(cardnum)" />
                <Cell title="签署机构" :value="memberUserId" />
            </CellGroup>
            <CellGroup inset>
                <template v-for="(item, index) in dataList" :key="index">
                    <Cell :title="item.templatename" :icon="iconName(item.recordstatus)" @click="signer(item)"
                        is-link />
                </template>
            </CellGroup>
        </div>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef } from 'vue'
import { CellGroup, Cell, showFailToast, showToast } from 'vant'
import { fullloading } from '@/utils/vant';
import { useNavigation } from '@mobile/router/navigation'
import { useRequest } from '@/hooks/request'
import { queryTencentUsereSignRecords, requestInitTencentESS } from '@/services/api/account';
import { useRequestCreateFlowByTemplateDirectly } from '@/business/user/account';
import plus from '@/utils/h5plus'
import { getFileUrl } from '@/filters';
import { getUserId } from '@/services/methods/user'
import { useUserStore } from '@/stores'
import { decryptAES } from '@/services/websocket/package/crypto'

const { getQueryStringToNumber } = useNavigation()
/// 所属机构
const memberUserId = getQueryStringToNumber('memberUserId')
/// userStore
const userStore = useUserStore()
/// 创建电子签合同
const { createTemplate, templateFormData } = useRequestCreateFlowByTemplateDirectly()
/// 电子签合同信息
const dataList = shallowRef<Model.TencentUsereSignRecordsRsq[]>([])
/// 用户信息
const { customername, cardnum, mobile2 } =  userStore.userInfo
/// 查询
const { run } = useRequest(queryTencentUsereSignRecords, {
    params: {
        userId: getUserId(),
        memberUserId: memberUserId
    },
    onSuccess: (res) => {
        if (res.data.length != 0) {
            dataList.value = res.data
        }  else {
            /// 创建电子签合同
            initTencentESS()
        }
    }
})

/// 创建电子签合同
const { run: initTencentESS } = useRequest(requestInitTencentESS, {
    manual: true,
    params: {
        userId: getUserId(),
        memberUserId: memberUserId
    },
    onSuccess: () => {
        /// 重新请求
        run()
    }
})

const iconName = (type: number) => {
    switch (type) {
        case 2: return 'info-o'
        case 4: return 'close'
        case 3: return 'passed'
        default: return 'circle'
    }
}

const openWebview = (url: string) => {
    const ua = window.navigator.userAgent.toLowerCase()
    if (ua.indexOf('micromessenger') !== -1) {
        showToast({
            type: 'fail',
            message: '请使用浏览器打开此页面'
        })
    } else {
        plus.openWebview({
            url,
            titleText: '实名认证',
            onClose: () => run()
        })
    }
}

const signer = (item: Model.TencentUsereSignRecordsRsq) => {
    ///  如果是已签署
    if (item.recordstatus === 2) {
        item.signurl ? openWebview(item.signurl) : showFailToast('合同地址错误')
    } else if (item.recordstatus === 3) {
        const fileUrl = getFileUrl(item.contractfileaddr)
        item.contractfileaddr ? plus.openURL(fileUrl) : showFailToast('合同地址错误')
    } else {
        fullloading((hideLoading) => {
            const userinfotype = useUserStore().userInfo.userinfotype
            templateFormData.userESignRecordID = item.recordid
            templateFormData.userType = userinfotype
            /// 个人信息
            if (userinfotype === 1) {
                templateFormData.personInfo = {
                    idCardNumber: decryptAES(cardnum),
                    mobile: mobile2,
                    name: customername
                }
            } else {
                templateFormData.organizationInfo = {
                    name: customername
                }
            }
            /// 创建合同
            createTemplate().then((res) => {
                hideLoading()
                openWebview(res.data.signUrl)
            }).catch((err) => {
                hideLoading(err, 'fail')
            })
        })
    }
}

</script>