<template>
  <div class="main">
    <van-tabs v-model:active="state.activeTab" @change="onRefresh">
        <van-tab :title="'未读通知(' + count(0) + ')'">
          <div v-if="count(0) > 0" class="toolbar">
            <van-button block @click="clearUnread()" plain type="primary" size="mini" >全部标为已读</van-button>
          </div>
          <div class="list">
            <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"
              >
                <template v-for="item in dataset(0)" :key="item.tongzhi_id">
                  <van-cell-group inset>
                    <van-swipe-cell>
                      <div class="row van-cell" @click="() => onClick(item)" >
                        <div v-if="item.content?.content">{{item.content.content}}</div>
                        <div v-if="item.push_info?.clazz_id">{{getTongzhiTitle(item.tongzhi_type)}}<small>({{formatDateTime(item.content.created_at)}})</small></div>
                        <div class="van-hairline--bottom"></div>
                        <template v-if="item.push_info?.clazz_id">
                          <div class="line">
                            <span>排课名称</span>
                            <span>{{item.push_info.clazz_name}}</span>
                          </div>
                          <div class="line">
                            <span>上课时间</span>
                            <span>{{item.push_info.start_from.replace("T", " ")}} ~ {{item.push_info.end_by.split("T")[1] || item.push_info.end_by}}</span>
                          </div>
                          <div class="line">
                            <span>上课老师</span>
                            <span>{{item.push_info.teacher_name}}</span>
                          </div>
                          <div class="line">
                            <span>上课学生</span>
                            <span>{{item.push_info.student_name}}</span>
                          </div>
                        </template>

                        <div class="line" v-if="item.content?.daka_id">
                          <span>打卡周期：</span>
                          <span>{{get_daka_period(item.content)}}</span>
                        </div>
                        <div class="line" v-if="item.push_info?.course_name">
                          <span>课程体系：</span>
                          <span>{{item.push_info?.course_name}}({{item.push_info?.course_section_name}})</span>
                        </div>
                      </div>
                      <template #right>
                        <van-button square text="已读" type="primary" class="swipe-button" @click="setRead(item.tongzhi_id)" />
                      </template>
                    </van-swipe-cell>
                  </van-cell-group>
                </template>
              </van-list>
            </van-pull-refresh>
          </div>
        </van-tab>
        <van-tab :title="'已读通知(' + count(1) + ')'">
          <div v-if="count(1) > 0" class="toolbar">
            <van-button block @click="removeAllRead()" plain type="danger" size="mini" >清除全部已读</van-button>
          </div>
          <div class="list">  
            <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"
              >
                <template v-for="item in dataset(1)" :key="item.tongzhi_id">
                  <van-cell-group inset>
                    <van-swipe-cell>
                      <div class="row van-cell read" @click="() => onClick(item)" >
                        <div v-if="item.content?.content">{{item.content.content}}</div>
                        <div v-if="item.push_info?.clazz_id">{{getTongzhiTitle(item.tongzhi_type)}}<small>({{formatDateTime(item.content.created_at)}})</small></div>
                        <div class="van-hairline--bottom"></div>
                        <template v-if="item.push_info?.clazz_id">
                          <div class="line">
                            <span>排课名称</span>
                            <span>{{item.push_info.clazz_name}}</span>
                          </div>
                          <div class="line">
                            <span>上课时间</span>
                            <span>{{formatDateTime(item.push_info.start_from)}} ~ {{formatDateTime(item.push_info.end_by).split(" ")[1]}}</span>
                          </div>
                          <div class="line">
                            <span>上课老师</span>
                            <span>{{item.push_info.teacher_name}}</span>
                          </div>
                          <div class="line">
                            <span>上课学生</span>
                            <span>{{item.push_info.student_name}}</span>
                          </div>
                        </template>
                        <div class="line" v-if="item.content.daka_id">
                          <span>打卡周期：</span>
                          <span>{{get_daka_period(item.content)}}</span>
                        </div>
                        <div class="line" v-if="item.push_info?.course_name">
                          <span>课程体系：</span>
                          <span>{{item.push_info?.course_name}}({{item.push_info?.course_section_name}})</span>
                        </div>
                      </div>
                      <template #right>
                        <van-button square text="清除" type="danger" class="swipe-button" @click="remove(item.tongzhi_id, item.tongzhi_status)" />
                      </template>
                    </van-swipe-cell>
                  </van-cell-group>
                </template>
              </van-list>
            </van-pull-refresh>
          </div>
        </van-tab>
      </van-tabs>
    
  </div>
</template>

