<template>
	<view class="container">
		<view class="content">
			<view class="public_tip">请正确填写就诊人姓名、身份证号、手机号，并再次核实就诊 人信息的正确性</view>
			<formPage :formConfigList="formConfigList" @toSelect="toSelect"></formPage>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { useOnLoad, usePreserMember } from '@/hook';
import {
  addBaseMemberByEncryptionStore_V3,
  queryMemberCardList_V3,
  checkVerificationCode_V3
} from '@/pagesPersonal/service/patientManagement';
import { common } from '@/utils';
import formPage from "@/pagesPersonal/st1/components/formPage/formPage.vue";

const app = getApp();

const formConfigList = ref<any[]>([]);
const queryBean = ref<any>({});
const pageType = ref("");
const dialogIsShow = ref(false);
const dialogIsSuccess = ref(true);
const currentType = ref('default'); // Default value based on usage in dialogConfirmClick

useOnLoad((options) => {
    let configList = common.deepCopy(uni.getStorageSync('formConfigList'), []).filter((item: any) => item.formScene == 'ADDMEMBER');
    // 如果有传queryBean,方向添值进入表单内容
    if (options.queryBean) {
        let qBean = options.queryBean ? JSON.parse(decodeURIComponent(options.queryBean)) : {};
        configList.map((item: any) => {
            if (common.isNotEmpty(qBean[item.vModel])) {
                // 判断等于input输入框类型 直接复制
                if (item.type == 'text') {
                    item.defValue = qBean[item.vModel];
                }
                // 判断等于下拉框类型 直接复制
                if (item.type == 'select') {
                    // item.options
                }
            }
        });
        queryBean.value = qBean;
    }
    pageType.value = options.pageType || "";
    formConfigList.value = configList;
});

/**
 * 接收到组件弹框触发的确定事件
 */
const dialogConfirmClick = async () => {
    dialogIsShow.value = false;
    /**默认方式  需要成功才去跳转  推荐方式和新生儿方式  失败也会添加无卡就诊人 直接跳转即可*/
    if ((currentType.value == 'default' && dialogIsSuccess.value && app.globalData.toUrl) || (currentType.value != 'default' && app.globalData.toUrl)) {
        /**如果是成功  并且全局存了url变量 跳转到全局URL */
        common.goToUrl(app.globalData.toUrl, {
            skipWay: "redirectTo"
        });
    } else {
        common.navigateBack(1);
    }
};

/**
 * 点击下一步
 */
const toSelect = async (e: any) => {
    // e.detail in Vue might be just e if the event emits the object directly. 
    // Assuming formPage emits the same object structure as before.
    // If formPage uses defineEmits(['toSelect']) and emit('toSelect', detail), then e is detail.
    // Checking the old code: bindtoSelect="toSelect", e.detail was used.
    // In Vue 3: @toSelect="toSelect", the payload is the first argument.
    // We assume the payload structure matches e.detail from the old code.
    
    // However, if formPage is still legacy-style but imported as Vue, let's assume standard Vue event emission.
    let detail = e.detail || e; // Fallback for safety

    let cType = detail.currentType;
    currentType.value = cType;
    let fConfigList = detail.formConfigList;
    
    /**过滤出当前展示的表单 */
    let currentList = fConfigList.filter((item: any) => item.store.type.indexOf(cType) != '-1' && item.isShow == '1');
    let provingCode = currentList.filter((item: any) => item.vModel == 'provingCode')[0]; /**验证码 */
    
    let queryData: any = {
        isChildren: cType == 'children' ? '1' : '0',
        hosId: app.globalData.districtId || app.globalData.hosId,
        pcId: detail.pcId,
        verificationCode: provingCode && provingCode.defValue || "",
    };
    
    for (let item of currentList) {
        /**校验正则 */
        if (!check(item, currentList)) {
            return;
        }
        /**添加请求参数 */
        if ((item.type == 'text' && item.vModel != "provingCode") || item.type == 'datePicker') {
            queryData[item.vModel] = item.defValue;
        } else if (item.type == 'region') {
            queryData[item.vModel] = item.defValue.join('');
        } else if (item.type == 'select' || item.type == 'radio') {
            queryData[item.vModel] = item.defValue ? item.options[item.defValue].value : '';
        }
    }
    
    /**儿童的还要判断姓名跟监护人不一致 */
    if (cType == 'children') {
        let membername = currentList.filter((item: any) => item.vModel == 'memberName')[0].defValue;
        let guardianName = currentList.filter((item: any) => item.vModel == 'guardianName')[0].defValue;
        if (membername == guardianName) {
            common.showToast('监护人姓名与儿童姓名不能一致');
            return;
        }
    }
    
    let checkType = formConfigList.value.filter((item: any) => item.vModel == 'checkType')[0];
    if (checkType && checkType.defValue == '1') {
        /**如果是人脸识别 */
        let data = {
            memberName: formConfigList.value.filter((item: any) => item.vModel == 'memberName')[0].defValue,
            idCardNo: formConfigList.value.filter((item: any) => item.vModel == 'certNum')[0].defValue
        };
        let resp = await startFacialRecognitionVerify(data).then(res => res).catch(err => err);
        if (!resp.success) {
            return;
        }
    }
    
    // 判断是否有输入验证码
    if (common.isNotEmpty(queryData.verificationCode) && await checkVerificationCode(queryData)) return;
    
    // 校验成功情况验证码数据
    queryData.pcId = "";
    queryData.verificationCode = "";
    
    // 判断当前为卡号查询就诊信息添加，且没在我们程序内绑定过时，补充信息
    if (pageType.value == 'cardAddMember') {
        let querData = {
            cardEncryptionStore: queryBean.value.encryptionStore,
            ...queryData,
        };
        let { resData: res } = await addBaseMemberByEncryptionStore_V3(querData);
        if (res.RespCode == 10000) {
            await usePreserMember();
            common.navigateBack(2);
        }
        return;
    }
    
    // 然后查询 就诊人院内卡信息走后续流程
    let { resp, resData } = await queryMemberCardList_V3(queryData);
    if (resData.RespCode == 10000) {
        let url = "/pagesPersonal/st1/business/patientManagement/faceChooseVisiCard/faceChooseVisiCard";
        let data = "";
        if (common.isNotEmpty(resp) && resp.length >= 1) {
            queryData.CardType = 1;
            data = 'queryData=' + JSON.stringify(queryData) + "&serviceType=addMember";
        } else {
            data = 'queryData=' + JSON.stringify(queryData) + "&serviceType=noCard_idCard";
        }
        //如果是添加健康卡
        if (pageType.value) {
            data += '&pageType=' + pageType.value;
        }
        common.goToUrl(url, { data, skipWay: 'redirectTo' });
    }
};

