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

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

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

const { data: roles, loading } = useRequest(getRoles);
const {
  form,
  loading: submitting,
  send: submit,
} = useForm(
  (model) => {
    const rawRoles = [];
    for (const id of model.roleIds) {
      const role = roles.value.find((role) => role.id === id);
      if (role) rawRoles.push(role.__raw__);
    }
    return editUser({ ...model, roles: rawRoles, roleIds: model.roleIds.join(',') });
  },
  { immediate: false, initialForm: { pid: '', userid: '', username: '', roleIds: [] as string[], stateSel: '0' } }
).onSuccess(({ data }) => emits('complete', data));

watchEffect(() => {
  form.value.pid = props.id ?? '';
  form.value.userid = props.account ?? '';
  form.value.username = props.name ?? '';
  form.value.roleIds = props.roles?.map((item) => item.id) ?? [];
});

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="user_id" label="账号" placeholder="请输入登录账号" v-model="form.userid" :rules="[{ required: true, message: '请输入登录账号' }]" />
      <van-field name="user_name" label="姓名" placeholder="请输入真实姓名" v-model="form.username" :rules="[{ required: true, message: '请输入真实姓名' }]" />
      <van-field name="user_roles" :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.roleIds" direction="horizontal" shape="square">
            <van-cell-group inset>
              <van-cell v-for="(item, index) in roles" clickable :key="item.id" :title="`复选框 ${item}`" @click="toggle(index)">
                <template #title>
                  <div class="flex">
                    <van-checkbox :name="item.id" ref="checkbox" :disabled="submitting" @click.stop />
                    {{ item.name }}
                  </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>
