<template>
  <div class="main">
    <template v-if="ready">
      <div class="body">
        <van-pull-refresh v-model="refreshing" @refresh="refresh">
          <van-cell title="日期" :value-class="{'text-unwrap': true, 'text-expired': expired}" :value="week" />
          <van-cell title="课程" is-link :arrow-direction="show_courses ? 'up': 'down'" @click="show_courses = !show_courses">
            共 {{entity.course_sections.length}} 条课程
          </van-cell>
          <course-section-group :show="show_courses" :dataset="entity.course_sections" />
          <van-cell title="教师" :value="entity.teacher_name" />
          <van-cell title="备注" :value="entity.beizhu" />
          <van-cell :border="false" title="我的练习"></van-cell>
          <lianxi-group :total="entity.lianxi_count" :movements="entity.course_sections" :removable="true" @remove="remove_lianxi" @piyue="view_piyue" />
        </van-pull-refresh>
      </div>
      <div class="footer">
        <van-badge v-if="comments_count || !expired" :content="comments_count" color="#0dcaf0" :show-zero="false" max="99">
          <van-button type="primary" @click="replying = true" >留言回复</van-button>
        </van-badge>
        <van-button type="primary" v-if="!expired"
                    @click="$router.push(`/student/lianxi/add?jihua_id=${entity.id}`)">添加练习</van-button>
      </div>
    </template>
    <DetailSkeleton v-else />
  </div>
  <van-action-sheet :lock-scroll="false" v-model:show="replying" title="留言回复" @close="removeComment" :close-on-click-overlay="false">
    <comments-sheet :disabled="expired" :ref_id="entity.id" :comment="commenting" @reply="replyComment" @submit="saveComment" @remove="removeComment"></comments-sheet>
  </van-action-sheet>
</template>

<script lang="ts">
import {computed, defineComponent, onBeforeUnmount, onBeforeMount, ref} from 'vue';
import {ActionSheet, Button, Cell, Empty, Icon, Image, PullRefresh, Tag, showFailToast, Badge, Collapse, CollapseItem, showConfirmDialog} from 'vant';
import useJihua from "~/store/jihua";
import {DateFormatter, formatDate} from "~/utils";
import {Lianxi, Comment, NotifyParam, NotifyTypes, CommentRefTypes, CommentContent, HtyBaseRoles} from "~/types";
import {wxUtil} from "~/utils/wx";
import AudioPlay from '~/components/audio-play.vue';
import CommentsSheet from '~/components/comments-sheet.vue'
import ScoreShow from '~/components/score-show.vue';
import LianxiGroup from '~/components/lianxi-group.vue';
import CourseGroup from '~/components/qumu-section-group.vue';
import {useRouter} from "vue-router";
import dayjs from "dayjs";
import useComment from "~/store/comment";
import useTimer from "~/store/timer";
import DetailSkeleton from '~/components/detail-skeleton.vue'
import useSession from "~/store/session";

