<template>
  <el-dialog
    :visible.sync="show"
    :title="configData.title"
    :modal-append-to-body="false"
    :width="`${percentWidth}%`"
    @close="handleCancel"
  >
    <PublicForm
      ref="publicForm"
      :form-arr="formArr"
      :form-data="formData"
      @outOperation="outOperation"
    />
    <span
      slot="footer"
      class="dialog-footer"
    >
      <slot name="footerBtn" />
      <el-button
        type="default"
        :size="$buttonSize"
        @click="handleCancel"
      >取 消</el-button>
      <el-button
        type="primary"
        :size="$buttonSize"
        @click="dialogOK"
      >保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import PublicForm from '@/components/form/index.vue';
export default {
  components: {
    PublicForm,
  },
  props: {
    visible: { // 是否展示弹窗
      type: Boolean,
      default: false,
    },
    formArr: { // 配置数组
      type: Array,
      required: true,
    },
    percentWidth: { // 弹窗宽度
      type: Number,
      default: 30,
    },
    formData: { // 表单数据
      type: Object,
      default: () => {},
    },
    /**
     * 配置对象
     * title          标题
     * addApi         新增接口
     * editApi        修改接口
     * type           1 新增  2 编辑
     * transFormData  参数处理方法
     * 默认  transformRequest: (params) => {
              return params;
            }
     */
    configData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      show: false,
    };
  },
  watch: {
    visible: {
      handler(nv) {
        this.show = nv;
      },
    },
  },
  methods: {
    handleCancel() {
      console.log('我是formArr', this.formArr);
      this.$emit('handleCancel');
    },
    outOperation(val, index, prop, num) {
      console.log('我是outOperation', val, index, prop, num);
    },
    dialogOK() {
      // 判断表单验证是否通过
      if (this.$refs.publicForm.submitForm()) {
        console.log('success');
        console.log(this.formData);
        const api = { 1: this.$apis[this.configData.addApi], 2: this.$apis[this.configData.editApi] };
        const params = this.configData.transFormData(this.formData);
        api[this.configData.type](params).then(res => {
          this.$message.success('操作成功');
          this.$emit('dialogOK', res);
        });
      } else {
        console.log('error');
        this.$emit('dialogCancel');
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .titiebox .titieboxlabel {
  white-space: nowrap;
}
</style>
