<template>
    <div class="main">
        <van-form @submit="save" class="form">
            <van-field v-model="store.current.course_name" readonly clickable right-icon="arrow"
                       @click="pickCourse" label="课程体系" required colon/>
            <van-field v-model="store.current.section_name" label="章节" required colon/>
            <van-field v-model="store.current.course_category_name" is-link readonly required colon
                       label="课程体系类型" placeholder="选择课程体系类型" @click="showPicker = true"/>
            <van-popup v-model:show="showPicker" round position="bottom">
                <van-picker
                        :columns="categories"
                        @cancel="showPicker = false"
                        @confirm="onPick"
                />
            </van-popup>
            <van-field v-model="store.current.course_text" label="说明" colon autosize required rows="3"
                       type="textarea" placeholder="请输入课程说明"/>
            <van-cell is-link @click="pickTeachers" title="共享给老师" v-if="canShare"
                    title-class="van-field__label" colon>
            <div v-for="teacher in store.current.teachers?.vals">
              <van-tag type="primary" size="medium">
                {{ teacher.teacher_name }}
              </van-tag>
            </div>
          </van-cell>
            <van-field label="图片" readonly colon/>
            <div class="uploader">
                <photo-uploader native v-model="store.qupuList" multiple :max-count="9" :do-upload="false"/>
            </div>
            <van-field label="视频" readonly colon placeholder="标星的为示范曲" input-align="right"/>
            <div class="uploader">
                <upload-progress>
                    <multi-video-uploader v-model="store.videoList"/>
                </upload-progress>
            </div>
            <div class="foot">
                <van-button block class="btn-submit" :disabled="!!loading" type="primary" native-type="submit">保存
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script lang="ts">
import {computed, defineComponent, onBeforeUnmount, onMounted, ref} from 'vue';
import {Button, Dialog, Field, Form, Image, Loading, Toast, Popup, Picker, Cell, Tag} from 'vant';
import UploadProgress from '~/components/upload-progress.vue';
import MultiVideoUploader from '~/components/multi-video-uploader.vue';
import {useRouter} from "vue-router";
import useCourseSection from "~/store/qumu-section";
import useUser from '~/store/user';
import PhotoUploader from '~/components/photo-uploader.vue';
import useLoading from "~/store/loading";
import useCourseCategory from "~/store/qumu-category";
import {HtySuperRoles, PickTargets} from "~/types";

export default defineComponent({
    name: "course-section-add",
    components: {
        [Loading.name]: Loading,
        [Dialog.name]: Dialog,
        [Toast.name]: Toast,
        [Button.name]: Button,
        [Image.name]: Image,
        [Form.name]: Form,
        [Field.name]: Field,
        [UploadProgress.name]: UploadProgress,
        [MultiVideoUploader.name]: MultiVideoUploader,
        [PhotoUploader.name]: PhotoUploader,
        [Popup.name]: Popup,
        [Picker.name]: Picker,
        [Cell.name]: Cell,
        [Tag.name]: Tag
    },
    setup({}) {
        const {loading} = useLoading();
        const router = useRouter();
        const usingQC = useCourseCategory();
        const {store, update, reset, find_draft, save_draft} = useCourseSection(router);
        const usingUser = useUser();
        const showPicker = ref(false)
        const timer = ref(0)
        reset();

        const canShare = computed(() => {
          let {roles, supervisor} = usingUser.store.current;
          return roles?.some(r => r.role_key === HtySuperRoles.SUPERVISOR) || !!supervisor
        })
        const pickCourse = () => {
            store.hanging = true;
            router.push('/course?picking=1')
        }

        const set_timer = () => {
            timer.value = setInterval(() => {
                let {videoList, current} = store;
                let resources = [...videoList]
                save_draft({...current, resources});
            }, 5000)
        }

        onMounted(async () => {
            usingUser.set_editing(true)
            await usingQC.query();
            if (!store.hanging) {
                let draft = await find_draft();
                if (draft) {
                    // 强制使用草稿，因为系统没有物理删除，直接删除草稿会保留很多无用数据
                    store.current = {...draft}
                    store.videoList = draft.resources || []
                }
                if (!store.current.course_category_key) {
                    let defaultQC = usingQC.getDefault()
                    if (defaultQC) {
                        store.current.course_category_key = defaultQC.category_key;
                        store.current.course_category_name = defaultQC.category_name;
                    }
                }
            }
            store.hanging = false
            set_timer();
        })

        onBeforeUnmount(() => {
            if (timer.value) {
                clearInterval(timer.value);
            }
        })

        const categories = computed(() => usingQC.store.list.map(x => ({text: x.category_name, value: x.category_key})))

        const onPick = ({selectedOptions}: any) => {
            let [{text, value}] = selectedOptions;
            store.current.course_category_key = value
            store.current.course_category_name = text
            showPicker.value = false;
        };

        const save = async () => {
            clearInterval(timer.value);
            update().catch(() => {
                set_timer();
            })
        }

        const pickTeachers = () => {
            store.hanging = true;
            router.push("/teacher/subsidiaries?multiple=1&target=" + PickTargets.COURSE_SECTION)
        }

        return {
            store, save, pickCourse, loading, categories, showPicker, onPick, canShare, pickTeachers
        };
    }

});
</script>

<style scoped lang="less">
.main {
  background: #FFFFFF;
  overflow: auto;

  .form {

    .uploader {
      padding: 0.16rem 0.32rem;
    }

    .foot {
      padding: 0.32rem;
      text-align: center;

      button {
        width: 90%;
        margin: auto;
      }
    }
  }
}
</style>
