<template>
  <div class="page-modal">
    <form-order v-bind="modalConfig" v-model="formData" ref="formRef"></form-order>
  </div>
</template>

<script>
  import { defineComponent, ref, watch } from 'vue';
  import useSystemStore from '@/store/main/system/system';

  import FormOrder from '@/base-ui/form-order';

  export default defineComponent({
    components: {
      FormOrder,
    },
    emits: ['dataChange'],
    props: {
      modalConfig: {
        type: Object,
        required: true,
      },
      defaultInfo: {
        type: Object,
        default: () => ({}),
      },
      otherInfo: {
        type: Object,
        default: () => ({}),
      },
      pageName: {
        type: String,
        require: true,
      },
    },
    setup(props, { emit }) {
      const formData = ref({});
      const formRef = ref();

      watch(
        () => props.defaultInfo,
        (newValue) => {
          for (const item of props.modalConfig.formItems) {
            formData.value[`${item.field}`] = newValue[`${item.field}`];
          }
          emit('dataChange', formData.value);
        },
        {
          deep: true, // 深度监听的参数
        },
      );
      watch(
        () => formData.value,
        (newValue) => {
          console.log(newValue, 'newValue');
          emit('dataChange', newValue);
        },
      );
      // 点击确定按钮的逻辑
      const handleConfirmClick = () => {
        formRef.value.ruleFormRef.validate((valid, fields) => {
          if (valid) {
            if (Object.keys(props.defaultInfo).length) {
              // 编辑
              const idName = props.pageName.split('/')[props.pageName.split('/').length - 1] + 'Id';
              console.log('编辑用户');
              useSystemStore().editPageDataAction({
                pageName: props.pageName,
                editData: { ...formData.value, ...props.otherInfo },
                id: props.defaultInfo[idName],
                idName: idName,
              });
            } else {
              // 新建
              console.log('新建用户');
              useSystemStore().createPageDataAction({
                pageName: props.pageName,
                newData: { ...formData.value, ...props.otherInfo },
              });
            }
          } else {
            console.log('验证失败');
          }
        });
      };

      return {
        formData,
        formRef,
        handleConfirmClick,
      };
    },
  });
</script>

<style scoped></style>
