<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
    :width="800"
  >
    <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 { workDataInfo, workDataAdd, workDataUpdate } from "@/api/workPlace/workInfo";
import { modalSchemas } from "./workData.data";
import { convertNumberToString } from "@/utils/tool";

defineOptions({ name: "WorkDataModal" });

const emit = defineEmits(["register", "reload"]);

const isUpdate = ref<number>(1);
const title = computed<string>(() => {
  return isUpdate.value === 1
    ? "编辑工作数据信息;"
    : isUpdate.value === 2
    ? "新增工作数据信息;"
    : "查看工作数据信息;";
});

const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; update: number }) => {
    modalLoading(true);
    const { record, update } = data;
    isUpdate.value = update;
    if (isUpdate.value === 3) {
      setProps({ disabled: true });
    } else {
      setProps({ disabled: false });
    }
    if ((update === 1 || update === 3) && record) {
      const ret = await workDataInfo(record.id);
      ret.workType = convertNumberToString(ret.workType )
      ret.state = convertNumberToString(ret.state )
      console.log(ret)
      ret.planType = ret.planType?convertNumberToString(ret.planType):''
      await setFieldsValue(ret);
    }
    modalLoading(false);
  }
);

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

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

<style scoped></style>
