<script>
import { deepClone, detail, loopRelationList, numberChinese } from '@/utils'
import render from '@/components/Generator/render/render.js'
import { dyOptionsList } from '@/components/Generator/generator/comConfig'
import { dictDetail } from '@/api/newbi/dict'
import RelationForm from '@/components/Generator/components/RelationForm'
import moment from 'moment/moment'
import { getAPIData, getdefaultAPIData } from '@/components/Dataset-filter/util'
import { getConfigData } from '@/api/onlineDev/visualDev'

const components = {
  itemBtns(element) {
    return [
      this.detailType !== 'detail' && element.relationData && element.relationData.itemRelationTable && element.relationData.RelationTableCubeId && (
        <span
          class="relationItem"
          style=""
          title="选择关联数据"
          onClick={(event) => {
            this.relationBoxclick(element)
          }}
        >
          <i class="el-icon-search" />
        </span>
      )
    ]
  },
  formItem(scheme, config, labelWidth, listeners) {
    return [
      scheme.__vModel__ !== this.idKey && !scheme.displayNone && (
        <el-col span={config.span === 24 && !config.typeSpan ? this.formConf.span : config.span}>
          <el-form-item label-width={labelWidth} prop={String(scheme.__vModel__)} key={scheme.__vModel__} label={config.showLabel ? config.label : ''}>
            <render
              formData={this[this.formConf.formModel]}
              detailType={this.detailType}
              primaryRow={this.primaryRowObj}
              model-id={this.modelId}
              conf={scheme}
              {...{ on: listeners }}
              ref={config.rowType === 'table' ? scheme.__vModel__ : undefined}
            />
            {components.itemBtns.call(this, scheme)}
          </el-form-item>
        </el-col>
      )
    ]
  },
  relationFormItem(scheme, config, labelWidth, listeners) {
    return [
      scheme.__vModel__ !== this.idKey && !scheme.displayNone && (
        <el-col span={config.span}>
          <el-form-item label-width={labelWidth} prop={String(scheme.__vModel__)} key={scheme.__vModel__} label={config.showLabel ? config.label : ''}>
            <el-button
              type="text"
              onClick={(event) => {
                this.relationDetail(h, scheme)
              }}
            >
              {this[this.formConf.formModel][scheme.__vModel__]}
            </el-button>
          </el-form-item>
        </el-col>
      )
    ]
  }
}
function getLogic(h, Ellogic) {
  const { formConfCopy } = this
  //op:绑定组件__vModel__ setType:1选中 2未选中 deVal：符合的值
  const { op, setType, deVal } = Ellogic.__logic__
  const eleList = []
  let deValList = []
  function f(fields) {
    fields.forEach((i) => {
      if (i.__config__.children && i.__config__.children.length) {
        f(i.__config__.children)
      } else {
        if (Number(i.__vModel__) === op) {
          eleList.push(i)
        }
      }
    })
  }
  f(formConfCopy.fields)
  let el = eleList[0]
  if (!Array.isArray(deVal)) {
    deValList = [deVal]
  } else {
    deValList = deVal
  }
  return setType === 1 ? deValList.includes(el.__config__.defaultValue) : !deValList.includes(el.__config__.defaultValue)
}

