<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="NuIotCameraUploadForm">
          <a-row>
						<a-col :span="24">
							<a-form-item label="录像类型" v-bind="validateInfos.videoType" id="NuIotCameraUploadForm-videoType" name="videoType">
                <a-select v-model:value="formData.videoType" placeholder="请选择设备状态">
                  <a-select-option value="1">定时录像</a-select-option>
                  <a-select-option value="2">移动侦测录像</a-select-option>
                  <a-select-option value="3">全部</a-select-option>
                </a-select>
              </a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="开始时间" v-bind="validateInfos.startTime" id="NuIotCameraUploadForm-startTime" name="startTime">
                <a-date-picker show-time placeholder="请选择开始时间" v-model:value="formData.startTime"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="结束时间" v-bind="validateInfos.endTime" id="NuIotCameraUploadForm-endTime" name="endTime">
                <a-date-picker show-time placeholder="请选择结束时间" v-model:value="formData.endTime"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="文件名称" id="NuIotCameraUploadForm-fileName" name="fileName">
								<a-input v-model:value="formData.fileName" placeholder="请输入文件名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="24" style="text-align: center">
              <a-button type="primary" preIcon="ant-design:cloud-upload-outlined" @click="uploadSummit" v-show="canUpload">回放上传</a-button>
              <a-button type="primary" preIcon="ant-design:disconnect-outlined" @click="uploadStop" v-show="!canUpload">停止上传</a-button>
<!--              <a-button type="primary" preIcon="ant-design:search-outlined" @click="getProgress">查询进度</a-button>-->
            </a-col>
          </a-row>
        </a-form>
        <a-row style="margin-top: 50px">
          <a-col :span="2">
          </a-col>
          <a-col :span="20">
            <a-progress :percent="percentRate" v-if="showPercent"/>
          </a-col>
        </a-row>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import {
  ref,
  reactive,
  defineExpose,
  nextTick,
  defineProps,
  computed,
  onMounted,
  watch,
  unref
} from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import {uploadToServer,stopUploadToServer,getUploadToServerProcess} from "@/views/iot/tplink/camera/camera.api";
  const props = defineProps({
    data: { type: Object, default: () => ({}) },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    deviceIndex: '',
    parentId: '',
    videoType: '',
    storageType: '0',
    fileName: '',
    startTime: '',
    endTime: '',
    taskId: '',
  });
  const percentRate = ref(0);
  const showPercent = ref(false);
  const timerRef = ref();
  const canUpload = ref(true);
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    videoType: [{ required: true, message: '请选择录像类型!' }],
    startTime: [{ required: true, message: '请选择开始时间!' }],
    endTime: [{ required: true, message: '请选择结束时间!' }],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  /**
   * 上传提交
   */
  async function uploadSummit(){
    await validate();
    let startTime = new Date(formData.startTime).getTime();
    startTime = Math.floor(startTime/1000);
    let endTime = new Date(formData.endTime).getTime();
    endTime = Math.floor(endTime/1000);
    let params = {
      videoType : formData.videoType,
      fileName : formData.fileName,
      startTime: startTime,
      endTime: endTime,
      deviceIndex: formData.deviceIndex,
      parentId: formData.parentId,
      storageType: formData.storageType
    }
    confirmLoading.value=true;
    await uploadToServer(params).then(res=>{
      confirmLoading.value=false;
      canUpload.value = false;
      const taskId = res.taskId;
      formData.taskId = taskId;
      percentRate.value = 0;
      showPercent.value = true;
      timerRef.value = setInterval(()=>{
        uploadProgress()
      },3000 );
    }).catch(res=>{
      console.log(res);
    });
  }

  /**
   * 上传暂定
   */
  function uploadStop(){
    let params = {
      taskId : formData.taskId
    }
    stopUploadToServer(params).then(res=>{
        clearInterval(timerRef.value);
        canUpload.value = true;
    }).catch(res=>{
      console.log(res);
    });
  }

  // function getProgress(){
  //   let params = {
  //     taskId : formData.fileName
  //   }
  //   getUploadToServerProcess(params).then(res=>{
  //     const process = res.process;
  //     percentRate.value = Math.round(process/10);
  //   }).catch(res=>{
  //     console.log(res);
  //   });
  // }

  /**
   * 上传进度
   */
  function uploadProgress(){
    if(showPercent.value){
      let params = {
        taskId : formData.taskId
      }
      getUploadToServerProcess(params).then(res=>{
        const process = res.process;
        percentRate.value = Math.round(process / 10);
        if (percentRate.value >= 100) {
          clearInterval(timerRef.value);
          canUpload.value = true;
        }
      }).catch(res=>{
        console.log(res);
      });
    }
  }

  /**
   * 销毁
   */
  function destroy(){
    clearInterval(timerRef.value);
  }

  onMounted(() => {
    watch(
      () => props.data,
      async () => {
        formData.deviceIndex = props.data.deviceIndex;
        formData.projectId = props.data.projectId;
        formData.regionId = props.data.regionId;
        formData.multitrans = props.data.multitrans;
        formData.scale = props.data.scale;
      },
      { deep: true, immediate: true }
    );
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
