<template>
  <div class="main">
    <van-search v-model.trim="state.keyword" @search="onRefresh" placeholder="请输入课程体系名称或段落搜索"></van-search>
    <div class="check-list" ref="checkList">
      <van-tag type="primary" @click="onClick(item)" @close="onClick(item)" closeable v-for="item in state.checked">{{item.course_name}}({{item.section_name}})</van-tag>
    </div>
    <van-tabs v-model:active="activeTab" @change="onRefresh">
      <van-tab v-for="tab in tabs" :name="tab.name" :title="tab.label"></van-tab>
    </van-tabs>
    <div class="list" :style="{'height': height}">
      <van-pull-refresh v-model="state.refreshing" @refresh="onRefresh">
        <van-list v-model:loading="state.loading" :finished="state.finished"
                  finished-text="没有更多数据了。" v-model:error="state.error"
                  error-text="请求失败，点击重新加载" @load="onPage"
        >
          <div v-for="item in dataset" :key="item.id" class="course-item">
            <van-cell center :label="item.section_name" :title="item.course_name" :value="item.course_category_name" inset>
              <template #icon>
                <van-icon color="#c8c9cc" class="course-toggle" size="0.5rem" name="arrow-down" v-if="item.closed" @click="() => onToggle(item)" />
                <van-icon color="#c8c9cc" class="course-toggle" size="0.5rem" name="arrow-up" v-else @click="() => onToggle(item)" />
              </template>
              <template #right-icon>
                <van-icon color="#07c160" size="0.5rem" name="checked" v-if="item.checked" @click="() => onClick(item)" />
                <van-icon color="#07c160" size="0.5rem" name="circle" v-else @click="() => onClick(item)" />
              </template>
            </van-cell>
            <div class="course-resource" v-if="!item.closed">
              <template v-if="get_qupu(item)?.url">
                <div class="qupu-map-root">
                  <qupu-map :background-url="get_qupu(item).url" :readonly="true" @pause="pause(item.id, $event)"
                            :marks="caches[item.id]?.resource_notes" />
                </div>
                <div class="divider"></div>
              </template>
              <upload-progress>
                <multi-video-uploader readonly :addable="false" downloadable :model-value="get_videos(item)" />
              </upload-progress>
            </div>
            <div class="qs-author-time van-cell__label">
              <strong>{{item.creator_name || "未知用户"}}</strong> 于 <strong>{{datetime(item.created_at) || "未知时间"}}</strong> 创建
            </div>
            <div class="qs-author-time van-cell__label">
              <strong>{{item.updator_name || "未知用户"}}</strong> 于 <strong>{{datetime(item.updated_at) || "未知时间"}}</strong> 更新
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
    <van-button class="btn-pick" type="primary" block :disabled="!state.checked.length" @click="onPick">确认</van-button>
  </div>
  <van-action-sheet :lock-scroll="false" v-model:show="state.replying" :title="'批注 ' + state.pausing"
                    @closeed="state.replying = false" :close-on-click-overlay="false">
    <comments-sheet :readonly="true" :ref_id="state.mark_id" @remove="state.replying = false"></comments-sheet>
  </van-action-sheet>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, onMounted, ref, watch, nextTick } from 'vue';
import {
  Button,
  Cell,
  SwipeCell,
  List,
  PullRefresh,
  Search,
  Icon,
  Tag,
  ActionSheet,
  Tabs,
  Tab,
  showFailToast
} from 'vant';
import useCourseSection from "~/store/qumu-section";
import useJihua from "~/store/jihua";
import useDaka from '~/store/daka';
import useCourseGroup from "~/store/qumu-section-group";
import useComment from "~/store/comment";
import useClazz from "~/store/clazz";
import CommentsSheet from "~/components/comments-sheet.vue";
import QupuMap from "~/components/qupu-map.vue";
import HtyImage from "~/components/hty-image.vue";
import UploadProgress from "~/components/upload-progress.vue";
import MultiVideoUploader from "~/components/multi-video-uploader.vue";
import {useRouter} from "vue-router";
import {CourseQueryParam, CourseSection, PickTargets, RefResourceTypes, ResourceNote} from '~/types';
import {DateFormatter, formatDate} from "~/utils";

export interface CourseState {
  loading: boolean,
  finished: boolean,
  error: boolean,
  keyword: string,
  refreshing: boolean,
  checked: CourseSection[],
  page: number,
  page_size: number,
  pausing: string,
  replying: boolean,
  mark_id: string,
  opening: string[]
}

