<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
  >
    <BasicForm @register="registerForm" layout="vertical" class="!px-6 !pt-4" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicWeekEnum, dataFormSchema } from './data';

  import {
    bedScheduledPersonAdd,
    bedScheduledPersonEdit,
    bedScheduledPersonDetail,
  } from '/@/api/biz/bed/scheduledPersonApi';
  import { getWorkingDay } from '/@/api/biz/management/working';

  import dayjs from 'dayjs';

  const emit = defineEmits(['success', 'register']);

  const getTitle = ref();
  const width = '45%';
  const isUpdate = ref(false);
  const rowId = ref();
  const specialNeedWeekOption = ref([]);

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    baseColProps: {
      span: 12,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    getTitle.value = `${isUpdate.value ? '编辑排班' : '新建排班'} ( ${data.record.patientName} | ${
      data.record.gender
    } | ${data.record.age}岁 )`;

    if (unref(isUpdate)) {
      const resData = await bedScheduledPersonDetail(data.record.patientBasicId);
      console.log('🚀 ~ file: FormModal.vue:54 ~ resData:', resData);
      rowId.value = resData.patientBasicId;
      const workingDay = await getWorkingDay();
      let specialNeedWeek = [];
      specialNeedWeekOption.value = [];
      // const specialNeedWeekOption = [];
      for (const i in workingDay) {
        if (resData.specialNeed && resData.specialNeed[i]) {
          specialNeedWeek = specialNeedWeek.concat(i);
        }
        specialNeedWeekOption.value.push({
          label: BasicWeekEnum[i],
          value: i,
        });
      }
      const fieldsData = Object.assign(resData, {
        frequency: {
          input: resData.frequency?.times || 2,
          dictValue: resData.frequency?.week == 1 ? 'week_1' : 'week_2',
          // dictValue: 'week_2',
        },
        sailingSorts: resData.specialNeed?.sailingSorts || [],
        specialNeedWeek,
      });
      console.log('🚀 ~ file: FormModal.vue:80 ~ fieldsData:', fieldsData);
      await updateSchema({
        field: 'specialNeedWeek',
        componentProps: {
          options: specialNeedWeekOption.value,
        },
      });
      await setFieldsValue({
        ...fieldsData,
      });
    } else {
      await setFieldsValue({
        appointmentDate: dayjs().format('YYYY-MM-DD'),
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      values.frequency = {
        week: values.frequency.dictValue == 'week_2' ? 2 : 1,
        times: values.frequency.input,
      };
      values.specialNeed = {};
      specialNeedWeekOption.value.forEach(ele => {
        if (values.specialNeedWeek.includes(ele.value)) {
          values.specialNeed[ele.value] = true;
        } else {
          values.specialNeed[ele.value] = false;
        }
      });
      values.specialNeed['sailingSorts'] = values.sailingSorts.sort();
      delete values.specialNeedWeek;
      delete values.sailingSorts;
      console.log('🚀 ~ file: FormModal.vue:98 ~ handleSubmit ~ values:', values);
      setModalProps({ confirmLoading: true });
      !unref(isUpdate)
        ? await bedScheduledPersonAdd({ ...values })
        : await bedScheduledPersonEdit({ ...values, patientBasicId: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeModal();
      emit('success', {
        isUpdate: unref(isUpdate),
        values: { ...values, id: rowId.value },
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
