<template>
    <div class="main">
        <van-form @submit="submit" class="form">
            <van-field v-model="state.course_name" is-link readonly required colon
                       label="课程" placeholder="选择课程" @click="showPicker = true"/>
            <van-popup v-model:show="showPicker" round position="bottom">
                <van-picker
                        :columns="state.course_options"
                        @cancel="showPicker = false"
                        @confirm="onPick"
                />
            </van-popup>
            <van-collapse v-model="activeNames" v-if="course_section">
                <van-collapse-item v-if="course_section.course_text" title="课程说明" name="shuoming">
                    <div>
                      <div v-for="line in course_section.course_text?.split('\n')">{{line}}</div>
                    </div>
                </van-collapse-item>
                <van-collapse-item title="课程示范" name="shifan" :label-class="has_shifan ? '' : 'no-shifan'"
                                   :label="has_shifan ? '': '课程尚无示范视频'">
                    <course-shifan :course-section="course_section"></course-shifan>
                </van-collapse-item>
            </van-collapse>
            <van-field label="练习录音"></van-field>
            <audio-record :label="'点击录音'" v-model="state.question"></audio-record>
            <van-field label="练习图片" readonly colon/>
            <div class="uploader">
                <photo-uploader native v-model="state.qupus" multiple :do-upload="false" :max-count="5"
                                :max-size="5 * 1024 * 1024"/>
            </div>
            <van-field label="练习视频" readonly colon/>
            <div class="uploader">
                <upload-progress>
                    <video-uploader v-model="state.videos"/>
                </upload-progress>
            </div>
            <van-field
                    v-model="state.text_question"
                    rows="2"
                    autosize
                    type="textarea"
                    maxlength="200"
                    placeholder="请输入留言"
                    show-word-limit
            />
            <div class="footer">
                <van-button round block :disabled="state.loading" class="btn-submit" type="primary"
                            native-type="submit">
                    {{ state.loading ? '提交中，请稍候...' : '提交' }}
                </van-button>
            </div>
        </van-form>
    </div>

</template>

<script lang="ts">
import {computed, defineComponent, onMounted, reactive, ref} from "vue";
import {Button, Field, Form, Picker, Popup, Toast, Collapse, CollapseItem, showFailToast} from "vant";
import UploadProgress from '~/components/upload-progress.vue';
import VideoUploader from '~/components/video-uploader.vue';
import PhotoUploader from '~/components/photo-uploader.vue';
import CourseShifan from '~/components/qumu-shifan.vue';
import {wxUtil} from '~/utils/wx';
import useJihua from "~/store/jihua";
import useDaka from '~/store/daka';
import useUser from "~/store/user";
import useNotify from "~/store/notify";
import useTask from "~/store/task";
import {useRouter} from "vue-router";
import usePool from "~/store/pool";
import {
    AudioAiScoreTask, AudioConvertTask, HtyBaseRoles,
    Lianxi, NotifyParam, NotifyTypes, RefResource,
    RefResourceTypes, ScoreFroms,
    TaskTypes,
    UploadedFile,
    UploadPhoto
} from "~/types";
import AudioRecord from '~/components/audio-record.vue';
import {ImageHelper} from "~/utils";
import useAudio from '~/store/audio'



interface LianxiState {
    jihua_course_section_id: string,
    daka_course_section_id: string,
    course_section_id: string,
    course_name: string,
    text_question: string,
    videos: UploadedFile[],
    qupus: Partial<UploadPhoto>[],
    question: { media_id: string, audio_url?: string },
    course_options: any[],
    loading: boolean
}

