<script setup lang="ts">
import type { CheckboxInstance, FormInstance } from 'vant';
import type { MenuLeafFlat, RoleModel } from '@/request/model/manage.model';
import { useForm } from 'alova/client';
import { flattenMenuLeaves } from '@/request/model/manage.model';

import { useRequest } from 'alova/client';
import { editRole, getMenus } from '@/request/api/manage';

const props = defineProps<Partial<RoleModel>>();
const emits = defineEmits<{
  complete: [model: RoleModel];
  cancel: [];
}>();

const menus = shallowRef<MenuLeafFlat[]>([]);
const { loading } = useRequest(getMenus).onSuccess(({ data }) => {
  menus.value = flattenMenuLeaves(data);
});
const {
  form,
  loading: submitting,
  send: submit,
} = useForm(
  (model) => {
    const selected = new Set<string>();
    for (const id of model.menuIds) {
      const menu = menus.value.find((menu) => menu.id === id);
      menu?.parents?.forEach((menu) => selected.add(menu.id));
      if (menu) selected.add(menu.id);
    }
    return editRole({ ...model, menuIds: [...selected] });
  },
  { immediate: false, initialForm: { pid: '', rolename: '', menuIds: [] as string[], stateSel: '0' } }
).onSuccess(({ data }) => emits('complete', data));

watchEffect(() => {
  form.value.pid = props.id ?? '';
  form.value.rolename = props.name ?? '';
  form.value.menuIds = props.menus ?? [];
});

const formRef = useTemplateRef<FormInstance>('form');
const checkboxRefs = useTemplateRef<CheckboxInstance[]>('checkbox');
const toggle = (index: number) => {
  if (submitting.value) return;
  checkboxRefs.value?.[index].toggle();
  formRef.value?.validate('role_menus');
};
</script>

<template>
  <van-form class="form-wrapper" @submit="submit(form)" label-align="top" required :readonly="submitting">
    <van-cell-group inset>
      <van-field name="role_name" label="角色名" placeholder="请输入角色名称" v-model="form.rolename" :rules="[{ required: true, message: '请输入角色名称' }]" />
      <van-field name="role_menus" :rules="[{ required: true, message: '请选择菜单权限' }]">
        <template #label>菜单权限<van-loading v-if="loading" class="ml-2" size="18" /> </template>
        <template #input>
          <van-checkbox-group v-model="form.menuIds" direction="horizontal" shape="square">
            <van-cell-group inset>
              <van-cell v-for="(item, index) in menus" clickable :key="item.id" @click="toggle(index)">
                <template #title>
                  <div class="flex">
                    <van-checkbox :name="item.id" ref="checkbox" :disabled="submitting" @click.stop />
                    {{ item.label }}
                  </div>
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </template>
      </van-field>
    </van-cell-group>
    <div style="padding: 16px">
      <van-button round block type="primary" native-type="submit" :loading="submitting">提交</van-button>
    </div>
  </van-form>
</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>
