<template>
  <div :class="classObject">
    <template v-if="formData.popupType === 'general'">
      <div 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">
        <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading" style="width: 100%"> {{ '提 交' }}</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 type="primary" @click="submitSuccess = false" size="medium">复制录入</el-button>
            <el-button
              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, 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
    }
  },
  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.relationConf = JSON.parse(this.config.relationData)
          this.formData = JSON.parse(this.config.formData)
          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
      }
    },
    sumbitForm(data) {
      if (!data) return
      let serialincNumberData = this.getSerialincNumberData(this.formData.fields, data)
      this.btnLoading = true
      let subimtData = []
      // 输入查询字符和对象，返回匹配的键的值组成的对象
      function searchHostObject(query, object) {
        const result = {}
        for (const key in object) {
          if (!object.hasOwnProperty(key) || !key.includes(query)) {
            result[key] = object[key]
          }
        }
        return result
      }
      function searchAssistantObject(query, object) {
        let result = []
        for (const key in object) {
          if (object.hasOwnProperty(key) && key.includes(query)) {
            result = object[key]
          }
        }
        return result
      }
      //查询主表字段
      const HostObj = searchHostObject('tableField', data)
      //查询子表字段
      const AssistantArray = searchAssistantObject('tableField', data)
      //存在子表
      if (AssistantArray.length) {
        //数据合并
        AssistantArray.forEach((i, k) => {
          Object.assign(i, HostObj)
        })
        subimtData = AssistantArray.map((i, k) => {
          return {
            id: '',
            oldData: null,
            data: JSON.stringify(i),
            ...serialincNumberData
          }
        })
      } else {
        subimtData = [{ data: JSON.stringify(data), id: '', ...serialincNumberData }]
      }
      createModel(this.modelId, subimtData)
        .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()
    },
    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;
  background: #ebeef5;
  padding: 10px;
}
@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>
