<template>
    <div class="main">
        <van-search v-model.trim="state.keyword" placeholder="请输入小组名称搜索"></van-search>
        <div class="check-list" ref="checkList" v-if="state.multi">
          <van-tag type="primary" @click="onClick(item)" v-for="item in state.checked">{{ item.group_name }}</van-tag>
        </div>
        <van-tabs v-model:active="activeTab" @change="onRefresh">
          <van-tab v-for="tab in tabs" :name="tab.name" :title="tab.label"></van-tab>
        </van-tabs>
        <div class="list" :style="state.multi ? {'height': height}: {}">
            <van-pull-refresh v-model="state.loading" @refresh="onRefresh">
                <van-list v-model:loading="state.loading" :finished="state.finished"
                          finished-text="No more data." v-model:error="state.error"
                          error-text="请求失败，点击重新加载"
                >
                    <template v-for="item in dataset" :key="item.id">
                        <van-cell center :title="item.group_name" @click="() => onClick(item)"
                                  :label="item.users.vals.map(x => x.real_name).join(', ')">
                            <template v-if="state.multi">
                                <van-icon color="#07c160" size="0.5rem" name="checked" v-if="item.checked" />
                                <van-icon color="#07c160" size="0.5rem" name="circle" v-else />
                            </template>
                        </van-cell>
                    </template>
                </van-list>
            </van-pull-refresh>
        </div>
        <van-button v-if="state.multi" class="btn-pick" type="primary" block :disabled="!state.checked.length"
                    @click="onPick">确认
        </van-button>
    </div>
</template>

<script lang="ts">
import {computed, defineComponent, nextTick, onMounted, reactive, ref} from 'vue';
import {Button, Cell, Icon, List, PullRefresh, Search, Dialog, Tag, SwipeCell, Tabs, Tab} from 'vant';
import {useRouter} from "vue-router";
import useUserGroup from '~/store/user-group';
import useUser from '~/store/user';
import useDaka from '~/store/daka';
import useClazz from "~/store/clazz";
import {UserGroup, PickTargets} from '~/types';

export interface GroupState {
    loading: boolean,
    finished: boolean,
    error: boolean,
    keyword: string,
    showDialog: boolean,
    checked: UserGroup[],
    multi: boolean
}

export default defineComponent({
    name: "user-group-pick",
    components: {
        [List.name]: List,
        [Cell.name]: Cell,
        [Search.name]: Search,
        [Button.name]: Button,
        [PullRefresh.name]: PullRefresh,
        [Dialog.name]: Dialog,
        [SwipeCell.name]: SwipeCell,
        [Icon.name]: Icon,
        [Tag.name]: Tag,
        [Tabs.name]: Tabs,
        [Tab.name]: Tab
    },
    props: {params: {} as any},
    setup({params}) {
        const router = useRouter();
        const usingDaka = useDaka();
        const usingClazz = useClazz();
        const {store:{current:{hty_id}}} = useUser();

        const state = reactive<GroupState>({
            loading: false,
            finished: false,
            error: false,
            keyword: '',
            showDialog: false,
            checked: [],
            multi: !!params.multi
        });

        if (params.target === PickTargets.DAKA) {
          state.checked = usingDaka.store.current.groups || []
        }

        const {store, query, reset} = useUserGroup();
        const checkList = ref(null)
        const height = ref("calc(100% - 1.08rem - 1.04rem - 0.16rem - 0.32rem - 0.32rem - var(--van-button-default-height) - 0.16rem)");
        reset();


        const activeTab = ref("mine")

        const tabs = [
            {name: "mine", label: "我的小组"},
            {name: "assigned", label: "共享小组"}
        ]

        const onRefresh = async () => {
            state.finished = false;
            state.error = false;
            state.loading = true;
            state.error = !(await query(activeTab.value));
            state.finished = true;
            state.loading = false;
        };

        const dataset = computed(() => {
            return store[activeTab.value].filter(x => (x.created_by === hty_id || x.owners?.vals?.some(o => o.user_id === hty_id)) && (!state.keyword || x.group_name.includes(state.keyword)))
                .map(x => ({...x, checked: state.checked.some(c => c.id === x.id)}));
        })


        const onClick = (group: UserGroup) => {
            if (state.multi) {
                if (state.checked.some(x => x.id === group.id)) {
                    state.checked = state.checked.filter(x => x.id !== group.id)
                } else {
                    state.checked.push(group);
                }
                nextTick(() => {
                    let el = checkList.value as unknown as HTMLDivElement;
                    height.value = `calc(100% - 1.08rem - 1.04rem - ${el.offsetHeight}px - 0.32rem - 0.32rem - var(--van-button-default-height) - 0.16rem)`;
                })
            } else {
              let { users, created_by, creator_name } = group;
                switch (params.target) {
                  case PickTargets.DAKA:
                    usingDaka.store.current.students = {val: {users}};
                    if (!usingDaka.store.current.teachers?.vals.some(t => t.teacher_id === created_by)) {
                      usingDaka.store.current.teachers?.vals.push({teacher_id: created_by, teacher_name: creator_name})
                    }
                    break;
                  case PickTargets.CLAZZ:
                    usingClazz.store.current.students = {val: {users}}
                }
                router.go(-1);
            }
        }


        const onPick = () => {
            router.go(-1);
        }


        onMounted(() => {
            reset();
            onRefresh()
        });


        return {
            state, dataset, onRefresh, onPick, onClick, height, checkList, activeTab, tabs
        };
    }
});
</script>

<style scoped lang="less">

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

  .check-list {
    padding: 0.08rem 0.16rem;

    :deep(.van-tag) {
      margin: 0 0.08rem;
    }
  }


  :deep(.van-tabs) {
    height: 1.2rem;

    .van-tabs__content {
      display: none;
    }
  }

  .list {
    width: calc(100% - 0.32rem);
    height: calc(100% - 0.54rem - 0.64rem - 1.2rem - 0.32rem - var(--van-button-default-height) - 0.16rem);
    overflow: auto;

    margin: 0 0.16rem 0.32rem;

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

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

}

.input-content {
  padding: 0.25rem;
  text-align: center;

}
</style>