export default defineComponent({
    name: "student-lianxi-add",
    components: {
        [Form.name]: Form,
        [Field.name]: Field,
        [Button.name]: Button,
        [Popup.name]: Popup,
        [Picker.name]: Picker,
        [VideoUploader.name]: VideoUploader,
        [AudioRecord.name]: AudioRecord,
        [UploadProgress.name]: UploadProgress,
        [PhotoUploader.name]: PhotoUploader,
        [CourseShifan.name]: CourseShifan,
        [Collapse.name]: Collapse,
        [CollapseItem.name]: CollapseItem
    },
    props: {
        params: {}
    },
    setup({params}: any) {
        wxUtil.init(['startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice']);

        const usingJihua = useJihua();
        const usingDaka = useDaka();

        const usingAudio = useAudio();
        const usingUser = useUser();
        const {notify_ws} = useNotify();
        const {createTask} = useTask();
        const {setKey} = usePool()
        const activeNames = ref(['shifan'])

        const state = reactive<LianxiState>({
            daka_course_section_id: '',
            jihua_course_section_id: '',
            course_section_id: '',
            course_name: '',
            text_question: '',
            videos: [],
            qupus: [],
            question: {media_id: ''},
            course_options: [],
            loading: false,
        });
        if (params.jihua_id) {
            usingJihua.read(params?.jihua_id).then(() => {
                let {course_sections, relations} = usingJihua.store.current;
                if (course_sections.length === 1) {
                    let first = course_sections[0];
                    let relation = (relations || [])[0];
                    state.jihua_course_section_id = relation.id as string;
                    state.course_name = `${first.course_name}(${first.section_name})`;
                    state.course_section_id = first.id as string;
                }
                state.course_options = course_sections.map(x => ({
                    text: `${x.course_name}(${x.section_name})`, value: x.id, jihua_course_section_id: (relations || []).find(y => y.course_section_id === x.id)?.id
                }));
                usingUser.set_editing(true)
            });
        } else if (params.daka_id) {
            usingDaka.read(params?.jihua_id).then(() => {
                let {course_sections, relations} = usingDaka.store.current;
                if (course_sections.length === 1) {
                    let first = course_sections[0];
                    let relation = (relations || [])[0];
                    state.daka_course_section_id = relation.id as string;
                    state.course_name = `${first.course_name}(${first.section_name})`;
                    state.course_section_id = first.id as string;
                }
                state.course_options = course_sections.map(x => ({
                    text: `${x.course_name}(${x.section_name})`, value: x.id, daka_course_section_id: (relations || []).find(y => y.course_section_id === x.id)?.id
                }));
                usingUser.set_editing(true)
            });
        }

        const router = useRouter();
        const recorder = ref<InstanceType<typeof AudioRecord>>()

        const showPicker = ref(false);
        const onPick = ({selectedOptions}: any) => {
            let [value] = selectedOptions;
            state.course_name = value.text;
            state.jihua_course_section_id = value.jihua_course_section_id;
            state.daka_course_section_id = value.daka_course_section_id;
            state.course_section_id = value.value;
            showPicker.value = false;
        };

        const submit = async () => {
            state.loading = true;
            await usingAudio.stopRecord();
            let {videos, qupus, text_question, jihua_course_section_id, daka_course_section_id} = state;
            if (!jihua_course_section_id && !daka_course_section_id) {
                showFailToast('请选择练习课程！')
                state.loading = false;
                return Promise.reject()
            }
            let [video] = videos;
            if (!video && !state.question.media_id) {
                showFailToast('请添加练习视频或练习录音！')
                state.loading = false;
                return Promise.reject()
            }
            let data: Lianxi = {
                jihua_course_section_id,
                daka_course_section_id,
                ref_resources: [],
                text_question: text_question
            };
            if (qupus.length > 0) {
                let task_id = await ImageHelper.combine_by_form(qupus);
                if (!task_id) {
                    state.loading = false;
                    return Promise.reject();
                }
                let qupu_resource: RefResource = {
                    resource_type: RefResourceTypes.Picture,
                    ref_type: "Lianxi",
                    ref_name: "练习图片",
                    tasks: {vals: [{task_id, task_type: TaskTypes.UPLOAD_PICTURE}]}
                }
                data.ref_resources.push(qupu_resource)
            }
            if (video) {
                data.ref_resources.push({
                    resource_type: RefResourceTypes.Video,
                    ref_type: "Lianxi",
                    ref_name: "练习视频",
                    resource_url: video.url,
                    hty_resource_id: video.hty_resource_id,
                    tasks: video.tasks
                })
            }
            let shifan, creator, teacher_id, getter, subsidiaries;
            if (jihua_course_section_id) {
                delete data.daka_course_section_id;
                teacher_id = usingJihua.store.current.teacher_id;
              shifan = await usingJihua.get_shifan(data.jihua_course_section_id);
                creator = usingJihua.create_jihua_lianxi;
                getter = usingJihua.get_lianxi_by_id
            } else if (daka_course_section_id) {
                delete data.jihua_course_section_id
                teacher_id = usingDaka.store.current.teacher_id;
                subsidiaries = usingDaka.store.current.teachers?.vals;
                shifan = await usingDaka.get_shifan(data.daka_course_section_id);
                creator = usingDaka.create_daka_lianxi;
                getter = usingDaka.get_lianxi_by_id
            }
            if (!creator) return;
            if (state.question.media_id) {
                if (!shifan) {
                    let task_id = await createTask({task_type: TaskTypes.CONVERT_AUDIO_FILE, payload: {media_id: state.question.media_id}});
                    data.ref_resources.push({
                      resource_type: RefResourceTypes.Audio,
                      ref_type: "Lianxi",
                      ref_name: "练习录音",
                      tasks: {
                        vals: [{
                          task_id, task_type: TaskTypes.CONVERT_AUDIO_FILE,
                          task_meta: {media_id: state.question.media_id}
                        }]
                      }
                    })
                } else {
                    data.ref_resources.push({
                        resource_type: RefResourceTypes.Audio,
                        ref_type: "Lianxi",
                        ref_name: "练习录音",
                    })
                }

            }
            let lianxi_id = await creator(data)
            if (lianxi_id) {
                notify_ws({ hty_id: teacher_id, course_name: course_section?.course_name, course_section_name: course_section?.section_name, lianxi_id, notify_type: NotifyTypes.LianxiCreate } as NotifyParam, HtyBaseRoles.TEACHER)
                // send notification to subsidiaries
                subsidiaries?.forEach(t => {
                    // avoid to send duplicate notification to same teacher
                    // subsidiaries may contain main teacher
                    if (t.teacher_id !== teacher_id) {
                      notify_ws({ hty_id: t.teacher_id, course_name: course_section?.course_name, course_section_name: course_section?.section_name, lianxi_id, notify_type: NotifyTypes.LianxiCreate } as NotifyParam, HtyBaseRoles.TEACHER)
                    }
                })

                if (state.question.media_id && shifan && getter) {

                    let lianxi: any = getter(lianxi_id);

                    if (lianxi) {
                        let audio = lianxi.ref_resources?.find((r: RefResource) => r.resource_type == RefResourceTypes.Audio);
                        let {shifan_url, audio_type} = shifan
                        let task = {
                            task_type: TaskTypes.AUDIO_FILE_AI_SCORE,
                            payload: {
                                aiScorePayload: {
                                    ref_id: lianxi_id, ref_type: "Lianxi",
                                    audio_type, reference_url: shifan_url,
                                    score_from: ScoreFroms.MachineLearning,
                                },
                                audioPayload: {
                                    ref_resource_id: audio?.id,
                                    media_id: state.question.media_id,
                                }
                            }
                        } as AudioAiScoreTask;
                        let task_id = await createTask(task);
                        audio.tasks = {
                            vals: [{
                                task_id: task_id,
                                task_type: TaskTypes.AUDIO_FILE_AI_SCORE,
                                task_meta: {media_id: state.question.media_id}
                            }]
                        }
                        audio.ref_id = lianxi_id
                        setKey("scoring_audio", audio);
                    }
                }
                await router.back();
            }
        };

        onMounted(() => {
            state.loading = false
        })

        const course_section = computed(() => (params.jihua_id ? usingJihua : usingDaka).store.current.course_sections.find(x => x.id === state.course_section_id));

        const has_shifan = computed(() => (course_section.value?.ref_resources || course_section.value?.resources)?.some(r => r.is_shifan))

        return {submit, state, recorder, showPicker, onPick, course_section, activeNames, has_shifan};
    }
});
</script>

<style scoped lang="less">
.form {
  background: #FFFFFF;
  height: 100%;
  padding-bottom: 1.5rem;
  overflow: auto;

  &::-webkit-scrollbar {
    display: none;
  }

  .uploader {
    padding: 0.16rem 0.32rem;
  }

  :deep(.no-shifan) {
    color: red;
  }

  .recorder {
    padding: 0.16rem 0.32rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  :deep(.audio-record) {
    padding: 0.16rem 0.32rem;
  }

  .footer {
    background: #FFFFFF;
    position: absolute;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0.2rem 5%;
    width: 100%;
    box-shadow: 0 -4px 4px 0px #dddddd;
    z-index: 400; // leaflet layer zindex

    .btn-submit {
      width: 100%
    }
  }
}
</style>
