<template>
  <view class="container">
    <image class="face_auth_bg" :src="iconUrl.face_auth_bg" />
    <!-- 演示线因没有人脸审核模块,可能会导致审核失败，可以注释代码提交审核，但是不要把注释代码上传到git上  -->
    <view class="main_box">
      <view class="cont displayFlexCol">
        <text>为保障账户安全</text>
        <text class="cont_text">当前业务需要采集您的人脸信息以核实身份</text>
        <image class="cont_img" :src="iconUrl.face_auth_icon"></image>
      </view>
      <view class="input_box padding_30upx">
        <view class="input_list" v-if="!changeMobile">
          <view class="input_item border_bottom">
            <view class="input_tit">姓名</view>
            <view class="input_con">{{ memberName }}</view>
          </view>
          <view class="input_item">
            <view class="input_tit">身份证号</view>
            <input class="input_con" placeholder="请输入就诊人身份证号" v-model="idCardNo" type='idcard'
              placeholder-style="color:#999"></input>
          </view>
        </view>
        <view class="input_list" v-if="changeMobile">
          <view class="input_item">
            <view class="input_tit">新手机号</view>
            <input class="input_con" placeholder="请输入新手机号" v-model="newMobile" type='number'
              placeholder-style="color:#999"></input>
          </view>
          <view class="input_item">
            <input class="input_con" placeholder="请输入验证码" v-model="code" type='number'
              placeholder-style="color:#999"></input>
            <view v-if="seconds <= 0" class="code_con_txt colorCustom" @click="getCode">获取验证码</view>
            <view v-if="seconds > 0" class="code_con_txt colorCustom">{{ seconds }}秒后重新获取</view>
          </view>
        </view>
      </view>
      <view class="public_btn_con bg_white">
        <view v-if="!changeMobile" class="public_btn backgroundCustom displayFlexRow" @click="startCertification">开始人脸识别
        </view>
        <view v-if="changeMobile" class="public_btn backgroundCustom displayFlexRow" @click="hisUpdateMobileByCard">
          修改手机号</view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { useStore } from 'vuex';
import { useOnLoad, usePreserMember } from '@/hook';
import { addUserLevelL2_V3, sendVerificationCode_V3, checkVerificationCode_V3, setHisMobile, queryBaseMemberList_V3 } from '@/pagesPersonal/service/patientManagement';
import { common } from '@/utils';
import icon from '@/utils/icon.js';

const app = getApp();
const store = useStore();

const iconUrl = ref(icon);
const currentUser = ref<any>({});
const checkUserInfo = ref<any>({});
const memberName = ref("");
const idCardNo = ref("");
const changeMobile = ref(false);
const newMobile = ref("");
const timer = ref<any>(null);
const seconds = ref(0);
const cardNo = ref("");
const memberId = ref("");
const pcid = ref("");
const pageType = ref("");
const code = ref("");

useOnLoad((options) => {
  console.log("authFace=========",options);
  if (options && options.params) {
    try {
      let params = JSON.parse(options.params);
  console.log("params=========",params);
      let pType = options.pageType;
      if (params) {
        cardNo.value = params.CardNo;
        memberName.value = params.MemberName;
        idCardNo.value = params.IdCardNo;
        memberId.value = params.MemberId;
        pageType.value = pType;
        app.globalData.currentUser = {
          memberId: params.MemberId
        };
      }
    } catch (e) {
      console.error('参数解析失败', e);
    }
  }
  currentUser.value = app.globalData.currentUser;
  main();
});

const main = async () => {
  let checkUser = {};
  let querData = {
    isEncrypt: true,
    isTokenSecret: true,
    hosId: app.globalData.districtId || app.globalData.hosId,
    memberId: currentUser.value.memberId
  };

  // Service returns resp array
  let { resData: resp } = await queryBaseMemberList_V3(querData);
  if (resp && resp.length > 0) {
    let keyStr = resp[0].baseMemberEncryptionStore;
    let key = uni.getStorageSync("token");
    checkUser = JSON.parse(await common.desDecrypt(keyStr, key, 'hex'));
  }

  checkUserInfo.value = checkUser;
  memberName.value = checkUser.memberName;
};

