<template>
    <div class="personal-auth" v-if="!loading">
      <div v-if="![1,2,3].includes(authInfo.status)">
        <div v-if="authMethod === EAuthMethod.FOURFACTOURS">
          <four-factours/>
        </div>
        <div v-if="authMethod === EAuthMethod.FACE">
          <van-form ref="loginForm" @submit="onSubmit" v-if="!uploadSuccess">
            <van-field
              v-model="name"
              :rules="[{ required: true, message: '请填写真实姓名' }]"
              placeholder="请输入您的真实姓名"></van-field>
            <van-field
              class="margintop10"
              v-model="idCard"
              :rules="[{ pattern: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(\d|x|X)$/, message: '请输入正确的身份证号' }]"
              placeholder="请输入您的身份证号"></van-field>
            <van-field
              v-model="videoBase64"
              :rules="[{ required: true, message: '请填上传视频' }]" class="videoInput margintop10">
              <template #input>
                <input type="file" accept="video/*" id="video" capture="camcorder" @change="handleFileChange" style="display:none;">
                <label for="video" v-if="!videoBase64" style="width:100%;padding: 30px;text-align:center" class="add-video">
                    <common-svg name="shipin1" width="34px" height="34px"></common-svg>
                    <div style="color:#3F79FE;font-size:16px;line-height:1.5em;">添加视频</div>
                    <div style="color:#353535;font-size:14px;">请提前录制好视频进行上传</div>
                </label>
                <div v-else>
                  <video controls :src="videoBase64" style="width:100%;" ></video>
                  <div class="video-desc">验证视频仅用于验证身份，不会在溯源详情环节向用户展示。</div>
                  <label for="video" class="re-add">重新上传 ></label>
                </div>
              </template>
            </van-field>
            <div v-if="!videoBase64" style="margin-top:20px;">
               <div class="require-title">视频要求</div>
               <div style="display:flex;flex-direction:row;justify-content:space-between;">
                 <div v-for="({icon, label}, index) in requires" :key="index">
                    <common-svg :name="icon" width="50px" height="50px"></common-svg>
                    <div style="color:#353535;font-size: 14px;">{{label}}</div>
                 </div>
               </div>
            </div>
            <van-button block color="#3F79FE"  type="primary" native-type="submit" style="margin-top: 60px;">确定</van-button>
          </van-form>
          <upload-success v-if="uploadSuccess"></upload-success>
        </div>
      </div>
      <Auditing v-if="authInfo.status === 1"></Auditing>
      <audit-failure v-if="authInfo.status === 3" @re-audit="reAuditHandler" :message="authInfo.message"></audit-failure>
      <div class="auth-success" v-if="authInfo.status === 2">
         <div class="item van-hairline--bottom"><span class="key">姓名:</span><span class="value">{{authInfo.name}}</span></div>
         <div class="item van-hairline--bottom"><span class="key">身份证号:</span><span class="value">{{authInfo.id_card}}</span></div>
      </div> 
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { Cell, Form, Field, CellGroup, Button, Image, RadioGroup, Radio, Popup } from 'vant';
import { State, Getter, Action, Mutation } from 'vuex-class';
import { Route } from 'vue-router';
import { AuthStatus } from '@/const/enum';
import UploadSuccess from './components/UploadSucess.vue';
import Auditing from './components/Auditing.vue';
import AuditFailure from './components/AuditFailure.vue';
import FourFactours from "./FourFactours.vue"
import {EAuthMethod} from "./types";


@Component({
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Image.name]: Image,
    [Cell.name]: Cell,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    UploadSuccess,
    Auditing,
    AuditFailure,
    FourFactours
  },
})
export default class Personal extends Vue {
  @State('authInfo') private authInfo!: any;
  @Action('getAuthInfo') private getAuthInfo!: () => void;
  @Mutation('updateAuthInfo') private updateAuthInfo!: (authInfo: any) => void;
  @Action('getUserInfo') private getUserInfo!: () => Promise<any>;


  private EAuthMethod = EAuthMethod;
  private loading = true;
  private authMethod: EAuthMethod | null = null;
  private AuthStatus: any = AuthStatus;
  private name: string = '';
  private idCard: string = '';
  private videoBase64: string = '';

  private uploadSuccess: boolean = false;

  private step: string = '1';


  private readonly requires: any[] = [
    {
      icon: 'benrenshipin2',
      label: '本人视频',
    },
    {
      icon: 'shipinqingxi',
      label: '视频清晰',
    },
    {
      icon: 'lianwuzhedang',
      label: '脸无遮挡',
    },
  ];

  private async mounted() {
    try{
      this.loading = true;
      await this.getAuthInfo();
      const authMethod = await this.getAuthMethod();
      this.authMethod = authMethod;
      this.loading = false;
    }catch(err){
      this.loading = false;
    }
  }


  private getAuthMethod(): Promise<EAuthMethod>{
    return this.$api.auth.method().then((ret: any)=>{
      return ret.method;
    })
  }

 
  private reAuditHandler() {
    this.updateAuthInfo({});
    this.$router.replace({ name: 'Auth'});
  }
  private onSubmit() {
    const { name, idCard, videoBase64 } = this;
    const params: any = {
      name,
      id_card: idCard,
      // bank_card: bankCard,
      // bank_phone: bankPhone,
      video_base64: videoBase64,
    };
    // this.$api.auth.bankcard4c(params).then((res: any) => {
    //   this.uploadSuccess = true;
    // });
    const toast = this.$toast({
      message: '0%',
      duration: 0, // 持续展示 toast
      forbidClick: true,
    });
    this.$api.auth.face(params, (process: any) => {
      const { loaded, total } = process;
      const percent = Math.floor(loaded / total * 100);
      toast.message = `${ percent }%`;
      if (percent === 100) {
        toast.clear();
      }
    }).then((res: any) => {
      this.uploadSuccess = true;
    });
  }
  private handleFileChange(e: any) {
    const [file] = e.target.files;
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (event: any) => {
        this.videoBase64  = event.target.result;
    };
  }
}
</script>
<style scoped lang="scss">
  .personal-auth{
    padding: 17px;
    ::v-deep .videoInput.van-cell{
      padding: 0;
    }
    .add-video{
      background:rgba(252,252,252,1);
      border-radius:4px;
      border:1px dashed rgba(225,225,225,1);
    }
    .err-add{
      color: #FF4242;
      background: #FFF8F8;
    }
    .video-desc{
      font-size:14px;
      line-height: 1.5em;
      color:#B6B7B9;
      background: #F9FBFF;
    }
    .margintop10{
      margin-top: 10px;
    }
    .re-add{
      display: block;
      color:#353535;
      font-size: 16px;
      line-height: 1.5em;
      background: #F9FBFF;
    }
    .require-title{
      position: relative;
      font-size: 14px;
      color: #353535;
      text-align: center;
      &::before, &::after{
        content: "";
        position: absolute;
        width: 120px;
        height: 1px;
        top: 50%;
        background-color: #E1E1E1;
      }
      &::before{
        left: 0%;
      }
      &::after{
        right: 0%;
      }
    }
    .auth-success{
      .item{
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        padding: 14px 16px;
        .key{
          font-size: 16px;
          color: #353535;
        }
        .value{
          color: #999999;
          font-size: 14px;
        }
      }
    }
   
  }
</style>