<template>
  <el-container class="container">
    <el-header class="container__header" height="48px">
      <form-navigator
        ref="FormNavigator"
        @saveValidate="saveValidate"
        @close-dialog="close"
        @local-save="localSave"
        @load-local="loadLocal"
        @switchForm="switchForm"
        :widgetForm="widgetForm"
        :form-data="formData"
        :form-id="formId"
        handleType="simple"
      />
    </el-header>
    <el-container class="container__body">
      <el-aside class="container__body--control" width="270px" v-if="asideShow">
        <field-panel
          :bo-def-ids="boDefIds"
          :widgetForm="widgetForm"
          :form-type="formType"
          :form-id="formId"
          :copyFormList="copyFormList"
          @addTocopyFormList="addTocopyFormList"
        />
      </el-aside>
      <div
        class="navbar-collapse"
        :class="{'navbar-collapse-right': !asideShow}"
        @click="asideShow = !asideShow"
      >
        <div class="navbar-collapse-bg">
          <i
            class="navbar-collapse-arrow"
            :class="{
              'el-icon-arrow-left': asideShow,
              'el-icon-arrow-right': !asideShow,
            }"
          ></i>
        </div>
      </div>
      <el-main
        class="container__body--widget form-container__body--widget"
        :class="{'widget-moblie__container': formType === 'mobile'}"
      >
        <widget-panel
          ref="widgetForm"
          :data.sync="widgetForm"
          :select.sync="widgetFormSelect"
          :selectWidgetList.sync="selectWidgetList"
          :formType="formType"
          :form-data.sync="formData"
        />
      </el-main>
      <div
        class="navbar-collapse"
        :class="{'navbar-collapse-left': rightAsideShow}"
        @click="rightAsideShow = !rightAsideShow"
      >
        <div class="navbar-collapse-bg">
          <i
            class="navbar-collapse-arrow"
            :class="{
              'el-icon-arrow-right': rightAsideShow,
              'el-icon-arrow-left': !rightAsideShow,
            }"
          ></i>
        </div>
      </div>
      <el-aside
        width="350px"
        class="container__body--property"
        v-show="rightAsideShow"
      >
        <property-panel
          @saveEnd="saveEnd"
          ref="propertyPanel"
          :data.sync="widgetFormSelect"
          :widgetForm.sync="widgetForm"
          :bo-def-data="boDefData"
          :main-bo-fields.sync="mainBoFields"
          :sub-tables="subTables"
          :form-data.sync="formData"
          :sun-tables-map="sunTablesMap"
          handleType="simple"
        />
      </el-aside>
    </el-container>
  </el-container>