const startCertification = async () => {
  let mName = memberName.value;
  let iCardNo = idCardNo.value;
  if (common.isEmpty(mName)) {
    common.showToast('请输入就诊人姓名');
    return;
  }
  if (common.isEmpty(iCardNo)) {
    common.showToast('请输入身份证号码');
    return;
  }
  if (iCardNo != checkUserInfo.value.idCardNo) {
    common.showToast('当前输入身份证号与实际授权用户信息不一致');
    return;
  }

  // uni.startFacialRecognitionVerify
  // #ifdef MP-WEIXIN
  uni.startFacialRecognitionVerify({
    checkAliveType: 1,
    name: mName,
    idCardNumber: iCardNo,
    success: async function (res) {
      let cUser = currentUser.value;
      if (!!pageType.value && pageType.value == "changeMobile") {
        changeMobile.value = true;
      } else {
        // 认证成功
        let queryData = {
          openId: uni.getStorageSync('openid'),
          memberId: cUser.memberId,
          store: {
            cardEncryptionStore: cUser.encryptionStore || '',
            baseMemberEncryptionStore: cUser.baseMemberEncryptionStore
          }
        };
        let { resData: resLevel } = await addUserLevelL2_V3(queryData);
        if (resLevel) {
          app.globalData.currentUser = cUser;
          common.navigateBack(1);
        }
      }
    },
    fail: (err) => {
      console.error('人脸识别失败', err);
      common.showToast('人脸识别失败');
    }
  });
  // #endif
  // #ifndef MP-WEIXIN
  common.showToast('当前平台不支持人脸识别');
  // #endif
};

const getCode = async () => {
  if (newMobile.value == "") {
    common.showToast("手机号不能为空");
    return;
  }
  let queryData = {
    OpenId: store.state.openId,
    HosId: app.globalData.hosId,
    Mobile: newMobile.value
  };
  let { resData: resp } = await sendVerificationCode_V3(queryData);
  if (!common.isEmpty(resp)) {
    pcid.value = resp[0].pcId;
    common.showModal('发送成功！');

    // Custom countdown logic
    seconds.value = 60;
    if (timer.value) clearInterval(timer.value);
    timer.value = setInterval(() => {
      seconds.value--;
      if (seconds.value <= 0) {
        clearInterval(timer.value);
      }
    }, 1000);
  }
};

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,
      };
      try {
        let { resData } = await checkVerificationCode_V3(reqData);
        if (resData && resData.RespCode == '10000') {
          resolve(false); // Valid
        } else {
          resolve(true); // Invalid
        }
      } catch (e) {
        resolve(true); // Invalid
      }
    }
  });
};

const hisUpdateMobileByCard = async () => {
  if (common.isEmpty(newMobile.value)) {
    common.showToast("请输入手机号");
    return;
  }
  if (common.isEmpty(pcid.value)) {
    common.showToast("请获取验证码");
    return;
  }
  if (common.isEmpty(code.value)) {
    common.showToast("请输入验证码");
    return;
  }

  // 校验验证码是否正确
  let reqData = {
    pcId: pcid.value || '',
    verificationCode: code.value,
  };
  if (await checkVerificationCode(reqData)) return;

  let data = {
    CardNo: cardNo.value,
    Mobile: newMobile.value,
    MemberName: memberName.value,
    MemberId: memberId.value
  };

  // setHisMobile returns resp
  let { resData: resp } = await setHisMobile(data);
  if (resp) {
    common.showModal("您的手机号码已修改成功", () => {
      common.navigateBack(1);
    });
  }
};
</script>

<style lang="scss" scoped>
.container {
  background: white;
}

.padding_30upx {
  padding: 0 30upx;
  box-sizing: border-box;
}

.face_auth_bg {
  width: 100%;
  height: 790upx;
  position: relative;
  z-index: 1;
}

.main_box {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}

.cont {
  padding: 56upx 74upx;
  box-sizing: border-box;
}

.cont text:nth-child(1) {
  font-size: 48upx;
  font-weight: bold;
  color: white;
  padding-bottom: 20upx;
}

.cont_img {
  width: 395upx;
  height: 395upx;
  margin-top: 55upx;
}

.cont_text {
  font-size: 32upx;
  color: white;
}

.input_list {
  display: inline-block;
  width: 100%;
  padding: 0 30upx;
  box-shadow: 0px 2px 20px 0px #ddd;
  border-radius: 20upx;
  background: white;
}

.input_item {
  height: 120upx;
  display: flex;
  align-items: center;
  position: relative;
  margin-bottom: -2px;
}

.input_tit {
  font-size: 32upx;
  font-weight: bold;
  color: #222326;
  width: 180upx;
  flex-shrink: 0;
}

.input_con {
  font-size: 32upx;
}

.public_btn {
  font-size: 34upx;
}

.code_con_txt {
  width: 30%;
}
</style>