<script setup>
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { VueCropper } from 'vue-cropper'
import 'vue-cropper/dist/index.css'
import { REQUEST } from '~/utils/request';
import mp3Png from '~/assets/mp3.jpg'
const props = defineProps({
  pid: String
})

let form = $ref({
  file: '',
  yys_id: '',
  // grade_name: '',
  // subject_id: '',
  // subject_name: '',
})


const rules = {
  file: [
    { required: true, message: '请上传学生作业', trigger: 'submit' },
  ],
  yys_id: [
    { required: true, message: '请选择所属作业', trigger: 'submit' },
  ],
}

let isRead = $ref(false)
let formRef = $ref()
async function handleSubmit() {
  // console.log('CropperFileRefs :>> ', CropperFileRefs);
  // return
  if (isRead) {
    const allCropper = await Promise.all(CropperFileRefs.map(async (CropperFileRef, idx) => new Promise((resolve, reject) => {
      CropperFileRef.getCropBlob(cropBlob => {
        const cropFile = new File([cropBlob], 'crop.jpeg', { type: cropBlob.type })
        REQUEST.upload({
          url: '/upload/main/file',
          data: { filedata: cropFile }
        }).then(res => {
          console.log('res :>> ', res);
          if (res.code == 1) {
            filelist[idx].crop = res.data.url;
            resolve(res.data.url)
          } else {
            reject(null)
          }
        })
      })
    })))
    console.log('allCropper :>> ', allCropper);
    formRef.validate().then((res) => {
      if (res === true) {

        request({
          url: `/yzy/zy_ssys_dtjl/add`,
          data: {
            yzy_zy_ssys_dtjl: filelist.map(({ keyword, file, crop }) => ({
              yzsd_keyword: keyword,
              yzsd_file: file,
              yys_id: form.yys_id,
              ks_id: props.pid,
              yz_img_cropping: crop
            }))
          }
        }).then(res => {
          if (res.code === '1') {
            ElMessage.success('上传成功')
            handleBack()
          }
        })
      }
    })
  } else {
    ElMessage.warning('请先勾选协议')
  }
}

const router = useRouter()
function handleBack() {
  router.back()
}

let filelist = $ref([])
let CropperFileRefs = $ref([])

// 获取视频第一帧的 blob 地址
async function getFirstFrameBlob(videoUrl) {
  const video = document.createElement('video');
  video.src = videoUrl;
  video.crossOrigin = 'anonymous';
  video.autoplay = true;
  return new Promise((resolve) => {
    video.addEventListener('loadeddata', () => {
      const canvas = document.createElement('canvas');

      const ctx = canvas.getContext('2d');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      setTimeout(() => {
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        canvas.toBlob((blob) => {
          resolve(URL.createObjectURL(blob));
        }, 'image/png', 1);
      }, 1000)


    })
  })
}

const onceFinished = ref(false)
async function handleUploadFinished(list) {
  onceFinished.value = true
  filelist = await Promise.all(list.map(async item => {
    if (!item.response) return item
    const d = item.response.data
    const blob = d.ext !== 'mp4' ? (d.ext !== 'mp3' ? URL.createObjectURL(item.raw) : mp3Png) : (await getFirstFrameBlob(URL.createObjectURL(item.raw)))
    return {
      name: d.file_name,
      file: d.url,
      keyword: d.file_name?.substr(0, d.file_name?.lastIndexOf('.')) ?? '',
      type: d.ext,
      blob,
      crop: undefined
    }
  }))
}


const uploadInputRef = ref()
const changeIndex = ref()
function handleUploadInputClick(idx) {
  changeIndex.value = idx
  uploadInputRef.value.click()
}

async function handleuploadInputChange(e) {
  const file = e.target.files[0];
  const blob = URL.createObjectURL(file)
  filelist[changeIndex.value].blob = blob
}
</script>

<template>
  <div class="w-full shadow bg-white rounded-md flex items-center px-36 py-4">
    <div class="text-lg text-hex-050026">上传作业</div>
    <el-divider direction="vertical" />
    <div class="text-sm">
      <span class="text-hex-949494">作业</span>
      <span class="text-hex-949494"> - 全景课堂</span>
      <span class="text-hex-949494"> - 创建作业</span>
      <span> - 上传作业</span>
    </div>
  </div>

  <div class="w-full flex flex-col items-center shadow bg-white rounded-md mt-4 p-4">
    <div class="text-lg text-hex-050026 w-full font-semibold">上传作业</div>

    <div class="w-560px text-hex-949494">
      <el-form :model="form" label-position="top" ref="formRef" :rules="rules">
        <el-form-item label="所属作业" prop="yys_id">
          <remote-select v-model="form.yys_id" url="/yzy/zy_ssys/index" :d="{ 'ssyskc_id': props.pid }"
            :fields="['yys_id', 'yys_name']" :defaultValue="true" size="large" placeholder="全部"></remote-select>
        </el-form-item>

        <el-form-item label="学生作业" prop="file">
          <!-- .doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.mp4,.mp3, -->
          <file-upload-progress :disabled="onceFinished" v-model:part="form.file" accept=".jpg,.jpeg,.png,.mp4,.mp3"
            :sizeLimit="1500 * 1024" @compile="handleUploadFinished" multiple sizeLimitMsg="1500MB">
            <template #default>
              <div class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9">
                <i-akar-icons:plus v-show="!onceFinished" class="text-xl" />
                <i-akar-icons:arrow-repeat v-show="onceFinished" class="text-xl"
                  @click="ElMessage.warning('请刷新页面后重新上传作业')" />
              </div>
            </template>
            <template #tip>
              <!-- doc,docx,xls,xlsx,ppt,pptx,pdf,mp4,mp3（500M以内） -->
              <div class="mt-2">请一次性上传所有作业，支持格式：jpg,jpeg,png,mp4,mp3（1500MB以内）</div>
            </template>
            <template #file>
            </template>
          </file-upload-progress>
        </el-form-item>




        <div class="w-full grid grid-cols-3 gap-4">
          <input type="file" accept="image/png, image/jpeg, image/jpg" class="hidden" ref="uploadInputRef" multiple=false
            @change="handleuploadInputChange">
          <template v-if="filelist.length">
            <div class="flex_center" v-for="(i, idx) in filelist">
              <div class="rounded-xl border-2 bg-white flex flex-col overflow-hidden cursor-pointer" :key="i">
                <el-button size="small" @click="handleUploadInputClick(idx)">重新选取封面</el-button>
                <div class="w-full flex-none h-160px">
                  <!-- <img :src="getFullUrl(i.file)" alt="" class="w-full h-full" /> -->
                  <VueCropper autoCrop :img="(i.blob)" centerBox :ref="(el) => CropperFileRefs[idx] = el">
                  </VueCropper>
                </div>

                <div class="p-2 flex justify-between items-center flex-auto">
                  <el-input v-model="i.keyword" placeholder="请输入作业名称"></el-input>
                </div>
              </div>
            </div>
          </template>
        </div>


        <el-checkbox v-model="isRead" label="已阅读并同意《作业上传协议》" size="large" />

        <div class="flex justify-around items-center text-sm mt-8">
          <div class="w-166px h-50px flex_center rounded bg-hex-00A3FF text-white cursor-pointer" @click="handleSubmit">
            提交</div>
          <div class="w-166px h-50px flex_center rounded bg-hex-F4F4F4 text-hex-41387F cursor-pointer"
            @click="handleBack">关闭</div>
        </div>
      </el-form>
    </div>
  </div>
</template>


<style lang="scss" scoped></style>
