<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { SysDeptApi } from '#/api/auth/dept';
import type { SysRoleApi } from '#/api/auth/role';
import type { SysUserApi } from '#/api/auth/user';

import { computed, h, onMounted, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { addFullName, getVxePopupContainer } from '@vben/utils';

import { Tag } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { treeList } from '#/api/auth/dept';
import { postOptionSelect } from '#/api/auth/post';
import { getAllRole } from '#/api/auth/role';
import { apiAdd, apiUpdate, getUserDetail } from '#/api/auth/user';
import { configInfoByKey } from '#/api/system/sysConfig';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { authScopeOptions } from '#/views/auth/role/data';

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<SysUserApi.User>({});
const isUpdate = ref(false);
function genDeptTree(deptList: SysDeptApi.Dept[]): SysDeptApi.Dept[] {
  const top: SysDeptApi.Dept = {
    children: [],
    id: 0,
    name: '顶级部门',
    parentId: -1,
    nodePath: '/',
    orderNum: 0,
    status: 1,
  };
  deptList.forEach((item) => {
    if (item.parentId === 0) {
      top.children?.push(item);
    }
  });
  return [top];
}

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'name',
    label: '姓名',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'username',
    label: '登录用户名',
    rules: 'required',
  },
  {
    component: 'InputPassword',
    fieldName: 'password',
    label: '登录密码',
    rules: 'required',
  },
  {
    component: 'ApiTreeSelect',
    componentProps: (formModel) => ({
      api: async () => {
        const deptArray = await treeList();
        const deptTree = genDeptTree(deptArray);
        addFullName(deptTree, 'name', ' / ');
        return deptTree;
      },
      async onSelect(deptId: number) {
        /** 根据部门ID加载岗位 */
        await setupPostOptions(deptId);
        /** 变化后需要重新选择岗位 */
        formModel.postIds = [];
      },
      class: 'w-full',
      treeLine: { showLeafIcon: false },
      treeIcon: false,
      // 筛选的字段
      treeNodeFilterProp: 'label',
      // 选中后显示在输入框的值
      treeNodeLabelProp: 'fullName',
      getVxePopupContainer,
      labelField: 'name',
      showSearch: true,
      treeDefaultExpandAll: true,
      valueField: 'id',
      childrenField: 'children',
    }),
    fieldName: 'deptId',
    label: '部门',
  },
  {
    component: 'Input',
    fieldName: 'phone',
    label: '电话',
    // rules: 'required',
  },
  // {
  //   component: 'Input',
  //   fieldName: 'email',
  //   label: '邮箱',
  //   rules: 'required',
  // },
  // {
  //   component: 'Input',
  //   fieldName: 'isAdmin',
  //   label: '是否为默认管理员,超级管理员',
  //   rules: 'required',
  // },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_COMMON_STATUS, true),
    },
    defaultValue: 1,
    formItemClass: 'col-span-2 md:col-span-2',
    fieldName: 'isEnable',
    label: '状态',
    rules: 'required',
  },
  {
    component: 'Select',
    componentProps: {
      getVxePopupContainer,
      mode: 'multiple',
      optionFilterProp: 'label',
      optionLabelProp: 'label',
      placeholder: '请先选择部门',
    },
    fieldName: 'postIds',
    help: '选择部门后, 将自动加载该部门下所有的岗位',
    label: '岗位',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      api: getAllRole,
      // 接口转options格式
      afterFetch: (data: SysRoleApi.Role[]) => {
        return data.map((item) => ({
          label: genRoleOptionlabel(item),
          // title用于选中后回填到输入框 默认为label
          title: item.name,
          value: item.id,
        }));
      },
      getVxePopupContainer,
      mode: 'multiple',
      optionFilterProp: 'title',
      optionLabelProp: 'title',
    },
    fieldName: 'roleIds',
    label: '角色',
  },
  {
    component: 'Textarea',
    fieldName: 'remark',
    formItemClass: 'items-start',
    label: '备注',
    // rules: 'required',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 90,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      // 需要重置岗位选择
      formApi.updateSchema([
        {
          componentProps: { options: [], placeholder: '请先选择部门' },
          fieldName: 'postIds',
        },
      ]);
      return null;
    }
    drawerApi.drawerLoading(true);
    const { id } = drawerApi.getData() as { id?: number };
    isUpdate.value = !!id;
    if (id) {
      const data = await getUserDetail(id);
      formData.value = data;
      formApi.setValues(formData.value);
      // 更新时不会触发onSelect 需要手动调用
      await setupPostOptions(data.deptId);
    } else {
      formApi.resetForm();
      await loadDefaultPassword(isUpdate.value);
    }
    /** update时 禁用用户名修改 不显示密码框 */
    formApi.updateSchema([
      { componentProps: { disabled: isUpdate.value }, fieldName: 'name' },
      {
        dependencies: { if: () => !isUpdate.value, triggerFields: ['id'] },
        fieldName: 'password',
      },
    ]);
    await markInitialized();
    drawerApi.drawerLoading(false);
  },
});

const defaultPassword = ref('');
onMounted(async () => {
  const password = await configInfoByKey('sys.user.initPassword');
  if (password) {
    defaultPassword.value = password;
  }
});

/**
 * 新增时候 从参数设置获取默认密码
 */
async function loadDefaultPassword(update: boolean) {
  if (!update && defaultPassword.value) {
    formApi.setFieldValue('password', defaultPassword.value);
  }
}

/**
 * 生成角色的自定义label
 * 也可以用option插槽来做
 * renderComponentContent: () => ({
    option: ({value, label, [disabled, key, title]}) => '',
  }),
 */
function genRoleOptionlabel(role: SysRoleApi.Role) {
  const found = authScopeOptions.find((item) => item.value === role.dataScope);
  if (!found) {
    return role.name;
  }
  return h('div', { class: 'flex items-center gap-[6px]' }, [
    h('span', null, role.name),
    h(Tag, { color: found.color }, () => found.label),
  ]);
}

/**
 * 岗位的加载
 */
async function setupPostOptions(deptId: number) {
  const postListResp = await postOptionSelect(deptId);
  const options = postListResp.map((item) => ({
    label: item.postName,
    value: item.id,
  }));
  const placeholder = options.length > 0 ? '请选择' : '该部门下暂无岗位';
  formApi.updateSchema([
    {
      componentProps: { options, placeholder },
      fieldName: 'postIds',
    },
  ]);
}

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<SysUserApi.User>();
    try {
      await (formData.value?.id
        ? apiUpdate({ id: formData.value.id, ...data })
        : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const getDrawerTitle = computed(() =>
  formData.value?.id ? '修改系统用户' : '新增系统用户',
);
</script>
<template>
  <Drawer class="w-[600px]" :title="getDrawerTitle">
    <BasicForm class="mx-4" />
  </Drawer>
</template>