const layouts = {
  colFormItem(h, scheme) {
    const config = scheme.__config__
    const listeners = buildListeners.call(this, scheme, h)
    let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null
    if (config.showLabel === false) labelWidth = '0'
    //是否带有逻辑判断
    if (scheme.__logic__ && scheme.__logic__.op) {
      //验证条件通行
      if (getLogic.call(this, h, scheme)) {
        // 关联字段为链接按钮
        if (this.detailType === 'detail' && this.associationRelation.find((o) => o.visualdevTableColumnId == scheme.__vModel__ && o.plaintext === 0)) {
          return components.relationFormItem.call(this, scheme, config, labelWidth, listeners)
        } else {
          return components.formItem.call(this, scheme, config, labelWidth, listeners)
        }
      }
    } else {
      if (this.detailType === 'detail' && this.associationRelation.find((o) => o.visualdevTableColumnId == scheme.__vModel__ && o.plaintext === 0)) {
        return components.relationFormItem.call(this, scheme, config, labelWidth, listeners)
      } else {
        return components.formItem.call(this, scheme, config, labelWidth, listeners)
      }
    }
  },

  rowFormItem(h, scheme) {
    if (scheme.__config__.jnpfKey === 'tab') {
      return (
        <el-col span={scheme.__config__.span} class="mb-10">
          <el-tabs type={scheme.type} tab-position={scheme['tab-position']} vModel={scheme.__config__.active}>
            {scheme.__config__.children.map((item, i) => {
              let child = renderChildren.call(this, h, item)
              return (
                <el-tab-pane key={item.name} label={item.title}>
                  <el-row>{child}</el-row>
                </el-tab-pane>
              )
            })}
          </el-tabs>
        </el-col>
      )
    }
    if (scheme.__config__.jnpfKey === 'collapse') {
      return (
        <el-col span={scheme.__config__.span} class="mb-20">
          <el-collapse vModel={scheme.__config__.active} accordion={scheme.accordion}>
            {scheme.__config__.children.map((item, i) => {
              let child = renderChildren.call(this, h, item)
              return (
                <el-collapse-item key={item.name} title={item.title} name={item.name}>
                  <el-row>{child}</el-row>
                </el-collapse-item>
              )
            })}
          </el-collapse>
        </el-col>
      )
    }
    let child = renderChildren.apply(this, arguments)
    if (scheme.__config__.jnpfKey === 'table') {
      if (!scheme.__config__.noShow) this.tableRefs[scheme.__vModel__] = scheme
      const param = { ...scheme, config: scheme }
      return layouts.colFormItem.call(this, h, param)
    }
    if (scheme.__config__.jnpfKey === 'card') {
      return (
        <el-col span={scheme.__config__.span} class="item-card">
          <el-card shadow={scheme.shadow} header={scheme.header} class="mb-20">
            {child}
          </el-card>
        </el-col>
      )
    }
    if (scheme.__config__.jnpfKey === 'row') {
      if (scheme.type === 'flex') {
        child = (
          <el-row type={scheme.type} justify={scheme.justify} align={scheme.align}>
            {child}
          </el-row>
        )
      }
      return (
        <el-col span={scheme.__config__.span}>
          <el-row gutter={scheme.gutter}>{child}</el-row>
        </el-col>
      )
    }
  }
}

function renderFrom(h) {
  const { formConfCopy } = this
  //当页面为独立全屏添加页面时
  if (formConfCopy.popupType === 'fullScreen') {
    return (
      <el-row type="flex" justify="center" align="middle" class={formConfCopy.formStyle}>
        <el-col xs={12} sm={12} md={12} lg={12} xl={10}>
          <el-form
            size={formConfCopy.size}
            label-position={formConfCopy.labelPosition}
            disabled={formConfCopy.disabled}
            label-width={`${formConfCopy.labelWidth}px`}
            ref={formConfCopy.formRef}
            // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
            props={{ model: this[formConfCopy.formModel] }}
            rules={this[formConfCopy.formRules]}
          >
            {renderFormItem.call(this, h, formConfCopy.fields)}
            {formConfCopy.formBtns && formBtns.call(this, h)}
          </el-form>
          {RelationDom.call(this, h)}
        </el-col>
      </el-row>
    )
  } else if (formConfCopy.popupType === 'topEntry') {
    return (
      <el-row type="flex" class="topEntryBox">
        <el-form
          inline={true}
          size={formConfCopy.size}
          label-position={formConfCopy.labelPosition}
          disabled={formConfCopy.disabled}
          label-width={`${formConfCopy.labelWidth}px`}
          ref={formConfCopy.formRef}
          // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
          props={{ model: this[formConfCopy.formModel] }}
          rules={this[formConfCopy.formRules]}
        >
          {renderFormItem.call(this, h, formConfCopy.fields)}
          {formConfCopy.formBtns && formBtns.call(this, h)}
        </el-form>
      </el-row>
    )
  } else {
    return (
      <el-form
        size={formConfCopy.size}
        label-position={formConfCopy.labelPosition}
        disabled={formConfCopy.disabled}
        label-width={formConfCopy.labelWidth === 'auto' ? formConfCopy.labelWidth : `${formConfCopy.labelWidth}px`}
        ref={formConfCopy.formRef}
        // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
        props={{ model: this[formConfCopy.formModel] }}
        rules={this[formConfCopy.formRules]}
      >
        <el-row gutter={formConfCopy.gutter} class={formConfCopy.formStyle} type="flex" style="flex-wrap:wrap">
          {renderFormItem.call(this, h, formConfCopy.fields)}
          {formConfCopy.formBtns && formBtns.call(this, h)}
          {RelationDom.call(this, h)}
        </el-row>
      </el-form>
    )
  }
}
function RelationDom(h) {
  const { relationConf } = this
  return <relation-form class="relationBox" relation-conf={relationConf} onChangeRow={this.changeElRowClick} ref="relationBox"></relation-form>
}
function formBtns(h) {
  return (
    <el-col>
      <el-form-item size="large">
        <el-button type="primary" onClick={this.submitForm}>
          提交
        </el-button>
        <el-button onClick={this.resetForm}>重置</el-button>
      </el-form-item>
    </el-col>
  )
}

