<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
  >
    <template #footer>
      <div v-if="isUpdate !== 3">
        <a-button type="default" @click="handleCancle">取消</a-button>
        <a-button type="primary" @click="handleSubmit">确认</a-button>
      </div>
    </template>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, useModalInner } from "@/components/Modal";
import { BasicForm, useForm } from "@/components/Form";
import { computed, ref, unref } from "vue";
import { infoInfo, infoAdd, infoUpdate } from "@/api/basicInfo/tenement";
import { modalSchemas } from "./info.data";
import {
  thirdPartyUserAdd,
  thirdPartyUserInfo,
  thirdPartyUserUpdate,
} from "@/api/system/user";

defineOptions({ name: "InfoModal" });

const emit = defineEmits(["register", "reload"]);
const infos = ref<any>({});
const isUpdate = ref<number>(1);
const title = computed<string>(() => {
  return "新增用户";
});

const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { info; record?: Recordable; update: number }) => {
    modalLoading(true);
    const { info, record, update } = data;
    isUpdate.value = update;
    infos.value = info;
    if (isUpdate.value === 3) {
      setProps({ disabled: true });
    } else {
      setProps({ disabled: false });
    }
    if ((update === 1 || update === 3) && record) {
      const ret = await thirdPartyUserInfo(record.id);
      await setFieldsValue(ret);
    }
    modalLoading(false);
  }
);

const [registerForm, { setFieldsValue, resetForm, validate, setProps }] = useForm({
  labelWidth: 140,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
  schemas: modalSchemas,
});

async function handleSubmit() {
  try {
    modalLoading(true);
    const data = await validate();
    if (isUpdate.value === 1) {
      await thirdPartyUserUpdate({ ...data, unitId: infos.value.id });
    } else {
      await thirdPartyUserAdd({ ...data, unitId: infos.value.id });
    }
    emit("reload");
    closeModal();
    await resetForm();
  } catch (e) {
    console.warn(e);
  } finally {
    modalLoading(false);
  }
}
function handleCancle() {
  closeModal();
  resetForm();
}
</script>

<style scoped></style>
