<template>
  <div class="main">
    <template v-if="ready">
      <div class="body">
        <van-pull-refresh v-model="refreshing" @refresh="refresh">
          <van-cell title="学生" :value="entity.student_name" />
          <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 :can-modify="true" @modify="modify_course_section" :show="show_courses"  :dataset="entity.course_sections" />
          <van-cell title="计划期限" :value-class="{'text-unwrap': true, 'text-expired': expired}" :value="week" />
          <van-cell title="当前周期" v-if="entity.versioned_data?.length" :value-class="{'text-unwrap': true, 'text-expired': yanqi_expired}" :value="yanqi_week" />
          <van-cell title="备注" :value="entity.beizhu" />
          <van-cell :border="false" title="学生练习"></van-cell>
          <lianxi-group :total="entity.lianxi_count" :movements="entity.course_sections" @piyue="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 size="small" type="primary" @click="replying = true">留言回复</van-button>
        </van-badge>
        <van-button size="small" type="primary" v-if="!entity.lianxi_count && !expired" @click="$router.push('/teacher/jihua/edit?id=' + entity.id)">编辑</van-button>
        <van-button size="small" v-if="!entity.lianxi_count" type="danger" @click="onRemove()">删除</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, Dialog, Icon, Tag, Empty, PullRefresh, Badge, Collapse, CollapseItem, showConfirmDialog} from 'vant';
import useJihua from "~/store/jihua";
import {formatDate} from "~/utils";
import {useRouter} from "vue-router";
import {wxUtil} from "~/utils/wx";
import useSession from "~/store/session";
import {
  Lianxi,
  NotifyParam,
  NotifyTypes,
  CommentContent,
  Comment,
  CommentRefTypes,
  HtyBaseRoles, VersionedData,
} from "~/types";
import AudioPlay from '~/components/audio-play.vue';
import dayjs from "dayjs";
import CommentsSheet from '~/components/comments-sheet.vue'
import ScoreShow from '~/components/score-show.vue';
import LianxiGroup from '~/components/lianxi-group.vue';
import useComment from "~/store/comment";
import useTimer from "~/store/timer";
import CourseGroup from '~/components/qumu-section-group.vue';
import DetailSkeleton from '~/components/detail-skeleton.vue';

export default defineComponent({
  name: "teacher-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,
    [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, remove, delay, check_tasks, prepare, notify, create_jihua_comment} = useJihua();
    const {count_comments} = useComment()
    const {startTimer, stopTimer} = useTimer()
    const router = useRouter();
    const session = useSession();

    const replying = ref(false)
    const commenting = ref<Comment | null>(null)
    const entity = computed(() => store.current)
    const ready = ref(false)
    
    const onRemove = () => {
      showConfirmDialog({
        title: "删除计划",
        message: "操作不可撤销，确认删除当前计划？"
      }).then(async () => {
        if (await remove()) {
          await router.back();
        }
      });
    };

    const refreshing = ref(false);
    const show_courses = 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 week = computed(() => {
      let { start_date, end_date } = store.current;
      return [formatDate(start_date), formatDate(end_date)].join(' ~ ')
    });

    const expired = computed(() => {
      return dayjs(store.current.end_date).valueOf() < dayjs().startOf('date').valueOf();
    })

    const yanqi_week = computed(() => {
      let { yanqi_start_date, yanqi_end_date } = store.current;
      return [formatDate(yanqi_start_date), formatDate(yanqi_end_date)].join(' ~ ')
    })

    const yanqi_expired = computed(() => {
      return dayjs(store.current.yanqi_end_date).valueOf() < dayjs().startOf('date').valueOf();
    })

    const onDelay = () => {
      showConfirmDialog({
        title: "计划延期",
        message: "确认将当前计划向后延期一周？"
      }).then((async () => {
        let id = await delay();
        if (id) {
          router.back();
        }
      }))
    }

    const can_delay = computed(() => {
      let { start_date, versioned_data } = store.current;
      if (versioned_data && versioned_data.length > 0) {
        start_date = versioned_data[versioned_data.length - 1].to_data.start_date
      }
      return dayjs(start_date).valueOf() < dayjs().startOf('date').valueOf();
    })


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

    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 piyue = (lianxi: Lianxi) => {
      router.push(`/teacher/jihua/piyue?jihua_id=${store.current.id}&lianxi_id=${lianxi.id}`)
    }


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

    const modify_course_section = (qs_id: string) => {
      router.push(`/course/section/modify?jihua_id=${store.current.id}&qs_id=${qs_id}`)
    }

    return {
      entity, week, onRemove, piyue, onDelay, refreshing, refresh, show_courses, expired, can_delay, modify_course_section,
      commenting, replyComment, replying, saveComment, removeComment, comments_count, ready, yanqi_week, yanqi_expired
    }
  }
});
</script>

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


    .body {
      height: calc(100% - 1.06rem);
      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;
            }
          }
        }
      }

      .lianxis {
        box-shadow: inset 0 0 3px 8px #f2f3f5;
        padding: 8px;

        .course-right {
          display: inline-flex;
          align-items: center;

          span:first-child {
            margin-right: 5px;
            font-size: 0.2rem;
          }
        }

        .lianxi {
          margin-bottom: 0.32rem;
          border-top: 1px dashed #dddddd;
          padding: 0 0.32rem;

          &.hide {
            display: none;
          }

          .lianxi-line {
            padding: 0.2rem 0;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            &.double {
              display: block;
              .audio-area {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 0.1rem;
              }

              .lianxi-line-label {
                margin-bottom: 0.1rem;
              }
            }

            .text-area {
              background: #e9ecef;
              font-size: 12px;
              width: 100%;
              padding: 0.125rem 0.25rem;
              background-clip: padding-box;
              border-radius: 0.125rem;
            }
          }
        }
      }
    }

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

      .van-badge__wrapper {
        display: inline-flex;
      }

      button {
        width: 1.6rem;
      }
    }

  }
</style>