function renderFormItem(h, elementList) {
  const { detailType } = this
  return elementList.map((scheme) => {
    const config = scheme.__config__
    const layout = layouts[config.layout]
    if (layout) {
      scheme.__vModel__ = String(scheme.__vModel__)
      if (detailType === 'detail') scheme.disabled = true
      return layout.call(this, h, scheme)
    }
    throw new Error(`没有与${config.layout}匹配的layout`)
  })
}

function renderChildren(h, scheme) {
  const config = scheme.__config__
  if (!Array.isArray(config.children)) return null
  return renderFormItem.call(this, h, config.children)
}

function setValue(event, config, scheme) {
  const { formConfCopy, formConf } = this
  // if (config && Array.isArray(config.defaultValue)) {
  //   this.$set(config, 'defaultValue', [event])
  //   this.$set(this[this.formConf.formModel], scheme.__vModel__, [event])
  // } else {
  this.$set(config, 'defaultValue', event)
  this.$set(this[this.formConf.formModel], scheme.__vModel__, event)
  // }
  if (scheme.relationValuePrimaryId) this.$set(scheme, 'relationValuePrimaryId', '')
  let mapList = loopRelationList(formConfCopy.fields)
  mapList.forEach((i, k) => {
    //当当前组件值change时 查询当前组件是否有api变量
    if (scheme.__config__.ApiReturn && scheme.__config__.ApiReturn.length) {
      // 主要是为了查询 当前change的组件下的API变量是否有组件使用 api变量传参使用
      if (i.__config__ && i.__config__.ApiParams && i.__config__.ApiParams.length) {
        let itemConfig = i.__config__
        const isVarTypeExist = checkApiVarTypeExist(itemConfig.ApiParams, scheme.__config__.ApiReturn)
        if (!isVarTypeExist) return
        if (!itemConfig.propsUrl) return
        setOptions.call(this, i, itemConfig, formConfCopy)
      }
      // 当当前组件有api变量要给其他组件赋值 查询哪个组件绑定了变量
      let isTreeSelect = config.jnpfKey === 'treeSelect' || config.jnpfKey === 'cascader'
      if (i.defaultVarType && i.defaultVarType.length) {
        // this.$set(i.__config__,'defaultValue',undefined)
        // this.$set(this[this.formConf.formModel], i.__vModel__, undefined)
        let cascaderData
        isTreeSelect ? (cascaderData = event) : (cascaderData = null)
        getdefaultAPIData(i, mapList, '', scheme, cascaderData).then((res) => {
          this.$set(i.__config__, 'defaultValue', res)
          this.$set(this[this.formConf.formModel], i.__vModel__, res)
        })
      } else {
        // 只创建了API变量并未给组件赋值时 可能在自定义表达式中使用 兼容处理
        let itemOptions
        isTreeSelect ? (itemOptions = scheme.options) : (itemOptions = scheme.__slot__.options)
        let selectRow = itemOptions.find((o) => o[scheme.__config__.apiProps.value] === event)
        if (selectRow) {
          for (const cur of scheme.__config__.ApiReturn) {
            // 储存全局变量
            sessionStorage.setItem(`API_${cur.varName}`, selectRow[cur.keyName])
          }
        }
      }
      this.apiVariableSetItem('API_VARIABLE_CHANGE', JSON.stringify(+new Date()))
    }
    if (scheme.allVar) {
      sessionStorage.setItem(`FORM_${scheme.__vModel__}`, event)
      this.apiVariableSetItem('API_VARIABLE_CHANGE', JSON.stringify(+new Date()))
    }
    // 查询当前组件是否有表单变量
    if (scheme.allVar && i.__config__ && i.__config__.ApiParams && i.__config__.ApiParams.length) {
      let itemConfig = i.__config__
      const isVarTypeExist = checkVarTypeExist(itemConfig.ApiParams, scheme.__vModel__)
      if (!isVarTypeExist) return
      if (!itemConfig.propsUrl) return
      setOptions.call(this, i, itemConfig, formConfCopy)
    }
  })
}
function setOptions(i, itemConfig, formConfCopy) {
  let isTreeSelect = itemConfig.jnpfKey === 'treeSelect' || itemConfig.jnpfKey === 'cascader'
  if (isTreeSelect) {
    getAPIData(i, itemConfig.propsUrl, itemConfig.ApiParams, formConfCopy.fields, '', itemConfig.apiProps).then((res) => {
      try {
        res = res.filter((o) => o[itemConfig.apiProps.idKey] || o[itemConfig.apiProps.pidKey])
        let treeData = g.T.toTree(res, i.props.props.children, itemConfig.apiProps.idKey, itemConfig.apiProps.pidKey)
        this.$set(i, 'options', treeData)
      } catch {}
    })
  } else {
    getAPIData(i.__slot__, itemConfig.propsUrl, itemConfig.ApiParams, formConfCopy.fields, '', itemConfig.apiProps).then((res) => {
      this.$set(i.__slot__, 'options', res)
    })
  }
}
// 查API变量
function checkApiVarTypeExist(arr, target) {
  for (let obj of arr) {
    for (let cur of target) {
      if (obj.varType && obj.varType.includes(cur.varName)) {
        return true
      }
    }
  }
  return false
}
// 查表单变量
function checkVarTypeExist(arr, target) {
  for (let obj of arr) {
    if (obj.varType && obj.varType.includes(Number(target))) {
      return true
    }
  }
  return false
}
function buildListeners(scheme, h) {
  const { formConfCopy } = this
  const config = scheme.__config__
  const methods = this.formConf.__methods__ || {}
  const listeners = {}
  // 给__methods__中的方法绑定this和event
  Object.keys(methods).forEach((key) => {
    listeners[key] = (event) => methods[key].call(this, event)
  })
  // 响应 render.js 中的 vModel $emit('input', val)
  listeners.input = (event) => setValue.call(this, event, config, scheme)
  listeners.change = (event) => {
    renderFormItem.call(this, h, formConfCopy.fields)
  }

  //当存在自定义表达式时
  if (scheme.defaultValueExp) {
    let str = scheme.defaultValueExp
    //将当前表达式中的变量提取
    let regs = /\[(.*?)]/gi
    const matches = []
    let match
    while ((match = regs.exec(str)) !== null) {
      matches.push(match[1])
    }
    let matcheList = matches.filter((l) => l !== undefined)
    //将当前表达式中的括号转义
    let executeStr = str.replace(/\[/g, '@').replace(/\]/g, '@')
    // setValue.call(this, eval(executeStr), config, scheme)
    window.numberChinese = numberChinese
    if (matcheList && matcheList.length) {
      XEUtils.objectEach(matcheList, (item, key) => {
        let reg = '/@' + item + '@/g'
        if (getConfigDefVal.call(this, h, item)[0]) {
          let aa = JSON.stringify(getConfigDefVal.call(this, h, item)[0])
          if (item && item.indexOf('$') > -1) reg = reg.replace(/\$/g, '')
          if (executeStr && executeStr.indexOf('$') > -1) executeStr = executeStr.replace(/\$/g, '')
          executeStr = g.replaceAll(executeStr, eval(reg), aa, true)
          try {
            setValue.call(this, eval(executeStr), config, scheme)
          } catch {}
        }
      })
    } else {
      try {
        setValue.call(this, eval(executeStr), config, scheme)
      } catch {}
    }
  }
  return listeners
}

