<template>
  <div class="main">
    <van-form @submit="save" class="form">
      <van-field v-model="state.entity.course_name" readonly right-icon="arrow"
                 label="课程体系" required colon />
      <van-field v-model="state.entity.section_name" label="章节" required colon />
      <van-field v-model="state.entity.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="state.entity.course_text" label="说明" colon required autosize rows="3"
                 type="textarea" placeholder="请输入课程说明" />
      <van-cell title="共享给老师" v-if="state.entity.teachers?.vals?.length"
                title-class="van-field__label" colon>
        <div v-for="teacher in state.entity.teachers?.vals">
          <van-tag type="primary" size="medium">
            {{ teacher.teacher_name }}
          </van-tag>
        </div>
      </van-cell>
      <van-field label="图片" readonly colon></van-field>
      <qupu-map-editor :qupu="state.qupu" :ref_id="state.entity.id" @submit="save_notes"
                       :resource_note_group="state.entity.resource_note_group">
      </qupu-map-editor>
      <van-field label="视频" readonly colon placeholder="标星的为示范曲" input-align="right"/>
      <div class="uploader">
        <upload-progress>
          <multi-video-uploader :can-set-shifan="true" :readonly="true" v-model="state.videoList" />
        </upload-progress>
      </div>
      <template v-if="state.audioList.length">
        <van-field label="音频" readonly colon placeholder="标星的为示范曲" input-align="right"/>
        <div class="uploader">
          <audio-card :readonly="true" :can-set-shifan="true" :model-value="state.audioList"></audio-card>
        </div>
      </template>
      <div class="foot">
        <van-button block class="btn-submit" :disabled="!!loading" type="primary" native-type="submit">保存</van-button>
        <van-button block class="btn-submit" :disabled="!!loading" type="default" @click="$router.back()">取消</van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts">
import {computed, defineComponent, onBeforeMount, onBeforeUnmount, reactive, ref} from 'vue';
import {
  Button,
  Cell,
  Dialog,
  Field,
  Form,
  Image,
  Loading,
  Picker,
  Popup,
  showFailToast,
  showNotify,
  Tag,
  Toast,
  Uploader
} from 'vant';
import UploadProgress from '~/components/upload-progress.vue';
import MultiVideoUploader from '~/components/multi-video-uploader.vue';
import PhotoUploader from '~/components/photo-uploader.vue';
import {useRouter} from "vue-router";
import useUser from '~/store/user';
import useLoading from "~/store/loading";
import useJihua from "~/store/jihua";
import useDaka from "~/store/daka";
import AudioCard from "~/components/audio-card.vue";
import {CommentRefTypes, CourseSection, RefResource, RefResourceTypes, RefTypes, TimeUnits} from "~/types";
import useCourseCategory from "~/store/qumu-category";
import QupuMapEditor from "~/components/qupu-map-editor.vue";
import usePiyue from "~/store/piyue";
import useComment from "~/store/comment";
import {PiyueLockMinutes, uuid} from "~/utils";
import useSession from "~/store/session";
import usePool from "~/store/pool";

