<template>
  <a-form :ref="refName" :model="model" :rules="rules" @finish="submitForm" @finishFailed="onFinishFailed"
    :labelAlign="labelAlign" v-bind="$attrs">
    <a-row :gutter="16" :justify="justify"
      :style="{ backgroundColor: 'var(--background-color)', width: colSpan === 24 ? '65%' : '100%', margin: '0 auto' }">
      <slot></slot>

      <a-flex gap="small" wrap="wrap" :style="{ marginLeft: '10px', marginBottom: '10px' }" v-if="mode === 'query'">
        <a-button type="primary" @click="handleQuery" ghost>
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button type="default" @click="handleReset">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
        <a-button type="link" v-if="showMore !== -1" @click="toggleMore">
          {{ internalShowMore === 1 ? '收起' : '更多' }}
        </a-button>
      </a-flex>
    </a-row>

    <!-- 表单模式：确认/关闭按钮 -->
    <a-flex style="margin-top: 20px;" gap="small" wrap="wrap" justify="center" align="center"
      v-if="mode === 'form' && isIframe">
      <a-button type="default" @click="close">
        <template #icon>
          <CloseCircleOutlined />
        </template>
        关闭
      </a-button>
      <a-button type="primary" html-type="submit" v-if="!see" :loading="$store.loading">
        <template #icon>
          <CheckCircleOutlined />
        </template>
        确认
      </a-button>
    </a-flex>
  </a-form>
</template>
<script setup>
</script>

<script>
import { DeleteOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

export default {
  components: {
    SearchOutlined,
    DeleteOutlined
  },
  inheritAttrs: false, // 禁用自动继承，手动控制透传
  inject: {
    parentMethods: {
      from: 'parentMethods',
      default: () => ({})
    }
  },
  name: "PaasForm",
  provide() {
    const self = this;
    return {
      get labelWidth() {
        return self.labelWidth;
      },
      get defaultColSpan() {
        return self.colSpan; // 提供默认的表单项跨度
      },
    };
  },
  props: {
    refName: {
      default: "form"
    },
    id: {
      default: "id",
    },
    autoPk: {
      default: true,
    },
    model: {
      type: Object,
      required: true,
    },
    rules: {
      type: Object,
    },
    labelWidth: {
      type: [String, Number],
      default: '-1px',
    },
    labelAlign: {
      type: String,
      default: 'right',
    },
    colSpan: {
      type: Number,
      default: 24,
    },
    mode: {
      type: String,
      default: 'form', // 默认表单模式（兼容旧代码）
      validator: (value) => ['form', 'query'].includes(value)
    },
    // 表单项对齐方式：'flex-start' = 左对齐，'center' = 居中对齐
    justify: {
      type: String,
      default: 'flex-start',
      validator: (value) => ['flex-start', 'center'].includes(value)
    },
    // 查询模式：是否显示"更多"按钮
    showMore: {
      type: Number,
      default: -1, // -1表示不显示更多按钮
    },
    formatData: {
      type: Function,
      default: (data) => data
    },
    closeGo: {
      default: -1,
      type: Number,
    },
    add: {
      default: null,
      type: String,
    },
    edit: {
      default: null,
      type: String,
    }
  },
  created() {
    this.isIframe = window.self == window.top;

    if (!!this.add) {
      this.addUrl = this.add;
    } else {
      this.addUrl = this.$store.menus.current;
    }
    if (!!this.edit) {
      this.editUrl = this.edit;
    } else {
      this.editUrl = this.$store.menus.current + "/edit";
    }
  },
  data() {
    return {
      isIframe: false,
      addUrl: "",
      editUrl: "",
      confirmFlag: false,
      internalShowMore: this.showMore, // 查询模式：控制更多/收起
    };
  },
  computed: {
    see() {
      return this.$store.forms.see;
    },
    action() {
      return this.$store.forms.action;
    },
  },
  watch: {
    showMore(newValue) {
      this.internalShowMore = newValue;
    }
  },
  methods: {
    // 查询模式：查询按钮点击
    handleQuery() {
      if (this.model.page) {
        this.model.page.current = 1;
      }
      this.$store.setQueryData(JSON.parse(JSON.stringify(this.model)));
      this.$bus.emit("loadData");
    },
    // 查询模式：清空按钮点击
    handleReset() {
      const resetModel = (obj) => {
        for (let key in obj) {
          if (typeof obj[key] === 'object' && obj[key] !== null) {
            obj[key] = Array.isArray(obj[key]) ? [] : {};
            resetModel(obj[key]);
          } else {
            switch (typeof obj[key]) {
              case 'string':
                obj[key] = null;
                break;
              case 'number':
                obj[key] = null;
                break;
              case 'boolean':
                obj[key] = false;
                break;
            }
          }
        }
      };
      resetModel(this.model);
      this.$emit('update:model', { ...this.model });
    },
    // 查询模式：切换更多/收起
    toggleMore() {
      this.internalShowMore = this.internalShowMore === 1 ? 0 : 1;
      this.$emit("update:showMore", this.internalShowMore);
    },
    onFinishFailed(errorInfo) {
      message.warn(errorInfo.errorFields[0].errors, 2.5);
    },
    submitForm(values) {
      if (this.confirmFlag) {
        return;
      }
      this.confirmFlag = true;
      setTimeout(() => {
        this.confirmFlag = false;
      }, 2000);

      var supFunc = this.$parent['submitForm'];
      if (!supFunc) {
        supFunc = this.parentMethods && this.parentMethods['submitForm'];
      }
      if (!!supFunc && supFunc instanceof Function) {
        supFunc(this.model);
        return;
      }

      let data = this.formatData(this.model);
      if (this.action == "add") {
        this.addClick(data);
      } else if (this.action == "edit") {
        this.editClick(data);
      }
    },
    addClick(data) {
      if (this.autoPk) {
        data.id = "";
      }
      this.$post(this.addUrl, data).then(res => {
        let data = res.data;
        if (!!this.callback) {
          this.callback(data);
        } else {
          this.$dyAlert(data, true)
        }
      });
    },
    editClick(data) {
      this.$put(this.editUrl, data).then(res => {
        let data = res.data;
        if (!!this.callback) {
          this.callback(data);
        } else {
          this.$dyAlert(data, true)
        }
      });
    },
    close() {
      this.$router.go(this.closeGo);
    },
  },
};
</script>