<template>
    <div class="video-uploader">
        <template v-if="readonly">
            <hty-video :downloadable="downloadable" v-if="!!files?.length" :src="files[0].url" :simple="simple"/>
        </template>
        <template v-else>
      <span class="btn-close" v-if="!!files?.length" @click="remove">
        <van-icon name="cross" color="white"/>
      </span>
            <hty-video v-if="!!files?.length" :src="files[0].url" :removable="true" :simple="simple"/>
            <div class="video-uploader-input" v-if="!files.length">
                <van-uploader v-if="!!showButton" accept="video/*" :v-model="files" :before-read="beforeRead"
                              :after-read="afterRead" :max-size="50 * 1024 * 1024" @oversize="onOversize">
                    <van-button icon="plus" size="small" type="primary">上传视频</van-button>
                </van-uploader>
                <van-uploader v-else accept="video/*" :v-model="files" :before-read="beforeRead" :after-read="afterRead"
                              :max-size="100 * 1024 * 1024" @oversize="onOversize"></van-uploader>
            </div>
        </template>
    </div>
</template>

<script>
import {defineComponent, getCurrentInstance, inject} from 'vue';
import {Icon, Uploader, Button, showFailToast} from 'vant';
import {hwUpYun} from '~/utils/upyun';
import request from "~/utils/request";
import HtyVideo from '~/components/hty-video.vue'
import useTask, { tsCreateTaskLastError } from "~/store/task";
import {TaskFrom, TaskStatuses, TaskTypes} from "~/types";
import {MediaHelper} from "~/utils";


export default defineComponent({
    name: "video-uploader",
    components: {
        [Icon.name]: Icon,
        [Uploader.name]: Uploader,
        [HtyVideo.name]: HtyVideo,
        [Button.name]: Button
    },
    // props: {
    //   readonly: { type: Boolean, default: false },
    //   multiple: { type: Boolean, default: false },
    //   maxCount: { type: Number, default: 8 },
    //   showButton: { type: Boolean, default: false },
    //   showUpload: { type: Boolean, default: true },
    //   modelValue: Array<any> // 这行如果不在最后一个，在服务器上build会报错，逗号语法问题
    // }
    props: ['modelValue', "readonly", "simple", "showButton", "multiple", "maxCount", "downloadable"],
    emits: ['update:modelValue'],
    computed: {
        files: {
            get() {
                return this.modelValue;
            },
            set(value) {
                this.$emit('update:modelValue', value);
            }
        }
    },

    setup(props) {

        const instance = getCurrentInstance();

        const startProgress = inject('startProgress');
        const updateProgress = inject('updateProgress');
        const endProgress = inject('endProgress');
        const {createTask} = useTask()

        const beforeRead = (file) => {
            if (!file.type.startsWith("video")) {
                showFailToast('请上传视频文件！');
                return false;
            }
            return true;
        };

        const afterRead = async (file) => {
            startProgress();
            const {r, d, e} = await hwUpYun.upload(file.file, 'music-room', percentage => {
                updateProgress(percentage);
            });
            if (r) {
                const res = await request({
                    url: '/api/v1/uc/create_hty_resource', method: 'POST',
                    data: {filename: file.file.name, url: d}
                });
                if (res.r) {
                    const task_id = await createTask({
                        task_type: TaskTypes.VIDEO_COMPRESSION,
                        payload: {
                            file_url: d,
                            resolution_type: 'HD',
                            hty_resource_id: res.d,
                        },
                    });
                    if (!task_id) {
                        showFailToast(tsCreateTaskLastError.message || '视频压缩任务创建失败');
                        endProgress();
                        return;
                    }
                    instance?.emit('update:modelValue', [{
                        url: d,
                        hty_resource_id: res.d,
                        tasks: {
                            vals: [{
                                task_id,
                                task_type: TaskTypes.VIDEO_COMPRESSION,
                                task_status: TaskStatuses.PENDING,
                                task_from: TaskFrom.TaskServer,
                                created_at: new Date(),
                            }],
                        },
                    }]);
                } else {
                    showFailToast(res.e);
                }
            } else {
                showFailToast(e);
            }
            endProgress();
        };
        const onOversize = (file) => {
            showFailToast('文件大小不能超过100MB!');
        };

        const remove = async () => {
          await MediaHelper.remove(props.modelValue);
          instance?.emit('update:modelValue', [])
        }

        return {afterRead, onOversize, beforeRead, remove};
    }
});
</script>

<style scoped lang="less">

.video-uploader {

  position: relative;

  .btn-close {
    position: absolute;
    cursor: pointer;
    right: 0;
    top: 0;
    width: 0.5rem;
    height: 0.5rem;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;

    i {
      font-size: 0.28rem;
    }
  }

  .video-uploader-input {
    width: 100%;

  }
}

</style>
