<template>
  <a-card :bordered="false" v-show="visible" class="card">
    <a-row :gutter="48" slot="extra">
      <a-col :md="48" :sm="48">
        <a-space class="table-page-search-submitButtons">
          <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
          <a-button type="default" @click="handleCancel()">返回</a-button>
        </a-space>
      </a-col>
    </a-row>
    <a-form :form="form" :labelCol="BaseTool.Constant.labelCol" :wrapperCol="BaseTool.Constant.wrapperCol">
      <a-row>
        <MComponent class="hover" v-for="item in components" :key="item.id" :config="config" :detail="item" @selectInfo="handleInfoSelect" />
      </a-row>
    </a-form>
    <SelectInfo ref="selectInfo" @selected="handleInfoSelected" />
  </a-card>
</template>

<script>
import MComponent from './component/modules/Component.vue'
import SelectInfo from './component/modules/SelectInfo'
import { addCustomData } from '@/api/custom/form'
export default {
  components: {
    MComponent,
    SelectInfo,
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      components: [],
      config: {},
      form: this.$form.createForm(this),
      record: {},
    }
  },
  created() {},
  methods: {
    base(record) {
      this.visible = true
      this.record = record
      this.components = JSON.parse(record.jsonString).components
      this.config = JSON.parse(record.jsonString).config
    },
    handleCancel() {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok')
    },
    handleInfoSelect(item) {
      this.$refs.selectInfo.base(item)
    },
    handleInfoSelected(keys, rows, detail) {
      const {
        form: { setFieldsValue },
      } = this
      const data = rows[0]
      const value = {}
      detail.attrs.connect.forEach((item) => {
        value[item.bind] = data[item.columnName]
      })
      this.$nextTick(() => {
        setFieldsValue(value)
      })
    },
    save() {
      const {
        form: { validateFieldsAndScroll },
      } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        console.log(2)
        if (errors) {
          this.confirmLoading = false
          return
        }
        console.log(3)
        const params = {
          jsonString: JSON.stringify(values),
          flowId: this.record.flowId,
          formId: this.record.id,
        }
        console.log(params)
        addCustomData(params).then((res) => {
          this.handleCancel()
        })
      })
    },
  },
}
</script>

<style>
</style>