<template>
  <BasicModal
    @ok="handleSubmit"
    :destroyOnClose="true"
    :maskClosable="false"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :width="1002"
    showFooter
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script setup lang="ts">
  import { ref, computed, unref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import {
    getClassTimeStatisticsSetLastInfo,
    postClasstimeClassTimeStatisticsSet,
    putClasstimeClassTimeStatisticsSet,
  } from '/@/services/apis/ClassTimeStatisticsSetController';

  const isUpdate = ref(true);
  const category = ref(2);
  const modelRef = ref<Recordable>({});
  const emit = defineEmits(['success', 'register']);

  const formConfig = reactive<Recordable[]>([
    { label: '早自习课时单价：正式聘用', field: 'cost1', addonAfter: '元', value: '' },
    { label: '非正式聘用', field: 'cost2', addonAfter: '元', value: '' },
    { label: '正课课时单价：正式聘用', field: 'cost3', addonAfter: '元', value: '' },
    { label: '非正式聘用', field: 'cost4', addonAfter: '元', value: '' },
    { label: '晚自习课时单价：正式聘用', field: 'cost5', addonAfter: '元', value: '' },
    { label: '非正式聘用', field: 'cost6', addonAfter: '元', value: '' },
    { label: ' 超出课时单价：正式聘用', field: 'cost7', addonAfter: '元', value: '' },
    { label: '非正式聘用', field: 'cost8', addonAfter: '元', value: '' },
    { label: '超出课时标准（每周）：正式聘用', field: 'cost9', addonAfter: '课时', value: '' },
    { label: '非正式聘用', field: 'cost10', addonAfter: '课时', value: '' },
    { label: '顶课课时单价：正式聘用', field: 'cost11', addonAfter: '元', value: '' },
    { label: '非正式聘用', field: 'cost12', addonAfter: '元', value: '' },
  ]);

  const [registerForm, { validate, resetFields, resetSchema, setFieldsValue }] = useForm({
    labelWidth: 240,
    schemas: [],
    showActionButtonGroup: false,
  });

  const [registerModal, { closeModal, setModalProps }] = useModalInner(async () => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = false;

    const formWeightSchema: FormSchema[] = [];

    formConfig.forEach((item) => {
      formWeightSchema.push({
        label: item.label,
        field: item.field,
        component: 'InputNumber',
        colProps: { span: 12 },
        required: true,
        componentProps: {
          addonAfter: item.addonAfter,
          style: { width: '100%' },
        },
      });
    });

    resetSchema(formWeightSchema);

    const resData = await getClassTimeStatisticsSetLastInfo({ category: category.value });
    if (resData) {
      modelRef.value = { ...resData };
      const jsonContent = JSON.parse(resData.jsonContent);
      const values: Recordable = {};
      jsonContent.forEach((item) => {
        values[item.field] = item.value;
      });
      setFieldsValue(values);
      isUpdate.value = true;
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '费用设置' : '费用设置'));
  const handleSubmit = async () => {
    try {
      const values = await validate();
      const jsonContent: Recordable[] = [];
      setModalProps({ confirmLoading: true });

      formConfig.forEach((item) => {
        jsonContent.push({ label: item.label, field: item.field, value: values[item.field] });
      });

      const postParams: Recordable = {
        category: category.value,
        jsonContent: JSON.stringify(jsonContent),
        id: unref(modelRef)?.id,
      };

      if (unref(isUpdate)) {
        await putClasstimeClassTimeStatisticsSet(postParams as API.UpdateClassTimeStatisticsSetDto);
      } else {
        await postClasstimeClassTimeStatisticsSet(postParams as API.AddClassTimeStatisticsSetDto);
      }

      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };
</script>

<style scoped lang="less"></style>
