<script setup lang='ts'>
import request from '~/request'
import { showFailToast, showSuccessToast, showDialog } from 'vant';

const router = useRouter()

function onClickLeft() {
  router.back()
}

const form = reactive({
  // axa_sycj_zdysyid_v2: undefined,
  axi_name: undefined,
  mode: '2',
  file: undefined,
  axi_rxcj_spwj_v2: undefined,
})
function onSubmit() {
  request({
    url: '/aimooc/xnszr_img/add',
    data: {
      aimooc_xnszr_img: {
        axi_is_system: 2,
        axi_name: form.axi_name,
        axi_rxcj_spwj_v2: form.axi_rxcj_spwj_v2,
      }
    }
  }).then((res: any) => {
    const info = res.data.one_info
    console.log('info : ', info)
    if (res?.code === '1') {
      showDialog({
        title: '提示',
        message: '提交成功',
        confirmButtonText: '返回首页',
      }).then(() => {
        router.back()
      })
    } else {
      showDialog({
        title: '提示',
        message: res?.msg,
        confirmButtonText: '重新提交',
      }).then(() => {
        onSubmit()
      })
    }
    // router.back()
  })
};

function afterRead(file: any) {
  file.status = 'uploading';
  file.message = '上传中...';
  console.log('文件类型 : ', file.file.type)
  // form.axi_rxcj_spwj_v2 = file.content
  request({
    url: '/upload/main/file',
    // 120 min
    timeout: 120 * 60000,
    data: {
      filedata: file.file
    },
    transformRequest: [
      function (data: any) {
        const formData = new FormData();
        Object.keys(data).forEach(key => formData.append(key, data[key]))
        return formData;
      },
    ],
  }).then((res: any) => {
    console.log('res : ', res)
    if (res?.code === '1') {
      form.axi_rxcj_spwj_v2 = res.data.url
      file.status = 'finished';
      file.message = '上传成功';
    } else {
      showFailToast(res?.msg)
      file.status = 'failed';
      file.message = '上传失败';
    }
  }).catch((error: any) => {
    if (error.code === 'ECONNABORTED') {
      showFailToast('请求超时，请检查网络连接并重试')
    }
    file.status = 'failed';
    file.message = '上传超时';
  })
}

function changeMode(name: string) {
  if (form.axi_rxcj_spwj_v2) {
    form.file = undefined
    form.axi_rxcj_spwj_v2 = undefined
  }
  if (name === '2') {
    try {
      navigator?.mediaDevices
        ?.getUserMedia({ video: true })
        ?.catch(() => {
          showDialog({
            title: '提示',
            message: '请在设置中打开相机权限,如果已经打开依然提示说明您的浏览器不支持',
          });
          form.mode = '1'
        });
    } catch (error) {
      showDialog({
        title: '提示',
        message: '请在设置中打开相机权限,如果已经打开依然提示说明您的浏览器不支持',
      });
      form.mode = '1'
    }
  }
}

// 2G 视频大小限制
const videoSize = 2 * 1024 * 1024 * 1024;

function beforeRead (file: any) {
  console.log('上传视频预校验 : ', file)
  if(file.type !== 'video/mp4' && file.type !== 'video/mov' && file.type !== 'video/webm'){
    showFailToast('视频类型'+file.type+'不支持采集，请上传 mp4、mov、webm 格式的视频')
    return false
  }
  if (file.size > videoSize){
    showFailToast('文件大小不能超过 2GB')
    return false
  }else{
    return true
  }
}

</script>

<template>
  <van-nav-bar title="选择人像采集模式" left-arrow @click-left="onClickLeft"></van-nav-bar>
  <div class="flex-auto py-4 ">
    <van-form class="h-full flex flex-col" @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="form.axi_name" name="请输入数字人名称" label="数字人名称" placeholder=""
          :rules="[{ required: true, message: '数字人名称不能为空' }]" />
        <van-field name="请选择人像采集模式" label="人像采集模式">
          <template #input>
            <van-radio-group v-model="form.mode" @change="changeMode">
              <van-radio name="2">已有录制，上传视频</van-radio>
              <van-radio class="mt-14px" name="1">手机录制</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field v-if="form.mode === '1'" name="录制视频" label="录制视频" :rules="[{ required: true, message: '录制视频不能为空' }]">
          <template #input>
            <van-uploader v-model="form.file" :max-count="1" accept="video/mp4,video/mov,video/webm" capture="user" :after-read="afterRead"
              :max-size="videoSize" :before-read="beforeRead ">
              <van-button type="primary">手机录制入口</van-button>
            </van-uploader>
          </template>
        </van-field>
        <van-field v-if="form.mode === '2'" name="上传视频" label="上传视频" :rules="[{ required: true, message: '上传视频不能为空' }]">
          <template #input>
            <van-uploader v-model="form.file" :max-count="1" accept="video/mp4,video/mov,video/webm" :after-read="afterRead"
              :max-size="videoSize" :before-read="beforeRead " />
          </template>
        </van-field>

      </van-cell-group>
      <div class="px-4 mt-20">
        <van-button block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
