<template>
  <div class="main">
    <van-form @submit="update" class="form">
        <van-field v-model="store.current.group_name" label="小组名称" required colon />
        <van-field :model-value="groupTypeName(store.current.group_type)" readonly clickable right-icon="arrow" @click="showPicker=true" label="小组类型" required colon />
        <van-field class="user-field" readonly clickable right-icon="arrow"
                @click="pickUsers" label="小组成员" required colon />
        <div class="user-list">
            <van-tag type="primary" closeable @close="removeUser(user)"  v-for="user in store.current.users.vals">{{user.real_name}}</van-tag>
        </div>
      <van-cell is-link @click="pickTeachers" title="助理老师" v-if="isSupervisor"
                title-class="van-field__label" colon>
        <div v-for="owner in store.current.owners?.vals">
          <van-tag type="primary" size="medium">
            {{ owner.real_name }}
          </van-tag>
        </div>
      </van-cell>
        <van-field v-model="store.current.group_desc" label="小组描述" maxlength="100" colon type="textarea" rows="3"/>
        <div class="foot">
            <van-button block class="btn-submit" type="primary" native-type="submit">保存</van-button>
        </div>
    </van-form>
  </div>
  <van-popup v-model:show="showPicker" position="bottom">
    <van-picker
        :columns="columns"
        @confirm="onPickType"
        @cancel="showPicker = false"
    />
    </van-popup>
</template>

<script lang="ts">
import {defineComponent, ref, computed} from 'vue';
import {Button, Dialog, Field, Form, Image, Loading, Toast, Picker, Popup, Tag, Cell, showFailToast} from 'vant';
import {useRouter} from "vue-router";
import useUserGroup from '~/store/user-group';
import useUser from '~/store/user';
import {GroupTypes, HtyBaseRoles, GroupUser, PickTargets, HtySuperRoles} from '~/types'

export default defineComponent({
  name: "user-group-edit",
  components: {
    [Loading.name]: Loading,
    [Dialog.name]: Dialog,
    [Toast.name]: Toast,
    [Button.name]: Button,
    [Image.name]: Image,
    [Form.name]: Form,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [Tag.name]: Tag,
    [Cell.name]: Cell
  },
  props: ['params'],
  setup({params}) {
    const usingUser = useUser();
    const router = useRouter();
    const {store, update, reset} = useUserGroup(router);
    reset();
    const isSupervisor = computed(() => usingUser.store.current.roles?.some(r => r.role_key === HtySuperRoles.SUPERVISOR))

    if (params.id) {
        let item = store.mine.find(x => x.id === params.id)
        if (item) {
            store.current = item
        } else {
            showFailToast('未找到指定数据！')
            router.push('/user-group')
        }
    }

    const showPicker = ref(false);
    const columns = computed(() => {
        let cols = [
            {text: "学生小组", value: GroupTypes.StudentGroup},
        ];
        if (usingUser.store.currentRole === HtyBaseRoles.TEACHER) {
            cols.push(
                {text: "教师小组", value: GroupTypes.TeacherGroup},
                {text: "师生小组", value: GroupTypes.TeacherWithStudent}
            );
        }
        return cols;
    });

    const onPickType = ({selectedValues}: any) => {
      store.current.group_type = selectedValues[0];
      showPicker.value = false;
      store.current.users = {vals: []};
    }

    const pickUsers = () => {
      store.hanging = true;
      switch(store.current.group_type) {
        case GroupTypes.TeacherGroup:
            router.push('/teacher?multiple=1&target=' + PickTargets.USER_GROUP)
            break;
        case GroupTypes.TeacherWithStudent:
            router.push('/student?multiple=1&target=' + PickTargets.USER_GROUP);
            break;
        case GroupTypes.StudentGroup:
            router.push('/user?picking=1&')
            break;
      } 
    }

    const groupTypeName = (group_type: GroupTypes) => {
        return {
            [GroupTypes.TeacherGroup]: '教师小组',
            [GroupTypes.TeacherWithStudent]: '师生小组',
            [GroupTypes.StudentGroup]: '学生小组',
        }[group_type];
    }


    const removeUser = (user: GroupUser) => {
        store.current.users.vals = store.current.users.vals.filter(x => x.user_id !== user.user_id)
    }

    const pickTeachers = () => {
      store.hanging = true;
      router.push("/teacher/subsidiaries?multiple=1&target=" + PickTargets.USER_GROUP)
    }

    return {
      store, update, pickUsers, columns, showPicker, onPickType, groupTypeName, removeUser, isSupervisor, pickTeachers
    };
  }

});
</script>

<style scoped lang="less">
.main {
    background: #FFFFFF;
    overflow: auto;
    .form {
        .user-field {
            &::after {
                display: none!important;
            }
        }

        .user-list {
            position: relative;
            padding: 0 0.24rem 0.16rem;

            :deep(.van-tag) {
                margin: 0.06rem 0.08rem;
            }
            &::after {
                position: absolute;
                box-sizing: border-box;
                content: " ";
                pointer-events: none;
                right: var(--van-padding-md);
                bottom: 0;
                left: var(--van-padding-md);
                border-bottom: 1px solid var(--van-cell-border-color);
                transform: scaleY(.5);
            }
        }

        .foot {
            padding: 0.32rem;
            text-align: center;

            button {
            width: 90%;
            margin: auto;
            }
        }
    }
}
</style>
