<template>
  <div :class="classObject">
    <template v-if="formData.popupType === 'general'">
      <div v-if="config.visualdevType !== 3" class="dialog-header">信息录入</div>
      <parser :form-conf="formData" :relation-conf="relationConf" :idKey="idKey" @submit="sumbitForm" :key="key" ref="dynamicForm" v-if="!loading" />
      <span slot="footer" :class="['dialog-footer', config.visualdevType === 3 ? 'dataFlowFooter' : '']">
        <el-button v-if="config.visualdevType !== 3" type="primary" @click="dataFormSubmit()" :loading="btnLoading" style="width: 100%"> {{ '提 交' }}</el-button>
        <el-button v-if="config.visualdevType === 3" type="primary" @click="goFlowBack()" :loading="btnLoading"> {{ '取 消' }}</el-button>
        <el-button v-if="config.visualdevType === 3" type="primary" @click="dataFormSubmit()" :loading="btnLoading"> {{ '提交审批' }}</el-button>
      </span>
    </template>
    <template v-if="formData.popupType === 'fullScreen'">
      <transition name="el-zoom-in-center">
        <div class="JNPF-preview-main">
          <div class="JNPF-common-page-header">
            <el-page-header @back="goBack" title="信息录入" />
            <div class="options">
              <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading" style="width: 100px"> {{ '提 交' }}</el-button>
            </div>
          </div>
          <div class="dynamic-form-main" :style="{ margin: '0 auto', width: formData.fullScreenWidth }">
            <parser :form-conf="formData" :relation-conf="relationConf" :idKey="idKey" @submit="sumbitForm" :key="key" ref="dynamicForm" v-if="!loading" />
          </div>
        </div>
      </transition>
    </template>
    <template v-if="submitSuccess">
      <div class="submitSuccess">
        <el-result icon="success" title="提交成功" subTitle="请根据按钮提示进行操作">
          <template slot="extra">
            <el-button v-if="config.visualdevType === 3" type="primary" @click="goFlowBack()" size="medium">返回</el-button>
            <el-button v-if="config.visualdevType !== 3" type="primary" @click="submitSuccess = false" size="medium">复制录入</el-button>
            <el-button v-if="config.visualdevType !== 3"
              type="primary"
              @click="
                submitSuccess = false
                getConfigData()
              "
              size="medium"
              >重新录入</el-button
            >
          </template>
        </el-result>
      </div>
    </template>
  </div>
</template>

