<template>
  <a-spin :spinning="confirmLoading>0">
<!--    <div class="form-redirect-toolbar" v-if="showSaveBut">-->
<!--      <span class="form-redirect-title"></span>-->
<!--      <div class="form-redirect-button-group">-->
<!--        <a-popconfirm placement="bottomRight" :title="$locle('m.common.tip.save_confirm')" @confirm="() => saveDraft()">-->
<!--          <a-button icon="save" type="primary" v-if="enableDraft">{{ $locle('m.common.button.saveDraft') }}</a-button>-->
<!--        </a-popconfirm>-->

<!--        <a-popconfirm placement="bottomRight" :title="$locle('m.common.tip.save_confirm')" @confirm="() => handleOk()">-->
<!--          <a-button icon="save" type="primary">{{ $locle('m.common.button.save') }}</a-button>-->
<!--        </a-popconfirm>-->
<!--      </div>-->
<!--    </div>-->

    <k-form-build @refreshParent="refreshParent" @close="close" :value="jsonData" @submit="handleSubmit" ref="KFormBuild" :allDataSource="allDataSource"
                  @refreshAllData="refreshAllData" :dsCode="dsCode" :stores="stores"
                  v-bind="$attrs"
                  @addModelKey="addModelKey" :dictMap="dictMap" :elValue="elValue" :formId="id" :fks="fks" :uploadTimestamp="uploadTimestamp"/>
  </a-spin>
</template>

<script>

  import {getAction, postAction} from '../../utils/manage'
  import {FormMixin} from '../../utils/FormMixin'
  import KFormBuild from '../../../packages/KFormBuild/index.vue'
  import YchConstant from "../../utils/YchConstant";
  import RelationUtil from "./RelationUtil";
  import locleUtil from "../../utils/LocleUtil";

  export default {
    name: 'FormRedirect',
    mixins: [FormMixin],
    components: {
      KFormBuild
    },
    props: {
      hiddenSaveBut: {
        type: Boolean,
        default: false,
      },
      formId: {
        type: String,
        default: null
      },
      formCode: {
        type: String,
        default: null
      },
      fks: {
        type: Array,
        default: () => []
      },
      parentValue: {
        type: Object,
        default: () => {
        }
      },
      func: {
        type: String,
        default: null
      },
      relationList: Array,
      refreshMap: Object,
      // 仅在页面暂时存储，用于子表添加
      saveInPage: {
        type: Boolean,
        default: false
      },
      disQueryDB: {
        type: Boolean,
        default: false
      },
      isTab: {
        type: Boolean,
        default: false // 是否从tab页签进入
      },
      record: {
        type: Object,
        default: () => {
        }
      },
      stores: {
        type: Object,
        default: () => {
          return {}
        }
      },
      tabConfig: Object,
      relationStatus: String,
      relationOpenFks: String,
      isTransport: Boolean
    },
    data() {
      return {
        syncNum: 0, // 防止异步
        tableName: null,
        getTableNameByFormCode: YchConstant.PREFIX_EFORM + '/engine/formEngine/getTableNameByFormCode',
        getIdByFkUrl: YchConstant.PREFIX_EFORM + '/engine/viewEngine/getIdByFk',
        relationValue: null,
      }
    },
    computed: {
      showSaveBut() {
        return !this.hiddenSaveBut && this.jsonData.config && !this.jsonData.config.hideDialogButtons && (this.func === 'add' || this.func === 'edit')
      },
    },
    methods: {
      $locle(params) {
        return locleUtil.getLocale(params)
      },
      checkFks() {
        return RelationUtil.checkFks({
          fks: this.fks,
        })
      },
      switchTab() {
        if (this.fks.length === 0) {
          return;
        }
        if (!this.checkFks()) {
          this.jsonData = {}
        }
        const fpk = this.fks[0]
        if (fpk.relationType === "temp-main-form") {
          // 当前表
          this.id = fpk.queryValue;
          this[this.func].apply(this)
        } else {
          // 一对一
          // TODO 一对一校验，可能不需要
          this.syncNum++
          const syncNum = this.syncNum
          this.getIdByFk().then(res => {
            // 防止异步
            if (syncNum !== this.syncNum) {
              return;
            }
            if (res.success) {
              if (res.result) {
                this.id = res.result
                this[this.func].apply(this)
              } else {
                this.id = null
                this['add'].apply(this)
              }
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      },
      getIdByFk() {
        return postAction(this.getIdByFkUrl + '?tableName=' + this.tableName, {fks: this.fks});
      },
      refreshAllData(){
        // 重新加载
        this[this.func].apply(this)
      },
      handleOk() {
        if (this.isTab) {
          this.$emit("handleOk", this)
        } else {
          this.save()
        }
      },
      saveDraft(){
        if (this.isTab) {
          this.$emit("handleOk", this,true)
        } else {
          this.save(null,null,true)
        }
      },
      setPk() {
        if (this.formValues && this.tableName) {
          this.$emit('setPk', {
            record: this.formValues,
            tableName: this.tableName,
            relationStatus: this.relationStatus,
            isForm: true,
          })
        }
      },
      initInView() {
        const _fks = this.fks
        const fks = RelationUtil.getChangedRelation({
          relationList: this.relationList,
          tableName: this.tableName,
          fks: this.fks,
          isForm: true,
          relationOpenFks: this.relationOpenFks,
        })
        if (_fks !== fks && this.fks) {
          this.fks.splice(0, this.fks.length)
          this.fks.push(...fks)
          this.switchTab()
        }
      }
    },
    mounted() {
      this[this.func].apply(this)
    },
    created() {
      console.log(this,'formredirect')
      getAction(this.getTableNameByFormCode, {formCode: this.formCode}).then((res) => {
        if (res.success) {
          this.tableName = res.result
          this.initInView()
        }
      })

      // 把当前对象放入stores，方便其他对象使用
      if (!this.stores.$vm) {
        this.stores.$vm = {}
      }
      this.stores.$vm[this.formCode] = this
    },
    watch: {
      relationList: {
        handler() {
          this.initInView()
        }
      },
    }
  }
</script>
<style scoped lang="less">
  .form-redirect-toolbar {
    width: 100%;
    height: 50px;
    line-height: 50px;
    padding: 0 27px 8px 10px;
    background: #fff;
    border-bottom: 1px solid #e8e8e8;

    .form-redirect-title {
      height: 50px;
      line-height: 50px;
      font-size: 18px;
      font-weight: 600;
      margin: 0px 0px 0px 10px;
      display: inline-block;
    }

    .form-redirect-button-group {
      display: inline-block;
      float: right;

      .ant-btn {
        margin: 6px 6px;
      }
    }
  }
</style>