export default defineComponent({
  name: "course-section-modify",
  components: {
    [AudioCard.name]: AudioCard,
    [Loading.name]: Loading,
    [Dialog.name]: Dialog,
    [Toast.name]: Toast,
    [Button.name]: Button,
    [Image.name]: Image,
    [Form.name]: Form,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [UploadProgress.name]: UploadProgress,
    [MultiVideoUploader.name]: MultiVideoUploader,
    [PhotoUploader.name]: PhotoUploader,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [Cell.name]: Cell,
    [Tag.name]: Tag,
    [QupuMapEditor.name]: QupuMapEditor
  },
  props: {
    params: {}
  },
  setup({params}: any) {
    let { jihua_id, daka_id, qs_id } = params;
    const {getRNG} = usePiyue()
    const router = useRouter();
    const usingUser = useUser();
    const usingQC = useCourseCategory();
    const usingJihua = useJihua();
    const usingDaka = useDaka();
    const showPicker = ref(false)
    const {loading} = useLoading();
    const {check_resource_notes_task} = useComment();
    const {setRemoteCache, getRemoteCache, delRemoteCache} = usePool()
    const session = useSession()
    const ref_resources = ref<RefResource[]>([])
    const state = reactive<{
      entity: CourseSection,
      qupu?: RefResource,
      videoList: RefResource[],
      audioList: RefResource[]
    }>({
      entity: {}, videoList: [], audioList: []
    })
    const editing = ref(false)

    onBeforeMount(async () => {
      if (jihua_id) {
        if (!usingJihua.store.current?.id) {
          await usingJihua.read(jihua_id)
        }
        state.entity = usingJihua.store.current.course_sections.find(qs => qs.id === qs_id);
        session.write("JIHUA", await usingJihua.prepare())
      } else if (daka_id) {
        if (!usingDaka.store.current?.id) {
          await usingDaka.read(daka_id)
        }
        // check lock
        let payload = {
          union_id: usingUser.store.current.union_id,
          hty_id: usingUser.store.current.hty_id,
          real_name: usingUser.store.current.real_name
        }
        let key = "edit_daka_qs_" + usingDaka.store.current.id;
        let tmp = await getRemoteCache(key);
        if (tmp) {
          try {
            tmp = JSON.parse(tmp)
          } catch (e) {
            console.log('json parse failed...', e)
          }
          if (tmp.hty_id !== payload.hty_id) {
            showNotify(tmp.real_name + "老师正在编辑该打卡，您当前只能查看不可编辑！")
            router.back();
            return;
          } else {
            await setRemoteCache(key, payload, PiyueLockMinutes, TimeUnits.MINUTE)
          }
        } else {
          await setRemoteCache(key, payload, PiyueLockMinutes, TimeUnits.MINUTE)
        }

        state.entity = usingDaka.store.current.course_sections.find(qs => qs.id === qs_id);
        console.log(state.entity)
        session.write("DAKA", await usingDaka.prepare())
        editing.value = true;
      }
      let resources = state.entity.ref_resources || state.entity.resources || [];
      state.qupu = resources.find((r: RefResource) => r.ref_type === RefTypes.CourseSection && r.resource_type === RefResourceTypes.Picture);
      state.videoList = resources.filter((r: RefResource) => r.resource_type === RefResourceTypes.Video);
      state.audioList = resources.filter((r: RefResource) => r.resource_type === RefResourceTypes.Audio);
      ref_resources.value = resources
      usingUser.set_editing(true)
      await usingQC.query()
    });

    onBeforeUnmount(() => {
      session.clear();
      if (editing.value) {
        delRemoteCache("edit_daka_qs_" + usingDaka.store.current.id)
      }
    })

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

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

    const save = async (nav_back = true) => {

      let {qupu, videoList, audioList} = state;
      if (nav_back) {
        let {section_name, course_text} = state.entity;
        if (!section_name) {
          showFailToast("请输入章节！")
          return;
        }

        if (!course_text) {
          showFailToast("请输入课程体系说明！")
          return;
        }
      }

      let data = {...state.entity}
      let resources = [...videoList, ...audioList];
      if (qupu) {
        // restore qupu resource
        resources.push(...ref_resources.value.filter(r => r.resource_type === RefResourceTypes.Picture));
      }
      data.ref_resources = resources.map(({ref_id, ...rest}) => ({...rest, ref_id: data.id}));
      if (jihua_id) {
        const r = await usingJihua.update(data)
        if (r) {
          if (nav_back) {
            await router.back();
          } else {
            await usingJihua.read(jihua_id, true);
            // sync new data to session
            session.write("JIHUA", await usingJihua.prepare());
            await check_resource_notes_task(state.entity.resource_note_group);
            return r;
          }
        }
      } else if (daka_id) {
        const r = await usingDaka.update(data)
        if (r) {
          if (nav_back) {
            await router.back();
          } else {
            await usingDaka.read(daka_id, true);
            // sync new data to session
            session.write("DAKA", await usingDaka.prepare());
            await check_resource_notes_task(state.entity.resource_note_group);
            return r;
          }
        }
      }
    }

    const save_notes = async ({marks, payload}) => {
      let rng = await getRNG(marks, payload);
      if (state.entity.resource_note_group) {
        let {ref_resource_ids, resource_note_ids, resource_notes, ...rest} = state.entity.resource_note_group;
        rng = {...rng, ...rest}
      }
      rng.id = rng.id || uuid();
      rng.ref_id = state.entity.id;
      rng.ref_type = RefTypes.CourseSection;
      for(let i = 0; i < rng.resource_notes?.length; i++) {
        let rn = rng.resource_notes[i];
        rn.id = rn.id || uuid();
        let comment = rn.comments && rn.comments[0];
        if (comment)  {
          comment.id = comment.id || uuid();
          comment.ref_id = rn.id;
          comment.ref_type = CommentRefTypes.ResourceNote;
          // set a id for ref resources since we do not save this data in the ref_resources table any more for this case
          // while we still need this id field to check if resource changed
          comment.ref_resources?.forEach(res => {
            res.id = res.id || uuid();
          })
          // only keep one comment
          rn.comments = [comment]
        }
      }
      state.entity.resource_note_group = rng;
      return await save(false)
    }

    return {
      state, save, loading, showPicker, onPick, categories, save_notes
    };
  }

});
</script>

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


      .uploader {
        padding: 0.16rem 0.32rem;
      }


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

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