<template>
  <div class="main">
    <van-tabs v-model:active="activeTab">
      <van-tab v-for="tab in tabs" :name="tab.name">
        <template #title>
          <span class="tab-title">
            {{tab.label}}
            <van-tag :color="tab_tag_color(tab.name)">
            {{dataset(tab.name).length}}
            </van-tag>
          </span>
        </template>
        <van-search v-if="tab.name === 'Approved'" v-model="state.keyword" />
        <div class="list">
          <van-pull-refresh v-model="state.refreshing" @refresh="onRefresh">
            <van-list v-model:loading="state.loading"
                      :finished="state.finished" finished-text="没有更多数据了"
                      @load="onRefresh">
              <van-cell-group inset>
                <template v-for="item in dataset(tab.name)" :key="item.hty_id">
                  <van-swipe-cell>
                    <van-cell is-link :to="`/teacher/detail?id=${item.hty_id}`">
                      <template #title>
                        {{item.real_name + (item.meta?.nickName ? ' (' + item.meta.nickName + ')' : '')}}
                        <van-tag v-if="!item.enabled" color="#646566" >未启用</van-tag>
                      </template>
                      <template #icon >
                        <hty-image :type="'avatar'" :url="item.avatar_url || item.meta?.avatarUrl" />
                      </template>
                    </van-cell>
                    <template #right>
                      <van-button v-if="tab.name === 'Waiting'" :disabled="!item.enabled" square type="primary" @click="approveTeacher(item.hty_id)" text="通过"></van-button>
                      <van-button v-if="tab.name === 'Waiting'" :disabled="!item.enabled" square type="danger" @click="reject(item.hty_id)" text="驳回"></van-button>
                    </template>
                  </van-swipe-cell>  
                </template>
              </van-cell-group>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
    </van-tabs>
  </div>
  <van-dialog v-model:show="state.rejecting" title="请输入驳回原因" show-cancel-button @confirm="confirm" @cancel="cancel">
    <div class="text-area">
      <van-field v-model="state.reason" rows="2" type="textarea" maxlength="200" show-word-limit/>
    </div>
  </van-dialog>

</template>

<script lang="ts">
import { defineComponent, reactive, onMounted, ref } from 'vue';
import { Cell, Search, List, Toast, Icon, Image, Tag, CellGroup, SwipeCell, PullRefresh, Button, Tab, Tabs, Dialog, Field, showFailToast } from 'vant';
import { useRouter } from 'vue-router';
import useUser from "~/store/user";
import { TeacherStudentStates, User } from '~/types'
import HtyImage from "~/components/hty-image.vue";

export default defineComponent({
  name: "admin-teachers",
  components: {
    [Search.name]: Search,
    [Cell.name]: Cell,
    [Toast.name]: Toast,
    [Icon.name]: Icon,
    [CellGroup.name]: CellGroup,
    [Image.name]: Image,
    [SwipeCell.name]: SwipeCell,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [PullRefresh.name]: PullRefresh,
    [Dialog.name]: Dialog,
    [Button.name]: Button,
    [Tag.name]: Tag,
    [Field.name]: Field,
    [List.name]: List,
    [HtyImage.name]: HtyImage
  },
  setup() {
    const state = reactive({
      keyword: '',
      loading: false,
      refreshing: false,
      finished: true,
      reason: '',
      rejecting: false,
      rejecting_id: ''
    });

    const activeTab = ref('Approved');

    const tabs = [
      {name: 'Approved', label: '已认证'},
      {name: 'Waiting', label: "待审核"},
      {name: 'Rejected', label: "已驳回"},
    ];

    const { store, getAllTeachers, approveTeacher, rejectTeacher } = useUser();

    const router = useRouter();

    const dataset = (tab: string) => {
      let list = store.teachers.all;
      if (tab === 'Approved') {
        list = list.filter(x => x.is_registered);
      } else if (tab === 'Waiting') {
        list = list.filter(x => !x.is_registered && !x.reject_reason);
      } else {
        list = list.filter(x => !x.is_registered && !!x.reject_reason);
      }
      
      if (state.keyword) {
        list = list.filter(x => x.real_name.includes(state.keyword))
      }
      return list;
    }

    const tab_tag_color = (tab: string) => {
      return {
        Approved: '#07c160',
        Waiting: '#ee0a24',
        Rejected: '#969799',
        [TeacherStudentStates.Removed]: '#646566',
      }[tab];
    }


    const search = async () => {
      state.loading = true;
      await getAllTeachers();
      state.finished = true;
      state.loading = false;
    }

    const onRefresh = () => {
      state.refreshing = false;
      search();
    }

    const reject = (teacher_id: string) => {
      state.rejecting = true;
      state.rejecting_id = teacher_id;
    }

    const confirm = async () => {
      let { rejecting_id, reason } = state;
      if (!reason) {
        showFailToast('请输入驳回原因！')
        return false;
      }
      console.log(rejecting_id, reason);
      await rejectTeacher(rejecting_id, reason);
    }

    const cancel = () => {
      state.rejecting = false;
      state.rejecting_id = ''
    }


    onMounted(async () => {
      if (store.teachers.all.length > 0) {
        return;
      }
      onRefresh();
    })

    const onSelect = (student: User) => {
      router.push('/teacher/detail?id=' + student.hty_id);
    };

    return {
      state, dataset, onSelect, onRefresh, reject, confirm, cancel,
      approveTeacher, tabs, activeTab, tab_tag_color
    };
  }
});
</script>

<style scoped lang="less">
  .main {
    width: 100%;
    height: calc(100% - 1rem);


    .tab-title {
      display: inline-flex;
      align-items: center;

      :deep(.van-tag) {
        margin-left: 3px;
      }
    }

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

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

        .van-tab__panel {
          height: 100%;

          .van-pull-refresh {
            height: 100%;
          }
        }
      }
    }

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

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

      :deep(.van-cell) {
        align-items: center;
      }
    }

    .btn-add {
      position: absolute;
      right: 0.3rem;
      bottom: 1rem;
      font-size: 0.9rem;
    }
  }

.text-area {
  font-size: 12px;
  width: 90%;
  margin: 0.2rem auto;
  background-clip: padding-box;
  border: 1px solid #dddddd;
}
</style>
