<script setup lang="ts">
import type { CheckboxInstance } from 'vant';
import type { RoleModel } from '@/request/model/manage.model';

import { useRequest } from 'alova/client';
import { getRoles } from '@/request/api/manage';

const emits = defineEmits<{ complete: [RoleModel[]] }>();

const show = defineModel('show', { default: false });
const selected = defineModel<string>('selected');

const { data: roles, loading } = useRequest(getRoles);

const form = ref({ roleIds: [] });
const submit = () => {
  const roleIds = form.value.roleIds;
  selected.value = roleIds.join(',');
  const rawRoles = [];
  for (const id of roleIds) {
    const role = roles.value.find((role) => role.id === id);
    if (role) rawRoles.push(role.__raw__);
  }
  emits('complete', rawRoles);
  show.value = false;
}

watchEffect(() => {
  form.value.roleIds = selected.value? selected.value.split(','): [];
});

const checkboxRefs = useTemplateRef<CheckboxInstance[]>('checkbox');
const toggle = (index) => {
  checkboxRefs.value[index].toggle();
};
</script>

<template>
  <van-popup v-model:show="show" position="top">
    <van-form class="form-wrapper" @submit="submit(form)" label-align="top">
      <van-checkbox-group v-model="form.roleIds" direction="horizontal" shape="square">
        <van-field name="user_roles">
          <template #label>选择角色<van-loading v-if="loading" class="ml-2" size="18" /> </template>
          <template #input>
            <van-checkbox-group v-model="form.roleIds" direction="horizontal" shape="square">
              <van-cell-group inset>
                <van-cell v-for="(item, index) in roles" clickable :key="item.id" @click="toggle(index)">
                  <template #title>
                    <div class="flex">
                      <van-checkbox :name="item.id" ref="checkbox" @click.stop />
                      {{ item.name }}
                    </div>
                  </template>
                </van-cell>
              </van-cell-group>
            </van-checkbox-group>
          </template>
        </van-field>
      </van-checkbox-group>
      <div class="flex gap-4" style="padding: 16px">
        <van-button round block native-type="submit">取消</van-button>
        <van-button round block type="primary" native-type="submit">确认</van-button>
      </div>
    </van-form>
  </van-popup>
</template>

<style scoped lang="scss">
.form-wrapper {
  :deep(.van-field__control) {
    .van-checkbox-group,
    .van-checkbox-group .van-cell-group {
      --van-cell-group-inset-padding: 0;
      flex: auto;
    }
    .van-checkbox-group {
      max-height: 40vh;
      overflow-y: auto;
    }
  }
}
</style>
