<script setup>
import { ref, reactive, computed, watch } from 'vue'
import {apiAudio,apiVideo,apiMediaCommon} from '@/api/media'
import { apiAuthor } from '@/api/author'
import { ElMessage } from 'element-plus'

const emits = defineEmits('save')
const show = defineModel('show', { type: Boolean, default: false })
const props = defineProps({
    mediaType:{
        type:String,
        default:'audio',//audio or video
    },
    modifydata:{
        type:Object,
        default:{
            fileUrl:'',
            mediaName:'',
            author:'',
            labels:'',
            mediaCover:'',
            duration:0,
        }
    },
    modifyType:{
        type:String,
        default:'add',//add or edit
    },
    ImageUploadWidth:{
        type:String,
        default:'120px'
    },
    ImageUploadHeight:{
        type:String,
        default:'120px'
    },
})
const mediaName = computed(()=>{
    return {'audio':'音频','video':'视频'}[props.mediaType]
})
const dialogTitle = computed(()=>{
    return {'add':'上传','edit':'编辑',}[props.modifyType]+mediaName.value
})
const uploadAccept = computed(()=>{
    return props.mediaType==='audio'?'.mp3':'.mp4'
})
const uploadType = computed(()=>{
    return props.mediaType==='audio'?'audio/mpeg':'video/mp4'
})
const mediaData = reactive({
    fileUrl:'',
    mediaName:'',
    author:'',
    labels:'',
    mediaCover:'',
    duration:0,
})
watch(show,(newval)=>{
    if(newval){
        formRef.value?.clearValidate()
        uploadLoading.value = false
        Object.assign(mediaData,props.modifydata)
        mediaData.labels = mediaData.labels.length?mediaData.labels.split(',').map(i=>Number(i)):''
        const AuthorItem = authorList.value.find(i=>i.Id===mediaData.author)||''
        mediaData.author = AuthorItem
    }else{
        Object.assign(mediaData,{
            fileUrl:'',
            mediaName:'',
            author:'',
            labels:'',
            mediaCover:'',
            duration:0
        })
    }
})

//获取研究员列表
let authorList = ref([])
function getAuthorList(){
    apiAuthor.getAuthorList({
        PageSize:999,
        CurrentIndex:1,
    }).then(res=>{
        if(res.Ret!==200) return 
        authorList.value = res.Data.List||[]
    })
}
getAuthorList()
//获取标签列表
let labelList = ref([])
function getLableList(){
    apiMediaCommon.getPermissionList().then(res=>{
        if(res.Ret!==200) return
        labelList.value = res.Data.List||[]
        //没有二级品种的标签禁用
        labelList.value = labelList.value.map(i=>{return {...i,disabled:!i.children}})
    })
}
getLableList()
//点击上传按钮
const uploadLoading = ref(false)
const uploadRef = ref(null)
function handleUpload(){
    uploadRef.value?.$el.getElementsByTagName('input')[0].click()
}
async function handleUploadMedia(file){
    uploadLoading.value = true
    const {type} = file.file
    if(type!==uploadType.value){
        ElMessage.warning(`仅支持${uploadAccept.value}格式的文件`)
        uploadLoading.value = false
        return 
    }
    let form = new FormData();
    form.append('File',file.file);
    const res = props.mediaType==='audio'
        ?await apiAudio.uploadAudioFile(form)
        :await apiVideo.uploadVideoFile(form)
    uploadLoading.value = false
    if(res.Ret!==200) return 
    mediaData.fileUrl = res.Data.Url||""
    mediaData.duration = res.Data.DurationMillisecond||0
    
}
//获取音频长度
function getAudioDuration(file){
    return new Promise((resolve,reject)=>{
        const audioContext = new AudioContext();
        const fileReader = new FileReader();
        fileReader.readAsArrayBuffer(file.file);

        fileReader.onload = function() {
        audioContext.decodeAudioData(fileReader.result)
            .then((buffer) => {
                resolve(buffer.duration||0)
            })
        };
    })
}

