<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :confirmDisabled="getConfirmDisabled"
    :title="getTitle"
    width="600px"
    @ok="handleSubmit"
  >
    <a-spin :spinning="isLoading">
      <BasicForm @register="registerForm" />
    </a-spin>
  </BasicDrawer>
</template>
<script lang="ts" setup name="UserDrawer">
  import { defineEmits, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, StatusValEnum, PASSWORD } from './schema';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import * as UserApi from '/@/api/system/userApi';
  import { useAsyncState } from '@vueuse/core';
  import { User } from '/@/api/model/user';
  import { getDistributorText } from '/@/commonSchemaProperty';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const entityId = ref(0);

  const useFormProps: any = ref({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm(useFormProps.value);

  /**
   * @description: 编辑时候影藏密码表单项 , 创建时候显示
   */
  const handlePwdFiled = () => {
    useFormProps.value.schemas?.forEach((item: any) => {
      if (item.field === PASSWORD) {
        item.show = !unref(isUpdate);
      }
    });
  };

  // id 查询
  const {
    state: detail,
    isReady: isDetailReady,
    isLoading,
    execute,
  } = useAsyncState(
    () => {
      return UserApi.getById(entityId.value).then((res: User) => res);
    },
    null,
    {
      immediate: false,
    },
  );

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    entityId.value = data?.record?.id;

    handlePwdFiled();

    if (unref(isUpdate)) {
      await execute();
      if (detail.value) {
        const formData: any = { ...detail.value };
        formData.distributorId = {
          label: data.record.distributor?.name || getDistributorText(data.record.distributorId),
          value: data.record.distributorId,
        };
        // 因为角色是单选。所以这里要把数组转换成单个对象
        let roleObj = {};
        if (formData.roleList && formData.roleList[0]) {
          const item = formData.roleList[0];
          roleObj = {
            label: item.remark,
            value: item.id,
          };
        }
        formData.roleList = roleObj;
        await setFieldsValue(formData);
      }
    }
  });

  const getConfirmDisabled = computed(() => {
    if (unref(isUpdate)) {
      return !unref(isDetailReady);
    } else {
      return false;
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      const { distributorId, ...rest } = values;
      const action = !unref(isUpdate) ? UserApi.add : UserApi.update;
      const data = !unref(isUpdate)
        ? {
            ...rest,
            distributorId: distributorId.value,
            distributorName: distributorId.label,
          }
        : Object.assign(
            {},
            {
              ...rest,
              id: unref(entityId),
              distributorId: distributorId.value,
              distributorName: distributorId.label,
              status: StatusValEnum.PENDING_REVIEW,
            },
          );
      data.roleList = [{ id: data.roleList.value }];
      await action(data);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
