<template>
    <app-view class="g-form">
        <template #header>
            <app-navbar title="合同签署" />
        </template>
        <div class="g-form__container">
            <CellGroup inset>
                <Cell title="姓名" :value="userInfo.customername" />
                <Cell title="手机号码" :value="userInfo.mobile2" />
                <Cell title="证件号码" :value="userInfo.cardnum" />
                <Cell title="签署机构" :value="signId" />
            </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 { CellGroup, Cell, showFailToast, showToast } from 'vant'
import { fullloading } from '@/utils/vant'
import { useNavigation } from '@mobile/router/navigation'
import { requestInitTencentESS } from '@/services/api/account'
import { useRequestCreateFlowByTemplateDirectly } from '@/business/user/account'
import plus from '@/utils/h5plus'

const { getQueryStringToNumber } = useNavigation()
/// 所属机构
const qs = getQueryStringToNumber('memberUserId')
/// 创建电子签合同
const { getTencentUsereSignRecords, createTemplate, userInfo, signId, dataList } = useRequestCreateFlowByTemplateDirectly(qs)

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: () => getTencentUsereSignRecords()
        })
    }
}

const signer = (item: Model.TencentUsereSignRecordsRsq) => {
    ///  如果是已签署
    if (item.recordstatus === 2) {
        item.signurl ? openWebview(item.signurl) : showFailToast('合同地址错误')
    } else if (item.recordstatus === 3) {
        showFailToast('合同已签署，请前往腾讯电子签小程序查看！')
    } else {
        fullloading((hideLoading) => {
            /// 创建合同
            createTemplate(item.recordid).then((res) => {
                hideLoading()
                openWebview(res.data.signUrl)
            }).catch((err) => {
                hideLoading(err, 'fail')
            })
        })
    }
}

getTencentUsereSignRecords().then(() => {
    if (!dataList.value.length) {
        // 创建电子签合同
        requestInitTencentESS({
            data: {
                memberUserId: signId
            }
        }).then(() => {
            getTencentUsereSignRecords()
        })
    }
})
</script>