export default defineComponent({
  name: "course-section-pick",
  components: {
    [List.name]: List,
    [Cell.name]: Cell,
    [Search.name]: Search,
    [Button.name]: Button,
    [PullRefresh.name]: PullRefresh,
    [Icon.name]: Icon,
    [SwipeCell.name]: SwipeCell,
    [Tag.name]: Tag,
    [ActionSheet.name]: ActionSheet,
    [CommentsSheet.name]: CommentsSheet,
    [QupuMap.name]: QupuMap,
    [HtyImage.name]: HtyImage,
    [UploadProgress.name]: UploadProgress,
    [MultiVideoUploader.name]: MultiVideoUploader,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab
  },
  props: {params: {} as any},
  setup({params}) {
    const usingJihua = useJihua();
    const usingDaka = useDaka();
    const usingCourseGroup = useCourseGroup();
    const usingClazz = useClazz();
    const state = reactive<CourseState>({
      loading: false,
      finished: false,
      error: false,
      keyword: '',
      refreshing: false,
      page: 1,
      page_size: 20,
      pausing: '',
      replying: false,
      mark_id: '',
      checked: ({
        [PickTargets.JIHUA]: usingJihua.store.current.course_sections,
        [PickTargets.DAKA]: usingDaka.store.current.course_sections,
        [PickTargets.COURSE_GROUP]: usingCourseGroup.store.current.course_sections
      }[params.target as PickTargets] || []),
      opening: []
    });
    const {get_resource_note_group} = useComment();
    const router = useRouter();
    const timer = ref(0);
    const checkList = ref(null)
    const caches: {[key: string]: any} = {};

    const height = ref("calc(100% - 1.08rem - 1.04rem - 0.16rem - 0.32rem - var(--van-button-default-height) - 0.16rem)");

    const { store, query } = useCourseSection(router);


    const activeTab = ref("mine")

    const tabs = [
      {name: "mine", label: "我的课程"},
      {name: "assigned", label: "共享课程"}
    ]

    const search = async (params: CourseQueryParam) => {
      state.finished = false;
      state.error = false;
      state.loading = true;
      let { keyword } = state;
      if (keyword) {
        keyword = keyword.replace(/\s+/g, ' ').trim();
        params.keyword = keyword || undefined;
      }
      state.error = !(await query(params, activeTab.value))
      state.page = params.page;
      if (store[activeTab.value].pages <= state.page) {
        state.finished = true;
      }
      state.loading = false;
    }


    const onRefresh = async () => {
      state.refreshing = true;
      await search({page: 1, page_size: state.page_size});
      state.refreshing = false;
    };

    watch(() => state.keyword, () => {
      if (timer.value) {
        clearTimeout(timer.value);
      }
      timer.value = window.setTimeout(() => {
        onRefresh();
      }, 500)
    })

    const onPage = async () => {
      if (state.finished) return;
      let { page, page_size } = state;
      await search({page: page + 1, page_size})
    }

    const dataset = computed(() => {
      return store[activeTab.value].list.map(x => {
        let item = {
          ...x,
          checked: false,
        }
        item.checked = state.checked.some(c => c.id === x.id);
        item.closed = !state.opening.includes(x.id as string)
        return item;
      });
    })

    const onClick = (item: CourseSection) => {
      if (state.checked.some(x => x.id === item.id)) {
        state.checked = state.checked.filter(x => x.id !== item.id)
      } else {
        state.checked.push(item);
      }
      nextTick(() => {
        let el = checkList.value as unknown as HTMLDivElement;
        height.value = `calc(100% - 1.08rem - 1.04rem - ${el.offsetHeight}px - 0.32rem - var(--van-button-default-height) - 0.16rem)`;
      })
    }

    const onToggle = async (item: CourseSection) => {
      let id = item.id as string;
      if (!caches[id]) {
        await get_resource_note_group(item)
        caches[id] = item.resource_note_group
      }
      if (state.opening.includes(id)) {
        state.opening = state.opening.filter(x => x !== id)
      } else {
        state.opening.push(id)
      }
    }

    const onPick = async () => {
      switch (params.target) {
        case PickTargets.JIHUA:
          usingJihua.store.current.course_sections = state.checked;
          break;
        case PickTargets.DAKA:
          usingDaka.store.current.course_sections = state.checked;
          break;
        case PickTargets.COURSE_GROUP:
          usingCourseGroup.store.current.course_sections = state.checked;
          break;
        case PickTargets.CLAZZ:
          usingClazz.store.current.course_sections = {vals: state.checked}
          break;
      }
      router.back();
    }


    const get_qupu = (qs: CourseSection) => {
      let resource  = qs.resources?.find(r => r.resource_type === RefResourceTypes.Picture);
      if (resource) {
        return { url: resource.resource_url, task: resource.tasks?.vals[0]}
      }
      return null
    }

    const get_videos = (qs: CourseSection) => {
      return (qs.resources || []).filter(r => r.resource_type === RefResourceTypes.Video);
    }


    const pause = (id: string, {serial_no}: ResourceNote) => {
      state.pausing = serial_no;
      state.mark_id = caches[id]?.resource_notes?.find((x: ResourceNote) => x.serial_no === serial_no)?.id || '';
      state.replying = true;
    }

    const datetime = (time: string | Date) => formatDate(time, DateFormatter.DateTime)


    onMounted(() => onRefresh());

    return {
      state, dataset, onRefresh, onClick, onPick, onPage, datetime, checkList, height, get_qupu, get_videos, pause, onToggle, caches, activeTab, tabs
    };
  }
});
</script>

<style scoped lang="less">

.main {
  width: 100vw;
  overflow: hidden;
  background: #f7f7f7;
  position: relative;

  .check-list {
    padding: 0.08rem 0.16rem;

    :deep(.van-tag) {
      margin: 0 0.08rem;
      cursor: pointer;
    }
  }

  .list {
    width: calc(100% - 0.32rem);
    height: calc(100% - 1.08rem - 1.04rem - 0.16rem - 0.32rem - var(--van-button-default-height) - 0.16rem);
    overflow: auto;

    margin: 0.16rem;

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

    .course-item  {
      background: #fff;
      margin-bottom: 10px;

      :deep(.van-cell__title) {
        flex: 4;
      }

      .course-toggle {
        margin: 0 4px 0 -12px;
        cursor: pointer;
      }

      .course-resource {
        padding: var(--van-padding-sm);
        box-shadow: 0 0 10px 5px rgba(0,0,0,0.1) inset;
        .qupu-map-root {
          height: 4rem;
        }

        .divider {
          height: 1px;
          background-color: #f2f3f5;
        }
      }


      .qs-author-time {
        padding: var(--van-padding-xs) var(--van-padding-sm) 0;
      }
    }


  }

  .btn-add {
    position: absolute;
    right: 0.24rem;
    bottom: 0.32rem;
  }

  .btn-pick {
    position: absolute;
    bottom: 0.16rem;
    height: 0.88rem;
    width: 90%;
    left: 5%;
  }

}
</style>