<script>
import Parser from '@/components/Generator/parser/Parser'
import {createModel, getConfigData, NewCreateModel, NewFlowCreateModel, updateModel} from '@/api/onlineDev/visualDev'
import { deepClone } from '@/utils'
import { getToken } from '@/utils/auth'
import moment from 'moment/moment'
export default {
  name: 'dataCreate',
  components: { Parser },
  data() {
    return {
      visible: true,
      loading: false,
      dataForm: {
        id: '',
        data: ''
      },
      key: +new Date(),
      btnLoading: false,
      modelId: '',
      config: {},
      formData: {},
      idKey: '',
      relationConf: [],
      columnDict: [],
      screenWidth: window.innerWidth,
      submitSuccess: false,
      secondaryDbLinkIdList:[],
      dbLinkId: ''
    }
  },
  created() {
    this.modelId = this.$route.query.id
    if (!this.modelId) return
    this.getConfigData()
  },
  computed: {
    classObject() {
      return {
        dataCreate: this.screenWidth <= 768,
        dataCreatePc: this.screenWidth > 768
      }
    }
  },
  methods: {
    getConfigData() {
      this.loading = true
      getConfigData(this.modelId)
        .then((res) => {
          if (res.data.code !== 200) {
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.replace('/404')
          }
          if (!res.data.data) return
          this.config = res.data.data
          this.dbLinkId = this.config.dbLinkId
          // this.relationConf = JSON.parse(this.config.relationData)
          this.formData = JSON.parse(this.config.formData)
          this.secondaryDbLinkIdList = this.formData.fields
            .map((o) => {
              if (o.__config__.jnpfKey === 'table') {
                return o.__vModel__
              }
            })
            .filter((l) => l !== undefined)
          if (this.config.visualdevType !== 3) {
            if (window.innerWidth > 767) {
              this.formData.popupType = 'fullScreen'
            } else {
              this.formData.labelPosition = 'top'
            }
          }
          this.idKey = this.config.idKey
          this.$nextTick(() => {
            this.loading = false
          })
          this.key = +new Date()
        })
        .catch(() => {})
    },
    getSerialincNumberData(fields, data) {
      let obj = fields.find((o) => o.__config__.jnpfKey === 'serialNumber')
      if (obj) {
        let copySet = deepClone(obj.serialgz)
        copySet.forEach((i, k) => {
          //根据设置生成数据
          if (i.type === 'createTime') {
            this.$set(i, 'chars', moment().format(i.format))
          }
          if (i.type === 'widget') {
            this.$set(i, 'chars', data[i.widgetvModel])
          }
        })
        return { _serialNumber: obj.__vModel__, _serialNumberConfig: copySet }
      } else {
        return null
      }
    },
    //子表整合数据
    flattenedArrayWithKey(foreignObj) {
      const result = []
      for (const key in foreignObj) {
        foreignObj[key].forEach((item) => {
          result.push({ dbLink: key, id: '', oldData: null, data: JSON.stringify(item) })
        })
      }
      return result
    },
    sumbitForm(data) {
      if (!data) return
      data = Object.keys(data).reduce((obj, key) => {
        if (!key.startsWith('isOnlyRead_')) {
          obj[key] = data[key]
        }
        return obj
      }, {})
      let params = {}
      //主表数据
      const primaryObj = {}
      //子表数据
      const foreignObj = {}
      this.formData.fields.forEach((item) => {
        if (item.__config__.jnpfKey === 'uploadImg') {
          let val = ''
          if (data[item.__vModel__] && data[item.__vModel__].length) {
            data[item.__vModel__].forEach((item) => {
              // 如果是数字
              if (item > 0) {
                val += item + ';'
              } else if (item.type === 'new') {
                val += item.url + ';'
              }
            })
          }
          // 去掉最后一个分号
          data[item.__vModel__] = val.substring(0, val.length - 1)
        }
        if (item.__config__.jnpfKey === 'uploadFz') {
          let val = ''
          if (data[item.__vModel__] && data[item.__vModel__].length) {
            data[item.__vModel__].forEach((item) => {
              if (item > 0) {
                val += item + ';'
              } else if (item.id) {
                val += item.id + ';'
              }
            })
          }
          // 去掉最后一个分号
          data[item.__vModel__] = val.substring(0, val.length - 1)
        }
        if (item.__config__.isJoin) {
          delete data[item.__vModel__]
        }
      })
      //获取提交数据时 查询存在于子表数据集合的key 将主子表数据区分开
      for (const key in data) {
        if (this.secondaryDbLinkIdList.includes(Number(key)) && Array.isArray(data[key])) {
          foreignObj[key] = data[key]
        } else {
          primaryObj[key] = data[key]
        }
      }
      let serialincNumberData = this.getSerialincNumberData(this.formData.fields, data)
      this.btnLoading = true
      //主表整合信息
      let primaryTable = {
        dbLink: this.dbLinkId,
        id: '',
        oldData: null,
        data: JSON.stringify(primaryObj),
        ...serialincNumberData
      }
      //子表整合数据
      let foreignTable = this.flattenedArrayWithKey(foreignObj)
      params = {
        primaryTable: primaryTable,
        foreignTable: foreignTable
      }
      if (this.config.visualdevType === 3) {
        params.modelId = this.modelId
        params.flowId = this.config.flowId
      }
      const formMethod = this.config.visualdevType === 3 ? NewFlowCreateModel : NewCreateModel
      formMethod(this.modelId, params,'',this.dbLinkId)
        .then((res) => {
          this.$message({
            message: res.data.msg,
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.submitSuccess = true
              this.visible = false
              this.btnLoading = false
            }
          })
        })
        .catch(() => {
          this.btnLoading = false
        })
    },
    dataFormSubmit() {
      this.$refs.dynamicForm && this.$refs.dynamicForm.submitForm()
    },
    goFlowBack(isRefresh) {
      this.visible = false
      window.parent.postMessage({ reloadIframe: true }, '*')
      this.$emit('close', isRefresh)
    },
    goBack() {
      let url = decodeURI(window.location.search || window.location.hash)
      //获取哈希地址信息
      function queryURLParams(url) {
        let result = {},
          reg1 = /([^?=&#]+)=([^?=&#]+)/g,
          reg2 = /#([^?=&#]+)/g
        url.replace(reg1, (n, x, y) => (result[x] = y))
        url.replace(reg2, (n, x) => (result['HASH'] = x))
        return result
      }
      let paramsObj = queryURLParams(url)
      this.$router.push(`/previewModel?isPreview=1&token=${process.env.NODE_ENV === 'development' ? getToken() : paramsObj.token}&id=${this.modelId}`)
    }
  }
}
</script>

<style lang="scss">
.app-main {
  background: #ffffff !important;
  height: calc(100vh - 0px) !important;
}
.dataCreate {
  padding: 35px 0 55px;
  position: relative;
  .dialog-header {
    position: fixed;
    width: 100%;
    padding: 10px;
    text-align: center;
    top: 0;
    left: 0;
    background-color: #ffffff;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
    z-index: 99;
  }
  .dialog-footer {
    position: fixed;
    display: block;
    bottom: -1px;
    left: 0;
    width: 100%;
    padding: 10px;
    background-color: #ffffff;
    z-index: 99;
    .el-button {
      height: 45px;
    }
  }
}
.dataCreatePc {
  height: calc(100vh - 60px);
  overflow: hidden;
  padding: 10px;
}
.dataFlowFooter{
  text-align: right;
  display: block;
}
@media (max-width: 768px) {
  .el-date-range-picker .el-picker-panel__body {
    min-width: 100%;
  }
  .el-date-range-picker__content {
    width: 100% !important;
  }
  .el-date-range-picker {
    width: 80% !important;
  }
  .el-date-range-picker__content {
    margin: 0;
    padding: 5px;
  }
  .el-date-range-picker__content.is-left {
    padding-bottom: 0;
  }
  .el-date-range-picker__content.is-right {
    padding-top: 0;
  }
  .el-date-table th {
    padding: 0;
  }
  .el-date-table td {
    padding: 0;
  }
}
.submitSuccess {
  position: fixed;
  top: 0;
  left: 0;
  background: rgb(213 212 212 / 80%);
  width: 100%;
  height: 100%;
  z-index: 99;
  padding: 150px 20px 0;
  .el-result {
    background-color: #ffffff;
  }
}
.el-input-number {
  width: 100% !important;
}
</style>
