<template>
  <div>
    <p class="flow-description">
      <span v-if="formName">
        {{ formName }}
        <i class="el-icon-right"></i>
      </span>
      <span>
        {{ description }}
      </span>
    </p>
    <div :class="[{ 'flow-formFlex': newformConfStyle }, 'flow-form']" :style="{ margin: '0 auto', width: formConf.fullScreenWidth }">
      <!--      旧数据-->
      <parser :style="{ width: newformConfStyle ? '40%' : '' }" :form-conf="oldformConf" :relation-conf="relationConf" :key="key + 1" ref="newdynamicForm" v-if="!loading & newformConfStyle" />
      <i v-if="newformConfStyle" class="el-icon-right" style="font-size: 80px"></i>
      <!--新数据 -->
      <parser
        :style="{ width: newformConfStyle ? '40%' : '' }"
        :form-conf="formConf"
        :relation-conf="relationConf"
        :flow-foreign-row-obj="flowForeignRowObj"
        @submit="sumbitForm"
        :key="key"
        ref="dynamicForm"
        v-if="!loading"
      />
    </div>
  </div>
</template>
<script>
import { DynamicInfo } from '@/api/workFlow/workFlowForm'
import {createModel, updateModel, getModelInfo, createFormModel} from '@/api/onlineDev/visualDev'
import Parser from '@/components/Generator/parser/Parser'
import {detail} from "@/utils";
import moment from "moment/moment";
export default {
  components: { Parser },
  data() {
    return {
      description: '',
      formName: '',
      formConf: {},
      formData: {},
      oldformConf: {},
      relationConf: [],
      flowForeignRowObj: { type: 'flow', data: '' },
      newformConfStyle: false,
      columnDict: [],
      key: +new Date(),
      loading: true,
      eventType: '',
      dataForm: {
        id: '',
        data: '',
        flowId: '',
        modelId: '',
        dataId: '',
        dataJson: ''
      },
      opType: '',
    }
  },
  methods: {
    init(data) {
      console.log(data)
      this.flowForeignRowObj = {}
      this.description = data.description
      this.formName = data.formName
      this.setting = data
      this.formConf = data.formConf ? JSON.parse(data.formConf) : {}
      this.dataForm.id = data.id || ''
      this.loading = true
      this.newformConfStyle = false
      this.opType = data.opType
      this.dataForm.modelId = data.modelId
      this.dataForm.dataId = data.id
      this.$nextTick(async () => {
        if (this.dataForm.id) {
          if (data.type == 1) {
            const detailData = await detail(data.modelId, data.primaryTableId, data.idKey, data.id)
            // getModelInfo(data.flowId, this.dataForm.id).then((res) => {
            //   this.dataForm = res.data.data
            //   if (!this.dataForm.data) return
              this.formData = detailData.data
              if (data.id) this.fillFormData(this.formConf, this.formData,detailData.columnDict)
              this.$nextTick(() => {
                this.loading = false
                this.$emit('setPageLoad')
              })
            // })
          } else {
            // DynamicInfo(this.dataForm.id).then(res => {
            this.dataForm = {data: data.formDataJson, id: data.id, flowId: data.flowId}
            if (!this.dataForm.data) return
            this.formData = JSON.parse(this.dataForm.data)
            // 适用于主子表类型表单的新增使用
            if (this.formData?.formData?.foreignTable && this.formData?.formData?.foreignTable.length) {
              // 使用 reduce 方法转换数据格式
              let result = this.formData.formData.foreignTable.reduce((acc, {data, dbLink}) => {
                // 解析 data 字段中的 JSON 字符串并转为对象
                let parsedData = JSON.parse(data)
                // 构建对象的键值对
                let newObj = Object.fromEntries(Object.entries(parsedData).map(([key, value]) => [key, value]))
                // 添加到对应的 dbLink 分组下
                acc[dbLink] = acc[dbLink] || []
                acc[dbLink].push(newObj)
                return acc
              }, {})
              this.flowForeignRowObj = { type: 'flow', data: result }
            }
            // 适用于主子表类型表单的编辑使用
            if (this.formData?.foreignTable && this.formData?.foreignTable.length) {
              // 使用 reduce 方法转换数据格式
              let result = this.formData.foreignTable.reduce((acc, {data, dbLink}) => {
                // 解析 data 字段中的 JSON 字符串并转为对象
                let parsedData = JSON.parse(data)
                // 构建对象的键值对
                let newObj = Object.fromEntries(Object.entries(parsedData).map(([key, value]) => [key, value]))
                // 添加到对应的 dbLink 分组下
                acc[dbLink] = acc[dbLink] || []
                acc[dbLink].push(newObj)
                return acc
              }, {})
              this.flowForeignRowObj = { type: 'flow', data: result }
            }
            //表单编辑回显时数据结构跟新增删除不同 需要单独处理
            if (this.formData?.primaryTable?.data && this.formData?.primaryTable.oldData) {
              this.oldformConf = data.formConf ? JSON.parse(data.formConf) : {}
              //编辑回显时样式也不同
              this.newformConfStyle = true
              //编辑后的数据
              let oldData = JSON.parse(this.formData.primaryTable.oldData)
              //老数据
              this.formData = JSON.parse(this.formData.primaryTable.data)
              this.fillFormData(this.oldformConf, oldData)
              this.fillFormData(this.formConf, this.formData)
            } else {
              this.fillFormData(this.formConf, this.formData)
            }
            this.$nextTick(() => {
              this.loading = false
              this.$emit('setPageLoad')
            })
            // })
          }
        } else {
          this.formData = {}
          this.fillFormData(this.formConf, this.formData,{})
          this.$nextTick(() => {
            this.loading = false
            this.$emit('setPageLoad')
          })
          this.dataForm.flowId = data.flowId
        }
        this.key = +new Date()
      })
    },
    fillFormData(form, data, columnDict) {
      if (this.opType != '-1') form.disabled = true // this.setting.readonly
      const loop = (list) => {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          if (item.__vModel__) {
            if (item.__config__.isJoin) {
              item.__config__.defaultValue = data[item.__vModel__]
              // 置灰
              item.readonly = true
            }else if (data.hasOwnProperty(item.__vModel__ + '_TEXT')){
              item.__config__.defaultValue = data[item.__vModel__ + '_TEXT'] || data[item.__vModel__]
            } else {
              const val = this.opType == '-1' ? data[columnDict[item.__vModel__]] : data[item.__vModel__]
              if (val) item.__config__.defaultValue = val
              if (item.__config__.viewDataType === 'DATETIME') {
                // if (this.useDateList.indexOf(item.__config__.jnpfKey) < 0){
                item.__config__.defaultValue = val ? moment(val).valueOf() : null
                // }
              }
              if (item.__config__ && item.__config__.jnpfKey === 'cascader') {
                try {
                  item.__config__.defaultValue = val ? val.split(item.props.props.separator || ';') : val
                } catch {}
              }
              if (item.__config__ && item.__config__.jnpfKey === 'select') {
                try {
                  item.__config__.defaultValue = val.toString()
                } catch {}
              }
              if (item.__config__ && item.__config__.jnpfKey === 'uploadImg') {
                item.__config__.defaultValue = item.__config__.defaultValue.length ? item.__config__.defaultValue.split(';') : []
              }
              if (item.__config__ && item.__config__.jnpfKey === 'uploadFz') {
                item.__config__.defaultValue = item.__config__.defaultValue.length ? item.__config__.defaultValue.split(';') : []
              }
              let noShow = false,
                isDisabled = true
              if (this.setting.formOperates && this.setting.formOperates.length) {
                let arr = this.setting.formOperates.filter((o) => o.id === item.__vModel__) || []
                if (arr.length) {
                  let obj = arr[0]
                  noShow = !obj.read
                  isDisabled = !obj.write
                }
              } else {
                isDisabled = false
              }
              isDisabled = item.disabled ? item.disabled : isDisabled
              noShow = item.__config__.noShow ? item.__config__.noShow : noShow
              if (this.setting.readonly) isDisabled = true
              this.$set(item, 'disabled', isDisabled)
              this.$set(item.__config__, 'noShow', noShow)
            }
          }
          if (item.__config__ && item.__config__.jnpfKey !== 'table' && item.__config__.children && Array.isArray(item.__config__.children)) {
            loop(item.__config__.children)
          }
        }
      }
      loop(form.fields)
    },
    sumbitForm(data) {
      if (!data) return
      this.dataForm.data = JSON.stringify(data)
      this.dataForm.dataJson = JSON.stringify(data)
      if (this.setting.type == 1) {
        if (this.eventType === 'save' || this.eventType === 'submit') {
          this.selfSubmit()
          return
        }
        this.$emit('eventReciver', this.dataForm, this.eventType)
      } else {
        this.$emit('eventReciver', this.dataForm, this.eventType)
      }
    },
    selfSubmit() {
      this.dataForm.status = this.eventType === 'submit' ? 0 : 1
      if (this.eventType === 'save') return this.selfHandleRequest()
      this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.selfHandleRequest()
        })
        .catch(() => {})
    },
    selfHandleRequest() {
      if (!this.dataForm.id) delete this.dataForm.id
      if (this.eventType === 'save') this.$emit('setLoad', true)
      const formMethod = this.dataForm.id ? updateModel : createFormModel
      formMethod(this.dataForm)
        .then((res) => {
          this.$message({
            message: res.data.msg,
            type: 'success',
            duration: 1500,
            onClose: () => {
              if (this.eventType === 'save') this.$emit('setLoad', false)
              this.$emit('close', true)
            }
          })
        })
        .catch(() => {
          if (this.eventType === 'save') this.$emit('setLoad', false)
        })
    },
    dataFormSubmit(eventType) {
      if (this.setting.isPreview) return this.$message({ message: '功能预览不支持数据保存', type: 'warning' })
      this.eventType = eventType
      this.$refs.dynamicForm && this.$refs.dynamicForm.submitForm('flow')
    }
  }
}
</script>
<style scoped lang="scss">
.flow-description {
  font-size: 15px;
  padding-left: 30px;
  padding-bottom: 20px;
}
.flow-formFlex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