// 检验验证码
const checkVerificationCode = async (queryData: any) => {
    return new Promise(async (resolve, reject) => {
        if (common.isEmpty(queryData.pcId)) {
            common.showModal('请先获取验证码');
        } else {
            let reqData = {
                pcId: queryData.pcId || '',
                verificationCode: queryData.verificationCode,
            };
            let { resData } = await checkVerificationCode_V3(reqData);
            if (resData.RespCode == 10000) {
                resolve(false);
                return;
            }
        }
        resolve(true);
    });
};

/**
 * 获取校验规则
 */
const check = (item: any, currentList: any[]) => {
    if (item.isShow == '1' && item.isMust == '1') {
        // 字符串去除所有空格
        if (typeof (item.defValue) == "string") {
            item.defValue = item.defValue.replace(/\s+/g, "");
        }
        /**只校验显示 和必填的 */
        if (common.isEmpty(item.defValue)) {
            common.showToast(item.warnMessage);
            return false;
        } else {
            let reg = item.regularExpressions ? new RegExp(item.regularExpressions) : "";
            /**有正则 则校验正则 */
            if (!common.isEmpty(item.regularExpressions) && !reg.test(item.defValue)) {
                /** 如果类型不是身份证时 证件号码不作格式校验 */
                if (item.vModel == 'certNum' || item.vModel == 'guardianCertNum') {
                    let certType = currentList.filter((ele: any) => (item.vModel == 'certNum' && ele.vModel == 'certType') || (item.vModel == 'guardianCertNum' && ele.vModel == 'guardianCertType'))[0];
                    if (certType.options[certType.defValue].value != '01') {
                        return true;
                    }
                }
                common.showToast(item.warnMessage);
                return false;
            }
        }
    }
    return true;
};

// Start Facial Recognition Verify Wrapper
const startFacialRecognitionVerify = (data: any) => {
    return new Promise((resolve, reject) => {
        // #ifdef MP-WEIXIN
        uni.startFacialRecognitionVerify({
            checkAliveType: 1, // 1: 读数字 2: 屏幕闪烁
            name: data.memberName,
            idCardNumber: data.idCardNo,
            success: (res) => {
                resolve({ success: true, res });
            },
            fail: (err) => {
                console.error('人脸识别失败', err);
                common.showToast('人脸识别失败');
                resolve({ success: false, err });
            }
        });
        // #endif
        // #ifndef MP-WEIXIN
        common.showToast('当前环境不支持人脸识别');
        resolve({ success: false });
        // #endif
    });
};

</script>

<style lang="scss" scoped>
</style>