</template>
<script>
  import FormNavigator from '@/components/form/FormNavigator.vue'
  import FieldPanel from '@/components/form/FieldPanel.vue'
  import WidgetPanel from '@/components/form/WidgetPanel.vue'
  import PropertyPanel from '@/components/form/PropertyPanel.vue'
  import request from '@/request.js'
  import sysType from '@/api/sysType'
  import req from '@/request'

  export default {
    props: ['visibleDialog', 'formId', 'formDefId', 'addBpmForm', 'formType', 'formAlias'],
    components: {FormNavigator, FieldPanel, WidgetPanel, PropertyPanel},
    data() {
      return {
        asideShow: true,
        rightAsideShow: true,
        widgetForm: {
          list: [],
          config: {
            labelWidth: 100,
            labelPosition: 'right',
            size: 'small',
            globalQueryJson: [],
          },
        },
        selectWidgetList: [],
        formData: this.addBpmForm,
        boDefData: null,
        widgetFormSelect: {options: {validateType: ''}},
        mainBoFields: [],
        subTables: [],
        sunTablesMap: {},
        boDefIds: '',
        copyFormList: [],
      }
    },
    watch: {
      visibleDialog: {
        handler: function (newVal) {
          if (newVal) {
            this.initData(this.formId, this.addBpmForm.bos)
          }
        },
        immediate: true,
      },
    },
    created() {
      this.initData(this.formId, this.addBpmForm.bos)
    },
    mounted() {
      this.monitor()
    },
    methods: {
      switchForm() {
        this.$emit('switchForm')
      },
      addTocopyFormList(form) {
        if (this.copyFormList.length > 0) {
          let isIn = false
          this.copyFormList.forEach((item) => {
            if (item.id == form.id) {
              isIn = true
            }
          })
          if (!isIn) {
            this.copyFormList.push(form)
          }
        } else {
          this.copyFormList.push(form)
        }
      },
      monitor() {
        let that = this
        document.onkeydown = function (e) {
          //按下删除提交
          let key = window.event.keyCode
          //事件中keycode=18为删除事件 左Alt
          if (key == 18 && e.code == 'AltRight') {
            that.handleWidgetDelete()
          }
        }
      },
      //删除表单字段控件
      deleteWidget(list) {
        for (let i = list.length - 1; i >= 0; i--) {
          if (list[i].key && !list[i].columns && !list[i].rows && !list[i].list) {
            //没使用布局字段
            if (this.selectWidgetList.indexOf(list[i].key) != -1) {
              list.splice(i, 1)
            }
          } else if (list[i].columns && list[i].columns.length > 0) {
            //栅格，tab页签，折叠面板
            for (let j = list[i].columns.length - 1; j >= 0; j--) {
              this.deleteWidget(list[i].columns[j].list)
            }
          } else if (list[i].rows && list[i].rows.length > 0) {
            //表格布局
            for (let k = list[i].rows.length - 1; k >= 0; k--) {
              if (list[i].rows[k].cols.length > 0) {
                for (let m = list[i].rows[k].cols.length - 1; m >= 0; m--) {
                  this.deleteWidget(list[i].rows[k].cols[m].list)
                }
              }
            }
          } else if (list[i].list && list[i].list.length > 0) {
            //子表，孙表
            this.deleteWidget(list[i].list)
          }
        }
      },
      handleWidgetDelete() {
        let list = this.widgetForm.list
        if (list.length > 0) {
          this.deleteWidget(list)
          this.selectWidgetList.empty()
        }
      },
      /**
       * 保存本地配置
       */
      localSave() {
        let localSaveData = {}
        localSaveData.widgetForm = this.widgetForm
        localSaveData.formData = this.formData
        localSaveData.boDefData = this.boDefData
        localSaveData.widgetFormSelect = this.widgetFormSelect
        localSaveData.mainBoFields = this.mainBoFields
        localSaveData.subTables = this.subTables
        localSaveData.sunTablesMap = this.sunTablesMap

        var jsonStr = JSON.stringify(localSaveData)
        var blob = new Blob([jsonStr], {type: 'application/json'})
        var saveAs = window.saveAs
        var name = this.formData.name || this.formData.key || '表单设计'
        saveAs(blob, name + new Date().getTime() + '.json')
      },
      /**
       * 加载本地存储
       */
      loadLocal(localSaveData) {
        const oldFormKey = this.formData.formKey
        const newFormKey = localSaveData.formData.formKey
        if (oldFormKey != newFormKey) {
          this.$message.error(
            '当前表单与本地导入的表单不是同一个表单，无法导入。'
          )
          return
        }
        const oldDefId = this.formData.defId
        const newVersion = this.formData.rev
        this.widgetForm = localSaveData.widgetForm
        this.formData = localSaveData.formData
        this.formData.rev = newVersion
        this.formData.defId = oldDefId
        this.boDefData = localSaveData.boDefData
        this.widgetFormSelect = localSaveData.widgetFormSelect
        this.mainBoFields = localSaveData.mainBoFields
        this.subTables = localSaveData.subTables
        this.sunTablesMap = localSaveData.sunTablesMap
      },
      saveEnd() {
        this.$refs.FormNavigator.saveEnd()
      },
      saveValidate() {
        this.$refs.propertyPanel.saveValidate()
      },
      close(value) {
        // value 保存表单成功时有值
        if (value) {
          this.$emit('update:formDefId', value.formData.defId)
          this.$emit('update:formId', value.formData.id)
          this.formData = value.formData
          this.formData.rev = value.rev
          this.$emit('updateForm', value.formData)
        } else {
          // 发布成功 关闭弹窗
          // this.$emit('update:visibleDialog', false)
        }
      },
      initData(formId, bos) {
        this.copyFormList = []
        if (this.formDefId) {
          request
            .get('${form}/form/formDef/v1/get?formDefId=' + this.formDefId)
            .then((response) => {
              this.widgetForm = JSON.parse(response.data.value.expand)
            })
        } else if (
          this.formData.templateConf &&
          this.formData.templateConf.boDefId
        ) {
          request
            .post(
              '${form}/form/form/v1/generateExpand',
              this.formData.templateConf
            )
            .then((response) => {
              this.widgetForm = JSON.parse(response.data.value)
            })
        }

        if (bos && bos.length > 0 && typeof(bos) !== 'string') {
          const boDefIds = bos.extractByKey('id').join(',')
          this.getBoDefData(boDefIds)
          this.widgetForm.boDefList = bos
          this.boDefIds = boDefIds

          this.setDefaultCategory()

          //获取表单别名
          let alias = this.formData.bos[0].alias
          this.formData.name = this.formData.bos[0].description
          this.formData.formKey = this.formAlias
          // this.getDefaultKey(alias).then((res) => {
          //   this.formData.formKey = res.data.value
          // })
          return
        }

        if (formId) {
          request
            .get('${form}/form/form/v1/formDesign?formId=' + formId)
            .then((response) => {
              this.formData = response.data
              this.formData.id = formId
              this.boDefIds = JSON.parse(this.formData.bos)
                .extractByKey('id')
                .join(',')
              this.getBoDefData(this.boDefIds)
            })
        }
      },
      setDefaultCategory() {
        //获取默认分类
        sysType.getSysTypeByCatId(7).then((data) => {
          for (let i = 0; i < data.length; i++) {
            if (data[i].parentId != null) {
              this.formData.typeId = data[i].id
              this.formData.typeName = data[i].name
              break
            }
          }
        })
      },
      getDefaultKey(key) {
        return req.get(
          window.context.form + '/form/form/v1/getDefaultKey?key=' + key
        )
      },
      getBoDefData(boDefId) {
        request.post('${form}/bo/def/v1/getBOTree', boDefId).then((response) => {
          this.boDefData = response.data
          this.getMainBoFields()
        })
      },
      getMainBoFields() {
        this.mainBoFields = []
        // 多个BO   一个Bo 对应一个主表
        this.boDefData.children.forEach((element) => {
          let boData = {...element}
          let boSubTables = boData.children.filter(
            (field) => field.nodeType == 'sub'
          )

          boSubTables.forEach((subTable) => {
            //收集孙实体
            const sunTables = subTable.children.filter(
              (field) => field.nodeType == 'sub'
            )
            if (sunTables && sunTables.length > 0) {
              this.sunTablesMap[subTable.name] = sunTables
            }

            let sunTable1 = {...subTable}
            sunTable1.children = subTable.children.filter(
              (field) => field.status != 'hide' && field.nodeType != 'sub'
            )
            this.subTables.push(sunTable1)
          })

          // 删除子表字段
          boData.children = boData.children.filter((field) => {
            return field.nodeType != 'sub' && field.status != 'hide'
          })

          this.mainBoFields.push(boData)
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/assets/css/element-variables.scss';

  .container {
    height: 100%;
    .container__header {
      padding: 0;
      background: $--color-white;
      z-index: 7;
    }
    .container__body {
      height: calc(100% - 80px);
    }
    .container__footer {
      background: $--background-color-secondary;
      border-top: 1px solid $--border-color-base;
    }
    .container__body--control {
      box-shadow: 2px 0 5px $--border-color-light;
    }
    .container__body--widget {
      background: $--background-color-base;
      position: relative;
      padding: 0 5px;
      margin-top: 1px;
      padding-left: 0;
      margin-left: -8px;
      margin-right: -8px;
    }
    .widget-moblie__container {
      background: #fff;
    }
    .container__body--property {
      margin-left: 3px;
      box-shadow: -2px 0 5px $--border-color-light;
      box-shadow: 0px 0px 20px #e4e7ed;
    }
    .navbar-collapse {
      margin-top: 40px;
      width: 10px;
      z-index: 999;
    }
    .navbar-collapse-bg {
      margin-left: 1px;
      height: 28px;
      border-top: 8px solid transparent;
      border-bottom: 8px solid transparent;
      border-left: 10px solid #fff;
      border-right: none;
      position: relative;
    }
    .navbar-collapse-left {
      .navbar-collapse-bg {
        margin-right: 1px;
        border-top: 8px solid transparent;
        border-bottom: 8px solid transparent;
        border-right: 10px solid #fff;
        border-left: none;
        .navbar-collapse-arrow {
          left: 0;
        }
      }
    }
    .navbar-collapse-bg:hover {
      cursor: pointer;
    }
    .navbar-collapse-arrow {
      position: absolute;
      left: -12px;
      top: 7px;
    }
  }
</style>
