<template>
  <div class="main">
    <van-search v-model="state.keyword" />
    <div class="checked-line" v-if="state.multiple" ref="checkedLine">
      <van-tag type="primary" v-for="user in state.checked">{{user.teacher_name}}</van-tag>
    </div>
    <div class="list" :style="listStyle">
      <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>
            <van-cell :title="item.teacher_name" v-for="item in dataset" :key="item.teacher_id" @click="onClick(item)">
              <template #right-icon>
                <van-icon v-if="state.checked.some(x => x.teacher_id === item.teacher_id)" size="25" name="checked" color="green" />
                <van-icon v-else size="25" name="circle" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-pull-refresh>
    </div>
      <div class="footer" v-if="state.multiple">
        <van-button @click="$router.back()">返回</van-button>
        <van-button type="primary" @click="onConfirm">确认</van-button>
      </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, onBeforeMount, ref, watch, nextTick } from 'vue';
import { Cell, Search, Toast, Icon, PullRefresh, List, Image, CellGroup, Tag, Button } from 'vant';
import { useRouter } from 'vue-router';
import {PickTargets, UserRel} from '~/types'
import useDaka from "~/store/daka";
import useJihua from "~/store/jihua";
import useSupervisor from "~/store/supervisor";
import useUserGroup from "~/store/user-group";
import useCourseSection from "~/store/qumu-section";
import useCourseGroup from "~/store/qumu-section-group";
import useUser from "~/store/user";
import useClazz from "~/store/clazz";

export default defineComponent({
  name: "teacher-index",
  components: {
    [Search.name]: Search,
    [Icon.name]: Icon,
    [Image.name]: Image,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Toast.name]: Toast,
    [PullRefresh.name]: PullRefresh,
    [List.name]: List,
    [Tag.name]: Tag,
    [Button.name]: Button
  },
  props: ['params'],
  setup({params}) {


    const usingDaka = useDaka();
    const usingJihua = useJihua();
    const usingUserGroup = useUserGroup();
    const usingQS = useCourseSection();
    const usingQSGroup = useCourseGroup()
    const usingClazz = useClazz()
    const {store:{current:{supervisor}}} = useUser()

    const { store, getSubsidiaries } = useSupervisor();

    const state = reactive<any>({
      keyword: '',
      loading: false,
      refreshing: false,
      finished: true,
      checked: [],
      multiple: !!params.multiple
    });



    const checkedLine = ref()



    const router = useRouter();

    const listStyle = ref({});

    const dataset = computed(() => {
      let list = store.subsidiaries.map(x => ({teacher_id: x.to_user_id, teacher_name: x.to_user_realname}));
      if (supervisor && !list.some(x => x.teacher_id === supervisor.teacher_id)) {
        list.push(supervisor)
      }
      if (state.keyword) {
        list = list.filter(x => x.teacher_name.includes(state.keyword))
      }
      return list;
    })


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

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

    watch(() => state.checked.length, () => {
      let el = checkedLine.value as unknown as HTMLDivElement;
      if (!el) {
        listStyle.value = {}
      }
      nextTick(() => {
        listStyle.value = {height: `calc(100% - 1.08rem - 1.4rem - ${el.clientHeight}px)`};
      })
    })



    onBeforeMount(async () => {

      await search();

      switch (params.target) {
        case PickTargets.JIHUA:
          state.checked = [...(usingJihua.store.current.teachers?.vals || [])].filter(t => dataset.value.some(x => x.teacher_id === t.teacher_id))
          break;
        case PickTargets.DAKA:
          state.checked = [...(usingDaka.store.current.teachers?.vals || [])].filter(t => dataset.value.some(x => x.teacher_id === t.teacher_id))
          break;
        case PickTargets.USER_GROUP:
          state.checked = [...(usingUserGroup.store.current.owners?.vals || [])].filter(o => dataset.value.some(x => x.teacher_id === o.user_id)).map(x => ({teacher_id: x.user_id, teacher_name: x.real_name}))
          break;
        case PickTargets.COURSE_SECTION:
          state.checked = [...(usingQS.store.current.teachers?.vals || [])].filter(t => dataset.value.some(x => x.teacher_id === t.teacher_id))
          break;
        case PickTargets.COURSE_GROUP:
          state.checked = [...(usingQSGroup.store.current.teachers?.vals || [])].filter(t => dataset.value.some(x => x.teacher_id === t.teacher_id))
          break;
        case PickTargets.CLAZZ:
          state.checked = [...(usingClazz.store.current.teachers?.val?.users?.vals || [])].filter(t => dataset.value.some(x => x.teacher_id === t.user_id))
          break;
      }
    })

    const onClick = ({teacher_id, teacher_name}: UserRel) => {
      if (state.multiple) {
        if (state.checked.some(x => x.teacher_id === teacher_id)) {
          state.checked = state.checked.filter(x => x.teacher_id !== teacher_id);
        } else {
          state.checked.push({teacher_id, teacher_name});
        }
      }
    };

    const onConfirm = () => {
      let teachers = [...state.checked];
      switch (params.target) {
        case PickTargets.DAKA:
          usingDaka.store.current.teachers = {vals: teachers}
          break;
        case PickTargets.JIHUA:
          usingJihua.store.current.teachers = {vals: teachers}
          break;
        case PickTargets.USER_GROUP:
          usingUserGroup.store.current.owners = {vals: teachers.map(t => ({user_id: t.teacher_id, real_name: t.teacher_name}))}
          break;
        case PickTargets.COURSE_SECTION:
          usingQS.store.current.teachers = {vals: teachers}
          break;
        case PickTargets.COURSE_GROUP:
          usingQSGroup.store.current.teachers = {vals: teachers}
          break;
        case PickTargets.CLAZZ:
          usingClazz.store.current.teachers = {val: {users: {vals: teachers.map(t => ({user_id: t.teacher_id, real_name: t.teacher_name}))}}}
          break;
      }
      router.back();
    }

    return {
      state, dataset, onClick, onRefresh, onConfirm, checkedLine, listStyle
    };
  }
});
</script>

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

    .checked-line {
      padding: 0.08rem 0.28rem;

      &:empty {
        padding: 0;
      }

      :deep(.van-tag) {
          margin: 0.04rem 0.06rem;
      }
    }

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

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

      .avatar {
        width: 0.5rem;
        height: 0.5rem;
        margin-right: 0.1rem;
      }

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

    .footer {
      width: 100%;
      position: absolute;
      bottom: 0.4rem;
      padding: 0.32rem;
      height: 1rem;
      display: flex;
      justify-content: space-between;

      :deep(.van-button) {
        width: 45%;
      }
    }
  }
</style>