export default defineComponent({
  name: "student-jihua-detail",
  components: {
    DetailSkeleton,
    [Cell.name]: Cell,
    [Button.name]: Button,
    [ActionSheet.name]: ActionSheet,
    [Tag.name]: Tag,
    [Icon.name]: Icon,
    [AudioPlay.name]: AudioPlay,
    [Empty.name]: Empty,
    [Image.name]: Image,
    [PullRefresh.name]: PullRefresh,
    [Badge.name]: Badge,
    [CommentsSheet.name]: CommentsSheet,
    [ScoreShow.name]: ScoreShow,
    [LianxiGroup.name]: LianxiGroup,
    [Collapse.name]: Collapse,
    [CollapseItem.name]: CollapseItem,
    [CourseGroup.name]: CourseGroup,
},
  props: {
    params: {}
  },
  setup({params}: any) {
    wxUtil.init(['playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'downloadVoice'])
    const {store, read, delete_jihua_lianxi, notify, prepare, create_jihua_comment, check_tasks} = useJihua();
    const {count_comments} = useComment();
    const {startTimer, stopTimer} = useTimer()
    const session = useSession();
    const router = useRouter();
    const show_courses = ref(false)
    const replying = ref(false)
    const ready = ref(false)

    const courses = computed(() => store.current.course_sections.map(x => `${x.course_name}(${x.section_name})`).join(','))
    const week = computed(() => [formatDate(store.current.start_date), formatDate(store.current.end_date)].join('~'));

    const entity = computed(() => store.current)

    const commenting = ref<Comment | null>(null)

    const refreshing = ref(false)

    const refresh = async () => {
        ready.value = false;
        await read(params?.id, true);
        refreshing.value = false;
        if (store.current.id) {
            stopTimer();
            startTimer(() => store.current, check_tasks)
        }
        ready.value = true
    }

    const notify_comment = ({comment_id, serial}: {comment_id: string, serial?: string}) => {
      
      let params: NotifyParam = {
        notify_type: NotifyTypes.StudentCommentJihua,
        hty_id: store.current.teacher_id,
        hty_id2: store.current.student_id,
        jihua_id: store.current.id,
        comment_id, serial
      }
      notify(params, HtyBaseRoles.TEACHER)
    }

    const replyComment = (parent_id?: string) => {
      commenting.value = { parent_id, ref_type: CommentRefTypes.Jihua, content: {} as CommentContent} as Comment
    }

    const saveComment = async () => {
      let comment = commenting.value as Comment;
      comment.ref_id = store.current.id;
      let created = await create_jihua_comment(comment);
      if (created) {
        commenting.value = null;
        notify_comment({comment_id: created.id})
      }
    }

    const removeComment = () => {
      commenting.value = null;
      replying.value = false;
    }

    onBeforeMount(async () => {
      ready.value = false;
      let { id, comment_id, qs, from_tongzhi } = params;
      await read(id, true);
      if (store.current.is_delete) {
        showConfirmDialog({
          message: "该计划已被老师删除",
          cancelButtonText: "返回通知",
          confirmButtonText: "查看计划列表",
          showCancelButton: !!from_tongzhi
        }).then(() => {
          router.replace("/student/jihua")
        }).catch(() => {
          router.back();
        })
        return;
      }
      if (comment_id) {
        replying.value = true;
      }
      if (qs) {
        show_courses.value = true;
      }
      if (store.current.id) {
        session.write("JIHUA", await prepare())
        startTimer(() => store.current, check_tasks)
      }
      ready.value = true;
    })

    onBeforeUnmount(() => {
      session.clear();
      stopTimer()
    })

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

    const remove_lianxi = async (lianxi: Lianxi) => {
      if (lianxi.piyue) {
        showFailToast('该练习已有批阅，不能删除')
        return;
      }
      showConfirmDialog({
        title: "删除练习",
        message: "操作不可撤销，确认删除当前练习？"
      }).then(async () => {
        await delete_jihua_lianxi(lianxi);
      }).catch(() => {})
    }

    const view_piyue = (lianxi: Lianxi) => {
      store.current_lianxi = lianxi;
      router.push(`/student/jihua/piyue?jihua_id=${store.current.id}&lianxi_id=${lianxi.id}`)
    }

    const expired = computed(() => dayjs(entity.value.end_date).valueOf() < dayjs().startOf('date').valueOf())

    const comments_count = computed(() => count_comments(store.current.id))

    return {
      entity, courses, week, datetime, remove_lianxi, replying, commenting,
      view_piyue, refreshing, refresh, show_courses, expired, comments_count,
      replyComment, saveComment, removeComment, ready
    }
  }
});
</script>

<style scoped lang="less">
  .main {

    .body {
      height: calc(100% - var(--van-button-default-height) - 0.32rem);
      overflow: auto;
      background: #FFFFFF;
      &::-webkit-scrollbar {
        display: none;
      }

      :deep(.van-pull-refresh) {
        min-height: 100%;
      }

      .courses {
        padding: 8px;
        box-shadow: inset 0 0 3px 8px #f2f3f5;
        .course-row {

          background: transparent;

          .course-text {
            padding: 0.12rem 0.24rem;
            font-size: 0.24rem;
          }

          .course-resource {
            padding: 6px;

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

    }

    .footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 0.16rem 0.32rem;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .van-badge__wrapper {
        display: inline-flex;
        width: 40%;
        
        button {
          width: 100%;
        }
      }

      button {
        width: 40%;
      }
    }

  }
</style>