//保存音频/视频
const formRef = ref(null)
const rules = {
    fileUrl:[{required:true,message:'请上传文件'}],
    mediaName:[{required:true,message:`请输入${mediaName.value}名称`}],
    author:[{required:true,message:'请选择研究员'}],
    labels:[{required:true,message:'请选择标签'}],
    mediaCover:[{required:true,message:'请上传封面图片'}],
}
async function handleSave(){
    try{
        await formRef.value?.validate()
    }catch(e){ return }
    let res = null
    const params = {
        AnalystId:mediaData.author.Id,
        AnalystName:mediaData.author.Name,
        SrcUrl:mediaData.fileUrl,
        PermissionIds:Array.isArray(mediaData.labels)?mediaData.labels.join(','):'',
    }
    const otherParams = props.mediaType==='audio'?{
        AudioName:mediaData.mediaName,
        DurationMillisecond:mediaData.duration
    }:{
        VideoName:mediaData.mediaName,
        CoverSrc:mediaData.mediaCover,
        DurationMillisecond:mediaData.duration
    }
    if(props.modifyType==='add'){
        res = props.mediaType==='audio'
        ? await apiAudio.addAudio({...params,...otherParams})
        : await apiVideo.addVideo({...params,...otherParams})
    }else{
        res = props.mediaType==='audio'
        ? await apiAudio.editAudio({...params,...otherParams,AudioId:mediaData.mediaId||0})
        : await apiVideo.editVideo({...params,...otherParams,VideoId:mediaData.mediaId||0})
    }
    if(res.Ret!==200) return 
    ElMessage.success(`${props.modifyType==='add'?'添加':'编辑'}成功`)
    show.value = false
    emits('save')
}
function handleUploadImg(file){
    //图片大小和格式限制
    const {size,type} = file.file
    const sizeLimit = 5*1024*1024
    if(!['image/png','image/jpeg'].includes(type)){
        ElMessage.warning('仅支持png、jpg格式的图片')
        return
    }
    if(size>sizeLimit){
        ElMessage.warning('视频封面不能超过5M')
        return
    }
    let form = new FormData();
    form.append('File',file.file);
    apiVideo.uploadVideoCover(form).then(res=>{
        if(res.Ret!==200) return 
        mediaData.mediaCover = res.Data?.Url||''
    })
}
</script>

<template>
    <el-dialog v-model="show" :title="dialogTitle" width="530px" draggable>
        <div class="content-wrap">
            <el-form label-width="95px" label-position="left" :model="mediaData" :rules="rules" ref="formRef">
                <el-form-item prop="fileUrl" class="upload-form-item">
                    <el-input :placeholder="props.mediaType==='audio'?'音频格式限制mp3':'视频格式限制mp4，编码器为H.264'" v-model="mediaData.fileUrl" disabled>
                        <template #append>
                            <el-button 
                                :loading="uploadLoading"
                                @click="handleUpload" 
                                style="background-color: #086CE0;color:#fff;border-top-left-radius:0;border-bottom-left-radius:0;">
                                {{uploadLoading?`上传中`:`上传${mediaName}`}}
                            </el-button>
                            <el-upload
                                ref="uploadRef"
                                action=""
                                :accept="uploadAccept"
                                :http-request="handleUploadMedia"
                                :show-file-list="false"
                                style="display: flex;"
                            >
                            </el-upload>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="mediaCover" label="照片" v-if="props.mediaType==='video'">
                    <ImageUpload
                        uploadHint="支持jpg、jpeg、png等格式，建议上传宽高比例为1920:1080的图片"
                        :imgUrl="mediaData.mediaCover"
                        :width="ImageUploadWidth"
                        :height="ImageUploadHeight"
                        @upload="handleUploadImg"
                        @remove="mediaData.mediaCover=''"
                    ></ImageUpload>
                </el-form-item>
                <el-form-item  prop="mediaName" :label="`${mediaName}名称`">
                    <el-input v-model="mediaData.mediaName" placeholder="请输入名称"></el-input>
                </el-form-item>
                <el-form-item prop="author" label="研究员名称">
                    <el-select v-model="mediaData.author" value-key="Id">
                        <el-option 
                            v-for="item in authorList" 
                            :key="item.Id"
                            :label="item.Name"
                            :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="labels" label="标签">
                    <el-cascader style="width: 100%;" 
                        v-model="mediaData.labels"
                        collapse-tags
                        collapse-tags-tooltip
                        :options="labelList"
                        :props="{
                            value:'id',
                            label:'name',
                            emitPath:false,
                            multiple:true
                        }"
                        >
                    </el-cascader>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="footer-wrap">
                <el-button type="primary" plain size="large" @click="show = false">取消</el-button>
                <el-button type="primary" size="large" @click="handleSave">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss">
.content-wrap{
    .upload-form-item{
        margin-left: -95px;
    }
}
</style>