<script lang="ts">
import {defineComponent, onMounted, reactive} from 'vue';
import {Button, Cell, CellGroup, Icon, List, PullRefresh, Search, showConfirmDialog, SwipeCell, Tab, Tabs} from 'vant';
import {useRouter} from "vue-router";
import useTongzhi from "~/store/tongzhi";
import {NotifyTypes, PagedQueryParam, Tongzhi, TongzhiContent, TongzhiStatuses} from '~/types';
import {DateFormatter, formatDate} from '~/utils'

export interface TongzhiState {
  loading: boolean,
  finished: boolean,
  error: boolean,
  refreshing: boolean,
  activeTab: number,
  page_size: number,
  page: {
    [TongzhiStatuses.Unread]: number,
    [TongzhiStatuses.Read]: number
  }
}

export default defineComponent({
  name: "tongzhi",
  components: {
    [List.name]: List,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Search.name]: Search,
    [Button.name]: Button,
    [PullRefresh.name]: PullRefresh,
    [Icon.name]: Icon,
    [SwipeCell.name]: SwipeCell,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab
  },
  setup() {
    
    const state = reactive<TongzhiState>({
      loading: false,
      finished: false,
      error: false,
      refreshing: false,
      activeTab: 0,
      page_size: 20,
      page: {
        [TongzhiStatuses.Unread]: 1,
        [TongzhiStatuses.Read]: 1
      }
    });
    const statuses = [TongzhiStatuses.Unread, TongzhiStatuses.Read];
    const router = useRouter();

    const { store, query, setRead, setReadAll, remove, removeAll } = useTongzhi();

    const search = async (params: PagedQueryParam) => {
      let status = statuses[state.activeTab]
      state.finished = false;
      state.error = false;
      state.loading = true;
      state.error = !(await query(params, status))
      state.page[status] = params.page;
      if (store[status].pages <= state.page[status]) {
        state.finished = true;
      }
      state.loading = false;
    }


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

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

    const dataset = (tab: number) => {
      return store[statuses[tab]].list;
    }

    const count = (tab: number) => {
      return store[statuses[tab]].total;
    }

    const getIds = ({content, push_info}: Tongzhi) => {
      let { ref_id, serial, comment_id } = push_info || {};
      let { jihua_id, lianxi_id, daka_id, clazz_id } = content;
      if  (!(jihua_id || lianxi_id || daka_id)) {
        if (push_info) {
          jihua_id = push_info.jihua_id;
          lianxi_id = push_info.lianxi_id;
          daka_id = push_info.daka_id;
          clazz_id = push_info.clazz_id;
        }
      }
      return {
        jihua_id, lianxi_id, daka_id, ref_id, serial, comment_id, clazz_id
      }
    }

    const onClick = async (tongzhi: Tongzhi) => {

      if (tongzhi.tongzhi_status == TongzhiStatuses.Unread) {
        await setRead(tongzhi.tongzhi_id);
      }

      let { jihua_id, lianxi_id, daka_id, ref_id, serial, comment_id, clazz_id } = getIds(tongzhi);

      let comment_param = comment_id ? "&comment_id=" + comment_id : "";
      let serial_param = serial ? '&serial=' + serial: '';
      let ref_param = ref_id ? "&ref_id=" + ref_id : "";
      switch(tongzhi.tongzhi_type) {
        case NotifyTypes.JihuaCreate:
        case NotifyTypes.JihuaUpdate:
        case NotifyTypes.TeacherCommentJihua:
          await router.push("/daka");
          break;
        case NotifyTypes.DakaCreate:
        case NotifyTypes.DakaUpdate:
        case NotifyTypes.TeacherCommentDaka:
        case NotifyTypes.StudentCommentDaka:
          router.push("/daka/detail?id=" + daka_id + "&from_tongzhi=1" + comment_param);
          break;
        case NotifyTypes.DakaDelete:
          router.push("/daka");
          break;
        case NotifyTypes.TeacherCommentPiyue:
          if (daka_id) {
            router.push(`/daka/piyue?daka_id=${daka_id}&lianxi_id=${lianxi_id}${serial_param}${comment_param}&from_tongzhi=1`);
          } else {
            router.push("/daka");
          }
          break;
        case NotifyTypes.JihuaDelete:
          router.push("/daka");
          break;
        case NotifyTypes.LianxiCreate:
          if (daka_id) {
            router.push(`/daka/piyue?daka_id=${daka_id}&lianxi_id=${lianxi_id}&from_tongzhi=1`);
          } else {
            router.push("/daka");
          }
          break;
        case NotifyTypes.LianxiDelete:
          if (daka_id) {
            router.push(`/daka/detail?id=${daka_id}`);
          } else {
            router.push("/daka");
          }
          break;
        case NotifyTypes.StudentCommentJihua:
          router.push("/daka");
          break;
        case NotifyTypes.PiyueCreate:
          if (daka_id) {
            router.push(`/daka/piyue?daka_id=${daka_id}&lianxi_id=${lianxi_id}&from_tongzhi=1`);
          } else {
            router.push("/daka");
          }
          break;
        case NotifyTypes.StudentCommentPiyue:
          if (daka_id) {
            router.push(`/daka/piyue?daka_id=${daka_id}&lianxi_id=${lianxi_id}${serial_param}${comment_param}&from_tongzhi=1`);
          } else {
            router.push("/daka");
          }
          break;
        case NotifyTypes.ResourceNoteGroupCreate:
          if (daka_id) {
            router.push(`/daka/piyue?daka_id=${daka_id}&lianxi_id=${lianxi_id}${ref_param}&from_tongzhi=1`);
          } else {
            router.push("/daka");
          }
          break;
        case NotifyTypes.StudentRegister:
          router.push('/teacher/students');
          break;
        case NotifyTypes.StudentRegisterApproved:
          router.back();
          break;
        case NotifyTypes.TeacherRegister:
          router.push("/admin/teachers");
          break;
        case NotifyTypes.TeacherRegisterApproved:
          router.back();
          break;
        case NotifyTypes.ClazzCreateOrUpdate:
        case NotifyTypes.TeacherCommentClazz:
          let { push_info: {start_from, comment_id} } = tongzhi;
          let url = "/clazz?clazz_id=" + clazz_id + "&start_from=" + start_from;
          if (comment_id) {
            url += "&comment_id=" + comment_id
          }
          router.push(url)
          break;
        case NotifyTypes.ClazzDelete:
          router.push("/clazz")
          break;
      }
    }


    onMounted(() => {
      onRefresh();
      query({page: 1, page_size: 20}, TongzhiStatuses.Read);
    });

    const formatDateTime = (dt: Date | string) => formatDate(dt, DateFormatter.DateTime)

    const removeAllRead = () => {
      showConfirmDialog({
        title: "确认清除全部已读消息？"
      }).then(() => {
        removeAll(TongzhiStatuses.Read)
      })
    }

    const clearUnread = () => {
      showConfirmDialog({
        title: "确认将全部未读消息标为已读？"
      }).then(() => {
        setReadAll()
      })
    }

    const getTongzhiTitle = (tongzhi_type) => {
      return {
        [NotifyTypes.ClazzCreateOrUpdate]: "上课时间确定通知",
        [NotifyTypes.ClazzDelete]: "排课预约取消通知",
        [NotifyTypes.TeacherCommentClazz]: "排课留言通知"
      }[tongzhi_type]
    }

    const get_daka_period = ({daka_start_date, daka_duration_days}: TongzhiContent) => {
      let end = new Date(daka_start_date);
      end.setDate(end.getDate() + daka_duration_days);
      return formatDate(daka_start_date) + " ~ " + formatDate(end)
    }


    return {
      state, dataset, onRefresh, onClick, onPage, formatDate, formatDateTime, count, setRead, clearUnread, remove, removeAllRead, get_daka_period, getTongzhiTitle
    };
  }
});
</script>

<style scoped lang="less">

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

    :deep(.van-tabs) {
      height: 100%;

      .van-tabs__content {
        height: calc(100% - var(--van-tabs-line-height));

        .van-tab__panel {
          height: 100%;
        }
      }
    }

  .toolbar {
    height: 0.48rem;
    padding-top: 0.04rem;
    :deep(.van-button)  {
      border: none!important;
    }

    + .list {
      height: calc(100% - 0.64rem - 0.52rem);
    }
  }

  .list {
    width: 100%;
    height: calc(100% - 0.64rem);
    overflow-y: auto;
    margin: 0.32rem 0;

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

    :deep(.van-cell-group) {
      margin-bottom: 0.2rem;
    }

    .swipe-button {
      height: 100%;
    }

    .row {
      
      flex-direction: column;
      background: #ddd;
      &.read {
        background: #fff;
      }

      .van-hairline--bottom {
        margin: 0.1rem 0;
      }

      .line {
        color: #9e9e9e;
        display: flex;
        justify-content: space-between;
        font-size: 0.24rem;
      }
    }

    
  }

  small {
    color: #9e9e9e;
  }

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

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

}
</style>
