<template>
  <view class="container">
    <view class="content">
      <view class="public_tip">温馨提示：请务必填写真实信息，您的信息我们将严格保密。</view>
      <formPage :formConfigList="formConfigList" @toSelect="makeUpAccount"></formPage>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { common } from '@/utils';
import {
  addBaseMember_V3,
  makeUpAccount as makeUpAccountApi,
  delMemberInfo_V3
} from '@/pagesPersonal/service/patientManagement';
import formPage from '@/pagesPersonal/st1/components/formPage/formPage.vue';

const app = getApp();
const userAccount = ref<any>(null);
const formConfigList = ref<any[]>([]);

onLoad(() => {
  const allFormConfigList = uni.getStorageSync('formConfigList') || [];
  const form = allFormConfigList.filter((item: any) => item.formScene == 'ACCOUNTLOGIN' && item.isShow == 1);
  userAccount.value = app.globalData.userAccount;
  formConfigList.value = form;
});

// 认证
const makeUpAccount = async (e: any) => {
  // 兼容 Vue event 和 小程序 event detail
  const configList = e.detail ? e.detail.formConfigList : (e.formConfigList || e);
  
  const res = await validate(configList);
  if (!res) return;
  
  //关系是本人-1
  res.relationCode = 1;
  const accountSn = userAccount.value.accountSn;
  
  //因验证接口一定要memberId 所以先添加
  let { resData } = await addBaseMember_V3({
    ...res,
    accountSn
  });
  
  if (resData.RespCode != 10000 || !resData.Data || !resData.Data.length) return;
  
  const memberId = resData.Data[0].memberId;
  const { resData: accountResData } = await makeUpAccountApi({
    memberId,
    accountSn
  });
  
  if (accountResData && accountResData.RespCode == 10000) {
    common.showToast("保存成功");
    uni.navigateBack();
  } else {
    await delMemberInfo_V3({
      accountSn: app.globalData.userAccount.accountSn,
      memberId: resData.Data[0].memberId,
    });
  }
};

// 表单验证
const validate = (formConfigList: any[]) => {
  return new Promise<any>((resolve) => {
    const dataObj: any = {};
    formConfigList.forEach((item: any) => {
      if (item.vModel == "certType") {
        dataObj[item.vModel] = item.options[item.defValue].value;
      } else {
        dataObj[item.vModel] = item.defValue;
      }
    });
    
    for (let item of formConfigList) {
      // 必填验证
      if (item.isMust && !item.defValue) {
        common.showToast(item.warnMessage);
        resolve(false);
        return;
      }
      // 规则验证
      if (item.regularExpressions) {
        const reg = new RegExp(item.regularExpressions);
        // 非身份证的不做验证
        if (item.vModel == "certNum") {
          if (dataObj.certType != "01") {
            continue;
          }
        }
        if (!reg.test(item.defValue)) {
          common.showToast(item.warnMessage);
          resolve(false);
          return;
        }
      }
    }
    resolve(dataObj);
  });
};
</script>

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