function getConfigDefVal(h, item) {
  const { formConfCopy } = this
  // 系统变量
  if (item && item.indexOf('systemGlobal_') > -1) {
    let systemItem = item.replace('systemGlobal_', '')
    if (!systemItem) return []
    const systemUserInfo = localStorage.getItem('lowcodeUserInfo')
    if (!systemUserInfo) return []
    return new Array(JSON.parse(systemUserInfo)[systemItem])
  } else if (item && item.indexOf('.') > -1) {
    // 子表单变量
    // 分割变量 arr[0]为子表单 arr[1]为子表单中的字段
    let itemArr = item.split('.')
    // 找到子表单对应的数据
    let list = itemArr && itemArr[0] && formConfCopy.fields.find((o) => o.__config__.tableName === itemArr[0])
    if (!list) return []
    // 查询对应子表单的具体信息 获取vmodel
    let itemObj = list.__config__.children.find((o) => o.__vModelName__ === itemArr[1])
    if (!itemObj) return []
    if (!this.$refs[String(list.__vModel__)]) return []
    // 通过vmodel找到对应的子表单组件填写数据
    let itemData = this.$refs[String(list.__vModel__)].$children[0].faceSubmit()
    const values = itemData.map((item) => Number(item[itemObj.__vModel__])).filter((value) => value)
    return [values] || []
    // const sum = itemData.reduce((acc, curr) => acc + parseInt(curr[itemObj.__vModel__]), 0);
    // return [Number.isNaN(sum) ? 0 : sum]
  } else if (item && item.indexOf('$') > -1) {
    // API变量
    let APIItem = item.replace(/\$/g, '')
    return new Array(sessionStorage.getItem(`API_${APIItem}`))
  } else {
    return formConfCopy.fields
      .map((i, k) => {
        if (i.__vModelName__ === item && i.__config__.defaultValue) return i.__config__.defaultValue
      })
      .filter((l) => l !== undefined)
  }
}
export default {
  components: {
    render,
    RelationForm
  },
  props: {
    formConf: {
      type: Object,
      required: true
    },
    primaryRowObj: {
      type: Object,
      default: () => {}
    },
    relationConf: {
      type: Array
    },
    detailType: {
      type: String,
      default: ''
    },
    idKey: {
      type: Number
      // required:true
    },
    associationRelation: {
      type: Array,
      default: () => []
    },
    modelId: {
      type: String,
      default: ''
    }
  },
  data() {
    const data = {
      formConfCopy: deepClone(this.formConf),
      relationConfCopy: deepClone(this.relationConf),
      [this.formConf.formModel]: {},
      [this.formConf.formRules]: {},
      options: {},
      tableRefs: {}
    }
    this.formRelationFlag(data.formConfCopy.fields, data.relationConfCopy)
    this.initFormData(data.formConfCopy.fields, data[this.formConf.formModel], this.detailType)
    this.buildRules(data.formConfCopy.fields, data[this.formConf.formRules])
    this.buildOptions(data.formConfCopy.fields, data.options)
    return data
  },
  methods: {
    formRelationFlag(componentList, relationBoxList) {
      componentList.forEach((cur) => {
        let str = relationBoxList
          .map((item) => item.relationList)
          .flat()
          .find((item) => item.drawId === cur.__vModel__)
        cur.relationFlag = !!(str && str.drawId === cur.__vModel__)
      })
    },
    initFormData(componentList, formData, detailType) {
      this.$store.commit('generator/UPDATE_RELATION_DATA', {})
      componentList.forEach((cur) => {
        if (detailType === 'detail') {
          cur.disabled = true
        } else {
          if (cur.__config__.isJoin) cur.displayNone = true
        }
        const config = cur.__config__
        if (cur.__vModel__) formData[cur.__vModel__] = config.defaultValue
        if (cur.__config__.jnpfKey === 'date') {
          //默认当前时间
          if (cur.defaultDay) {
            //添加默认时间 当前没有值是添加数据
            if (!formData[cur.__vModel__] && !config.defaultValue) {
              let dfDay = moment().valueOf()
              formData[cur.__vModel__] = dfDay
              config.defaultValue = dfDay
            } else {
              //允许编辑时更新 重新赋值
              if (cur.editChange) {
                let dfDay = moment().valueOf()
                formData[cur.__vModel__] = dfDay
                config.defaultValue = dfDay
              }
            }
          }
        }
        if (cur.__config__.jnpfKey === 'table') return
        if (config.children) this.initFormData(config.children, formData)
      })
    },
    buildOptions(componentList, data) {
      sessionStorage.clear()
      componentList.forEach((cur) => {
        const config = cur.__config__
        if (dyOptionsList.indexOf(config.jnpfKey) > -1) {
          let isTreeSelect = config.jnpfKey === 'treeSelect' || config.jnpfKey === 'cascader'
          if (config.dataType === 'dictionary') {
            if (!config.dictionaryType) return
            dictDetail({ id: config.dictionaryType }).then((res) => {
              let content = JSON.parse(res.data.data.content || '[]')
              isTreeSelect ? (cur.options = content.map((i) => ({ fullName: i.value, id: i.key }))) : (cur.__slot__.options = content.map((i) => ({ fullName: i.value, id: i.key })))
            })
          }
          //当下拉组件使用api接口时
          if (config.dataType === 'dynamic') {
            let isTreeSelect = config.jnpfKey === 'treeSelect' || config.jnpfKey === 'cascader'
            // if(!config.ApiParams.length) return
            if (!config.propsUrl) return
            if (isTreeSelect) {
              getAPIData(cur, config.propsUrl, config.ApiParams, componentList, '', config.apiProps).then((res) => {
                // this.$set(scheme,'options',res)
                try {
                  res = res.filter((i) => i[cur.__config__.apiProps.idKey] || i[cur.__config__.apiProps.pidKey])
                  let treeData = g.T.toTree(res, cur.props.props.children, cur.__config__.apiProps.idKey, cur.__config__.apiProps.pidKey)
                  this.$set(cur, 'options', treeData)
                } catch {}
              })
            } else {
              getAPIData(cur.__slot__, config.propsUrl, config.ApiParams, componentList, '', config.apiProps).then((res) => {
                this.$set(cur.__slot__, 'options', res)
              })
            }
          }
          // if (config.dataType === 'dynamic') {
          //   if (!config.propsUrl) return
          //   isTreeSelect ? cur.options = getAPIData(cur,config.propsUrl,config.formAllVar,componentList) : cur.__slot__.options = getAPIData(cur.__slot__,config.propsUrl,config.formAllVar,componentList)
          // }
        }
        if (config.children && config.jnpfKey !== 'table') this.buildOptions(config.children, data)
      })
    },
    buildRules(componentList, rules) {
      componentList.forEach((cur) => {
        const config = cur.__config__
        if (Array.isArray(config.regList)) {
          if (config.required) {
            const required = { required: config.required, message: cur.placeholder }
            if (Array.isArray(config.defaultValue)) {
              required.type = 'array'
              required.message = `请至少选择一个${config.label}`
            }
            required.message === undefined && (required.message = `${config.label}不能为空`)
            config.regList.push(required)
          }
          rules[cur.__vModel__] = config.regList.map((item) => {
            item.pattern && (item.pattern = eval(item.pattern))
            item.trigger = config.trigger || 'blur'
            return item
          })
        }
        if (config.children) this.buildRules(config.children, rules)
      })
    },
    relationBoxclick(element, index, parent) {
      this.$refs.relationBox.getData(element.relationData)
      // this.relationConfCopy = deepClone(this.relationConf)
      // this.relationConfCopy.forEach((i,k)=>{
      //   i.relationList.forEach((v,x)=>{
      //     if (v.drawId === element.__vModel__){
      //       this.$refs.relationBox.getData(i.relationName,i.fieldName,i.fieldList)
      //     }
      //   })
      // })
    },
    async relationDetail(h, scheme) {
      if (!scheme.relationData.itemRelationTable) return
      this.$emit('relationModalLodig', true)
      // 获取当前表单的信息
      const rowRes = await getConfigData(this.modelId)
      const rowData = rowRes.data.data
      // 获取当前表格信息
      const rowDetailData = await detail(this.modelId, rowData.dbLinkId)
      function isEmptyObject(obj) {
        return Object.keys(obj).length === 0
      }
      const rowColumnDict = rowDetailData.columnDict
      const field = rowColumnDict[scheme.__vModel__]
      const rowAssociationData = JSON.parse(localStorage.getItem('BROWSER_associationData')) || {}
      const rowAssociationColumnDict = JSON.parse(localStorage.getItem('BROWSER_associationColumnDict')) || {}
      // 获取下一个被点击的关联表单信息
      const res = await getConfigData(scheme.relationData.itemRelationTable)
      const data = res.data.data
      let params = {
        fullName: data.fullName,
        formData: JSON.parse(data.formData),
        associationRelation: data.associationRelation,
        modelId: scheme.relationData.itemRelationTable,
        idKey: data.idKey,
        columnDict: rowAssociationColumnDict[field],
        columnList: JSON.parse(data.columnData).columnList,
        dbLinkId: data.dbLinkId,
        row: rowAssociationData[field][scheme.relationValuePrimaryId],
        id: 0
      }
      const detailData = await detail(params.modelId, params.dbLinkId, params.idKey, params.row[rowAssociationColumnDict[field][params.idKey]])
      if (isEmptyObject(detailData.data)) {
        this.$emit('relationModalLodig', false)
        this.$message({ message: '未查询到关联数据', type: 'warning' })
        return
      }
      if (detailData.data) {
        let relationMapList = loopRelationList(params.formData.fields)
        const columnList = params.columnList.map((v) => {
          if (relationMapList.find((i) => i.__vModel__ === v.propId)) {
            return {
              ...v,
              ...{
                params: {
                  compoentConfig: relationMapList.find((i) => i.__vModel__ === v.propId),
                  ...v,
                  field: detailData.columnDict[v.propId]
                }
              }
            }
          }
        })
        Object.keys(detailData.data).forEach((key) => {
          const cellValue = detailData.data[key]
          const field = key
          const column = columnList.filter((i) => i.params).find((i) => i.params.field === field)
          if (column && column.params && column.params.compoentConfig.relationData && column.params.compoentConfig.relationData.showTitle.length) {
            const fieldArray = []
            if (cellValue) {
              let associationSeparator = column.params.compoentConfig.relationData.associationSeparator || ';'
              cellValue.split(associationSeparator).forEach((i, index) => {
                if (column.params.compoentConfig.relationData.isCheck) {
                  try {
                    const data = detailData.associationData[field][detailData.data[field]]
                    const primaryId = column.params.compoentConfig.relationData.itemRelationList.find((i) => i.drawId === column.params.propId)
                    const relationField = detailData.associationColumnDict[field][primaryId.columnId]
                    fieldArray.push(data ? data[relationField] : i)
                  } catch (e) {
                    fieldArray.push(detailData.data[field])
                  }
                } else {
                  // 逗号隔开
                  try {
                    const data = detailData.associationData[field][i]
                    const primaryId = column.params.compoentConfig.relationData.itemRelationList.find((i) => i.drawId === column.params.propId)
                    const relationField = detailData.associationColumnDict[field][primaryId.columnId]
                    fieldArray.push(data[relationField] ? data[relationField] : i)
                  } catch (e) {
                    fieldArray.push(detailData.data[field])
                  }
                }
              })
              params.row[field + '_TEXT'] = fieldArray.join(',')
            }
          }
        })
      }
      params.id = params.row[params.columnDict[params.idKey]]
      this.$emit(
        'relationModal',
        params.formData,
        params.modelId,
        params.id,
        false,
        params.row,
        params.idKey,
        params.columnDict,
        params.dbLinkId,
        'detail',
        params.associationRelation,
        params.fullName
      )
    },
    changeElRowClick(row) {
      let { id, relationConfObj, jsonData } = row
      let list = loopRelationList(this.formConfCopy.fields)
      relationConfObj.itemRelationList.forEach((i, k) => {
        list.forEach((c, b) => {
          if (i.columnId && i.drawId && i.drawId == c.__vModel__) {
            if (jsonData) {
              // 数据为多行时 存储数据为数组 多列为单条数据 用户看到的数据要跟提交数据进行区分
              if (Array.isArray(jsonData) && jsonData.length) {
                let value = jsonData
                  .map((o) => {
                    return o[i.columnId]
                  })
                  .filter((l) => l !== undefined)
                let valueSeparator = c.relationData.associationSeparator ? value.join(c.relationData.associationSeparator) : value.join(';')
                setValue.call(this, valueSeparator, c.__config__, c)
                if (i.plaintext === 0) this.$set(c, 'relationValuePrimaryId', id)
              } else {
                let value = jsonData[i.columnId]
                let a
                if (c.__config__.defaultValue) {
                  a = [c.__config__.defaultValue, value].join('-')
                } else {
                  a = value
                }
                setValue.call(this, a, c.__config__, c)
                if (i.plaintext === 0) this.$set(c, 'relationValuePrimaryId', id)
              }
            }
            // setValue.call(this,id,c.__config__,c)
          }
        })
      })
      this.formRelationFlag(this.formConfCopy.fields, this.relationConfCopy)
      this.$refs.relationBox.visible = false
    },
    resetForm() {
      this.$store.commit('generator/UPDATE_RELATION_DATA', {})
      this.formConfCopy = deepClone(this.formConf)
      this.$refs[this.formConf.formRef].resetFields()
      Object.keys(this.tableRefs).forEach((vModel) => {
        this.$refs[vModel].$children[0].resetTable()
      })
    },
    checkTableData() {
      let valid = true
      Object.keys(this.tableRefs).forEach((vModel) => {
        const res = this.$refs[vModel].$children[0].submit() // 返回false或表单数据
        res ? (this[this.formConf.formModel][vModel] = res) : (valid = false)
      })
      return valid
    },
    submitForm() {
      const isTableValid = this.checkTableData()
      this.$refs[this.formConf.formRef].validate((valid) => {
        if (!valid) return false
        if (!isTableValid) return false
        // 触发sumit事件
        let list = loopRelationList(this.formConfCopy.fields)
        // 查询要提交的数据中 是否有关联数据的主键id 如果有的话 要进行替换 关联数据只提交关联数据的主键id
        Object.keys(this[this.formConf.formModel]).forEach((key) => {
          let row = list.find((obj) => obj.__vModel__ == key && obj.relationValuePrimaryId)
          if (row) this[this.formConf.formModel][key] = row.relationValuePrimaryId
          // 级联选择器在开启多选时返回的是数组 需要转换成字符串
          if (list.find((obj) => obj.__vModel__ == key && obj.props && obj.props.props.multiple && obj.__config__.jnpfKey === 'cascader') && Array.isArray(this[this.formConf.formModel][key])) {
            this[this.formConf.formModel][key] = list.find((obj) => obj.__vModel__ == key).props.props.separator
              ? this[this.formConf.formModel][key].join(list.find((obj) => obj.__vModel__ == key).props.props.separator)
              : this[this.formConf.formModel][key].join(';')
          }
        })
        this.$emit('submit', this[this.formConf.formModel])
        return true
      })
    }
  },
  render(h) {
    return renderFrom.call(this, h)
  }
}
</script>
<style lang="scss">
.relationItem {
  cursor: pointer;
  background: #0d84ff;
  padding: 0 10px;
  position: absolute;
  right: 0;
  top: 0;
  i {
    color: #ffffff;
  }
}
.topEntryBox {
  display: flex !important; //设置布局
  flex-wrap: wrap !important; //进行换行操作
  .el-form-item--small .el-form-item__content {
    line-height: 35px !important;
  }
}
@media (max-width: 768px) {
  .relationItem {
    margin-right: 0;
  }
}
</style>
