import {reactive} from 'vue'
import {saveWatchRecord} from "@/api/webApi/webVideo";

export const useVideoRecord = function () {
    const state = reactive({
        committed: false,
        duration: 0,
        percent: 0
    })

    const reset = function () {
        state.committed = false
        state.duration = 0
        state.percent = 0
    }

    const syncProgress = function ({currentTime, duration}) {
        state.duration = duration
        state.percent = 0 // for safe division
        if (duration > 0) state.percent = currentTime * 100 / duration
    }

    const commit = async function ({src, aliIdType}) {
        if (!src) return // 无效数据
        if (state.committed) return // 已提交
        if (!state.percent) return // 无效数据
        if (state.percent < 2) return // <2%播放太短，也不记，防止过度触发提交
        await saveWatchRecord(src, state.duration, state.percent, aliIdType)
        state.committed = true
        console.log('saveWatchRecord committed')
    }

    return {
        state,
        reset,
        syncProgress,
        commit
    }
}