<template>
  <ay-container>
    <div class="form">
      <uni-forms ref="form" :modelValue="data" :rules="rules" validateTrigger="blur">
        <div class="font-bold bs-fz mb-spacd2">上传并提交您的证件照片</div>
        <div class="s-fz gray-color mb-spac">为配合国家监管要求，请上传身份证正反面照片</div>
        <!-- <div class="p-fz mt-spac mb-spac">身份证照片</div> -->
        <div class="center flex-col">
          <uni-forms-item name="idCardFront">
            <div class="chunk id-card id-card-front" @click="methods.upload(0)">
              <image
                class="image"
                v-show="data.idCardFront"
                :src="ay.getResourceUrl(data.idCardFront)"
                mode="scaleToFill"
              />
              <div class="desc">点击上传身份证人像面</div>
            </div>
          </uni-forms-item>
          <uni-forms-item name="idCardBack">
            <div class="chunk id-card id-card-back" @click="methods.upload(1)">
              <image
                class="image"
                v-show="data.idCardBack"
                :src="ay.getResourceUrl(data.idCardBack)"
                mode="scaleToFill"
              />
              <div class="desc">点击上传身份证国徽面</div>
            </div>
          </uni-forms-item>
        </div>
        <uni-forms-item>
          <div class="p-fz mb-spac">拍摄要求</div>
          <div class="center justify-between">
            <image class="error-img" src="@img/idCard/idCard0.png" />
            <image class="error-img" src="@img/idCard/idCard1.png" />
            <image class="error-img" src="@img/idCard/idCard_error2.png" />
            <image class="error-img" src="@img/idCard/idCard_error3.png" />
          </div>
        </uni-forms-item>
        <uni-forms-item label="姓名" name="realname">
          <template #label>
            <uni-icons type="person" color="" size="32" class="mr-spac" />
          </template>
          <uni-easyinput v-model="data.realname" placeholder="请输入姓名" />
        </uni-forms-item>
        <uni-forms-item label="身份证号" name="idcardNo">
          <template #label>
            <uni-icons type="auth" color="" size="32" class="mr-spac" />
          </template>
          <uni-easyinput v-model="data.idcardNo" placeholder="请输入身份证号" />
        </uni-forms-item>
        <uni-forms-item name="idcardValidity">
          <div class="s-fz mb-spac">身份证有效期</div>
          <div class="center justify-start">
            <uni-datetime-picker
              v-model="data.idcardValidityStart"
              type="date"
              :clearIcon="false"
              placeholder="开始日期"
              :end="safeDate"
              class="flex-auto"
            />
            <div class="ml-spacd2 mr-spacd2">--</div>
            <checkbox-group @change="methods.checkChange" class="mr-spacd4">
              <label class="center">
                <checkbox value="check" :checked="data.idcardValidityLong" class="checkbox" />
                <span>长期</span>
              </label>
            </checkbox-group>
            <uni-datetime-picker
              v-model="data.idcardValidityEnd"
              type="date"
              :clearIcon="false"
              placeholder="结束时间"
              :start="safeDate"
              :style="{ visibility: data.idcardValidityLong ? 'hidden' : '' }"
            />
          </div>
          <!-- <uni-easyinput v-model="data.idcardValidity" placeholder="请输入身份证有效期" /> -->
        </uni-forms-item>
      </uni-forms>
    </div>
    <div class="btns">
      <button
        type="primary"
        @click="methods.auth"
        :disabled="store.webapi.user.idcard_auth.ios"
        :loading="store.webapi.user.idcard_auth.ing"
      >
        开始认证
      </button>
    </div>
  </ay-container>
</template>

<script lang="ts" setup>
import { Loading } from 'vant'

const form = ref()
const rules = {
  idCardFront: {
    rules: [
      {
        required: true,
        errorMessage: '请上传身份证正面照片',
        validateFunction() {
          return !!data.idCardFront
        },
      },
    ],
  },
  idCardBack: {
    rules: [
      {
        required: true,
        errorMessage: '请上传身份证反面照片',
        validateFunction() {
          return !!data.idCardBack
        },
      },
    ],
  },
  realname: {
    rules: [
      {
        required: true,
        errorMessage: '请输入姓名',
      },
    ],
  },
  idcardNo: {
    rules: [
      {
        required: true,
        errorMessage: '请输入身份证号',
      },
    ],
  },
  idcardValidity: {
    rules: [
      {
        required: true,
        errorMessage: '请选择有效期限',
        validateFunction() {
          return !!(data.idcardValidityStart && (data.idcardValidityEnd || data.idcardValidityLong))
        },
      },
    ],
  },
}
const data = reactive({
  idCardFront: '',
  idCardBack: '',
  realname: '',
  idcardNo: '',
  idcardValidityStart: '',
  idcardValidityEnd: '',
  idcardValidityLong: false,
  // 定义这个属性默认值：-， 是为了激活验证，否则idCard对应的validateFunction验证不生效
  idcardValidity: '-',
})
const safeDate = computed(() => {
  const rv: any = Date.now()
  // if (data.idcardValidityEnd) {
  //   rv = data.idcardValidityEnd
  // }
  return rv
})
const methods = {
  upload(type) {
    if (store.webapi.message.file.ing) {
      return
    }
    webapi.message
      .file(
        {},
        {
          showLoading: true,
          loadingText: '上传中...',
        },
      )
      .then((res) => {
        if (type === 0) {
          data.idCardFront = res
        }
        if (type === 1) {
          data.idCardBack = res
        }
        console.log(res)
      })
  },
  checkChange(e) {
    data.idcardValidityLong = !!e.detail.value.length
  },
  auth() {
    form.value
      .validate()
      .then(() => {
        const startDate = func.getDate(data.idcardValidityStart).format(enums.FormatType.YMDNC)
        let endDate = '长期'
        if (!data.idcardValidityLong) {
          endDate = func.getDate(data.idcardValidityEnd).format(enums.FormatType.YMDNC)
        }
        const param = {
          idcardFaceUrl: data.idCardFront,
          idcardBackUrl: data.idCardBack,
          realname: data.realname,
          idcardNo: data.idcardNo,
          idcardValidity: `${startDate}~${endDate}`,
        }
        webapi.user.idcard_auth(param).then((res) => {
          if (res) {
            func.native.showToast('实名认证成功！').then(() => {
              ay.navigateBack({ aceas: {} })
            })
          }
        })
      })
      .catch((err) => {
        if (['realname', 'idcardNo', 'idcardValidity'].includes(err[0].key)) {
          uni.pageScrollTo({
            scrollTop: config.common.SystemInfo.screenHeight + 100,
          })
        }
      })
  },
}
ay.entrance(() => {})
</script>

<style lang="scss" scoped>
.form {
  padding-bottom: 200rpx;
}
.id-card {
  width: 668rpx;
  height: 434rpx;
  padding: 0;
  background-repeat: no-repeat;
  background-position: center 50px;
  background-size: contain;
  background-size: 50%;
  & .image {
    position: relative;
    z-index: 1;
    width: 100%;
    height: 100%;
  }
  & .desc {
    position: absolute;
    bottom: $p-spac * 3;
    width: 100%;
    font-size: $p-fz;
    color: $gray-color;
    text-align: center;
  }
}
.id-card-front {
  background-image: url('@img/idCard/idCard_front.png');
}
.id-card-back {
  background-image: url('@img/idCard/idCard_back.png');
}
.error-img {
  position: relative;
  width: 160rpx;
  height: 100rpx;
}
.chunk {
  margin: 0;
  overflow: unset;
}
</style>
