<template>
  <div :class="{'custom-form-form-edit-view': true, 'preview': preview, 'editing': !preview}">
    <!--组件列表 start-->
    <div class="custom-form-widget-view">
      <div class="custom-form-edit-view-head">
        <h4 class="custom-form-form-name">组件列表</h4>
      </div>
      <div class="custom-form-widget-view-body" ref="widgets">
        <div class="custom-form-widget pw-zform-item" v-for="widget in widgets" :key="widget.name">
          <div>
            <img :src="widget.image"/>
          </div>
        </div>
      </div>
    </div>
    <!--组件列表 end-->

    <!--内容视图 start-->
    <div class="custom-form-form-view">
      <div class="custom-form-form-view-head" v-if="templateZcms">
        <el-button plain round size="mini" type="primary" class="go-back" @click="$router.push('/plugins/customForm')">
          <i class="fa fa-fw fa-chevron-left"></i>返回列表
        </el-button>
        <el-button type="text" @click="onPreview">
          <i :class="'fa fa-fw ' + (preview?'fa-edit':'fa-eye')"></i>{{preview?'编辑':'预览'}}
        </el-button>
        <el-button type="text" @click="onSaveToTemplate" v-if="!preview && templateZcms.templateFlag === 'N'">
          <i class="fa fa-fw fa-copy"></i>存为模板
        </el-button>
        <el-button type="text" @click="onSave" v-if="!preview">
          <i class="fa fa-fw fa-save"></i>保存
        </el-button>
        <el-button type="text" @click="publish" v-if="!preview && templateZcms.templateFlag === 'N'">
          <i class="fa fa-fw fa-paper-plane"></i>发布
        </el-button>
      </div>
      <div class="custom-form-form-view-body" tabindex="-1" ref="form-box" v-if="templateZcms"
           @keydown.delete.stop.prevent="onKeyDown('delete')"
           @keydown.up.stop.prevent="onKeyDown('up')"
           @keydown.down.stop.prevent="onKeyDown('down')"></div>
    </div>
    <!--内容视图 end-->

    <!--属性编辑区域 start-->
    <div class="custom-form-edit-view">
      <div class="custom-form-edit-view-head">
        <h4 class="custom-form-form-name">属性编辑</h4>
        <el-button type="text" :disabled="editingIndex < 0" @click="onAddControl">
          <i class="fa fa-fw fa-plus"></i>添加控件
        </el-button>
      </div>
      <div class="custom-form-edit-view-body">
        <el-form v-if="params && params.form && zfData && editingIndex < 0" label-width="8em">
          <el-form-item v-for="item in params.form" :key="item.name" :label="item.label + ':'">
            <el-input v-if="item.type === 'text'" :disabled="!item.editable" v-model="zfData[item.name]"></el-input>
            <el-row v-else-if="item.type === 'layout'">
              <el-col :span="20">
                <el-slider :min="1" :max="23" show-stops :disabled="!item.editable"
                           @input="layoutChange($event ,zfData, item.name)"
                           :value="zfData[item.name]?parseInt(zfData[item.name].label):8">
                </el-slider>
              </el-col>
              <el-col :span="4" style="text-align: right;">
                <el-tooltip class="item" effect="dark" content="同步所有表单项标签宽度" placement="left">
                  <el-button @click="resetLayout" icon="refresh" size="mini" type="primary"></el-button>
                </el-tooltip>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <el-collapse :value="collapseValue" v-if="editingIndex > -1">
          <el-collapse-item name="item" title="表单项属性">
            <el-form label-width="8em" v-if="editingIndex > -1">
              <el-form-item v-for="item in params.item" v-if="item.type !== 'controls'" :key="item.name" :label="item.label + ':'">
                <el-input clearable
                          v-if="item.type === 'text'"
                          :disabled="!item.editable"
                          v-model="zfData.fields[editingIndex][item.name]"></el-input>

                <el-switch v-else-if="item.type === 'boolean'"
                           :disabled="!item.editable"
                           :active-value="item.name"
                           :inactive-value="''"
                           v-model="zfData.fields[editingIndex][item.name]"></el-switch>

                <el-input-number v-else-if="item.type === 'number'"
                                 :min="item.min ? parseInt(item.min) : -Infinity"
                                 :max="item.max ? parseInt(item.max) : Infinity"
                                 :disabled="!item.editable"
                                 v-model="zfData.fields[editingIndex][item.name]"></el-input-number>

                <el-slider v-else-if="item.type === 'layout'"
                           :min="1"
                           :max="23"
                           show-stops
                           :disabled="!item.editable"
                           @input="layoutChange($event ,zfData.fields[editingIndex], item.name)"
                           :value="zfData.fields[editingIndex][item.name]?parseInt(zfData.fields[editingIndex][item.name].label):8"></el-slider>
              </el-form-item>
            </el-form>
          </el-collapse-item>

          <el-collapse-item :name="index" v-for="(item, index) in zfData.fields[editingIndex].controls" :key="item.type+'-'+index">
            <div class="custom-form-control-item" slot="title">
              <h5 class="custom-form-control-item-title">{{params[item.type].name}}</h5>
              <i @click.stop="onRemoveControl(index)" class="custom-form-control-item-action rm fa fa-fw fa-remove"></i>
              <i @click.stop="onDwControl(index === zfData.fields[editingIndex].controls.length-1 ,index)"
                 :class="{'custom-form-control-item-action dw fa fa-fw fa-arrow-down': true, 'disabled': index === zfData.fields[editingIndex].controls.length-1}"></i>
              <i @click.stop="onUpControl(index === 0, index)" :class="{'custom-form-control-item-action up fa fa-fw fa-arrow-up': true, 'disabled': index === 0}"></i>
            </div>
            <el-form label-width="8em">
              <el-form-item v-show="param.type !== 'name' && param.type !== 'type'" v-for="(param, i) in params[item.type].params" :key="param.name + '-' + i" :label="param.label + ':'">
                <el-input clearable
                          v-if="param.type === 'text'"
                          :disabled="!param.editable"
                          v-model="zfData.fields[editingIndex].controls[index][param.name]"></el-input>

                <el-switch v-else-if="param.type === 'boolean'"
                           :disabled="!param.editable"
                           :active-value="param.name"
                           :inactive-value="''"
                           v-model="zfData.fields[editingIndex].controls[index][param.name]"></el-switch>

                <el-input-number v-else-if="param.type === 'number'"
                                 :min="param.min ? parseInt(param.min) : -Infinity"
                                 :max="param.max ? parseInt(param.max) : Infinity"
                                 :disabled="!param.editable"
                                 v-model="zfData.fields[editingIndex].controls[index][param.name]"></el-input-number>

                <z-form-param-file-type v-else-if="param.type === 'accept'" v-model="zfData.fields[editingIndex].controls[index][param.name]"></z-form-param-file-type>
                <z-form-param-option v-else-if="param.type === 'option'" v-model="zfData.fields[editingIndex].controls[index][param.name]"></z-form-param-option>
                <z-form-param-verify v-else-if="param.type === 'verify'" v-model="zfData.fields[editingIndex].controls[index][param.name]"></z-form-param-verify>
                <z-form-param-address v-else-if="param.type === 'address'" v-model="zfData.fields[editingIndex].controls[index][param.name]" :address-data="$ZF.addressData"></z-form-param-address>

                <el-slider v-else-if="param.type === 'col'"
                           :min="(parseInt(param.min) || 2)"
                           :max="(parseInt(param.max) || 24)"
                           show-stops
                           :disabled="!param.editable"
                           @input="zfData.fields[editingIndex].controls[index][param.name] = $event"
                           :value="(parseInt(zfData.fields[editingIndex].controls[index][param.name]) || 12)"></el-slider>
              </el-form-item>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <!--属性编辑区域 end-->

    <!--添加控件弹窗 start-->
    <el-dialog @closed="addControlParam = {}"
               v-if="params" :close-on-click-modal="false"
               :title="params[addControlParam.type] ? params[addControlParam.type].name : '选择控件'"
               :visible.sync="addingControl"
               append-to-body>
      <div class="add-control-panel">
        <div class="add-control-list">
          <control-selector v-model="addControlParam.type" :params="params"></control-selector>
        </div>
        <div class="add-control-editor">
          <el-form label-width="8em" v-if="addControlParam.type">
            <el-form-item v-show="param.type !== 'name' && param.type !== 'type'" v-for="(param, i) in params[addControlParam.type].params" :key="param.name + '-' + i" :label="param.label + ':'">
              <el-input clearable
                        v-if="param.type === 'text'"
                        :disabled="!param.editable"
                        v-model="addControlParam[param.name]"></el-input>

              <el-switch v-else-if="param.type === 'boolean'"
                         :disabled="!param.editable"
                         :active-value="param.name"
                         :inactive-value="''"
                         v-model="addControlParam[param.name]"></el-switch>

              <el-input-number v-else-if="param.type === 'number'"
                               :min="param.min ? parseInt(param.min) : -Infinity"
                               :max="param.max ? parseInt(param.max) : Infinity"
                               :disabled="!param.editable"
                               v-model="addControlParam[param.name]"></el-input-number>

              <z-form-param-file-type v-else-if="param.type === 'accept'" v-model="addControlParam[param.name]"></z-form-param-file-type>
              <z-form-param-option v-else-if="param.type === 'option'" v-model="addControlParam[param.name]"></z-form-param-option>
              <z-form-param-verify v-else-if="param.type === 'verify'" v-model="addControlParam[param.name]"></z-form-param-verify>

              <el-slider v-else-if="param.type === 'col'"
                         :min="(parseInt(param.min) || 2)"
                         :max="(parseInt(param.max) || 24)"
                         show-stops
                         :disabled="!param.editable"
                         @input="addControlParam[param.name] = $event"
                         :value="(parseInt(addControlParam[param.name]) || 12)"></el-slider>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addControl">确 定</el-button>
        <el-button @click="addingControl = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!--添加控件弹窗 end-->

    <!--保存为模板弹窗 start-->
    <el-dialog title="保存为模板" @closed="saveToTempData = {name: '', type: null, scenes: null}" v-if="tempTypeData.status" :visible.sync="saveToTempShow" append-to-body>
      <el-form label-width="8em" :model="saveToTempData">
        <el-form-item label="名称:" prop="name" :rules="[{ required: true, message: '表单名称不能为空'},{ min: 3, max: 25, message: '表单名称长度需控制在 3 到 25 个字符'}]">
          <el-input v-model="saveToTempData.name"></el-input>
        </el-form-item>
        <el-form-item label="类型:">
          <table class="custom-form-temp-type-panel">
            <tr>
              <td class="custom-form-temp-type-panel-title">行业类型</td>
              <td class="custom-form-temp-type-panel-title">场景类型</td>
            </tr>
            <tr>
              <td>
                <el-tree @node-click="saveToTempTypeClick" :render-content="renderContentType" :data="tempTypeData.types" :props="treeProps" node-key="ID" render-after-expand highlight-current
                         expand-on-click-node auto-expand-parent accordion></el-tree>
              </td>
              <td>
                <el-tree @node-click="saveToTempScenesClick" :render-content="renderContentScenes" :data="tempTypeData.scenes" :props="treeProps" node-key="ID" render-after-expand highlight-current
                         expand-on-click-node auto-expand-parent accordion></el-tree>
              </td>
            </tr>
          </table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveToTemp">确 定</el-button>
        <el-button @click="saveToTempShow = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!--保存为模板弹窗 end-->
  </div>
</template>

<script>
import ZFormParamOption from './components/ZFormParamOption.vue'
import ZFormParamVerify from './components/ZFormParamVerify.vue'
import ZFormParamAddress from './components/ZFormParamAddress.vue'
import ZFormParamFileType from './components/ZFormParamFileType.vue'
import ControlSelector from './components/ControlSelector.vue'
import $ZF from './libs/zform.js'
import widgets from './mock/widgets.js'
import Sortable from 'sortablejs'

const $ = window.$
const axios = window.axios

const tools = {
  createInputName () {
    return Date.now().toString(36) + Math.random().toString(36).substr(2, 6)
  }
}

export default {
  components: {ZFormParamFileType, ControlSelector, ZFormParamOption, ZFormParamVerify, ZFormParamAddress},
  props: {
    ID: {
      type: String,
      default: ''
    },
    $ZF: {
      default () {
        return $ZF
      }
    }
  },
  data () {
    return {
      template: null,
      templateZcms: '',
      zfData: null,
      preview: false,
      doms: {
        root: null,
        items: null,
        header: null,
        footer: null,
        title: null,
        help: null,
        form: null
      },
      actions: {
        onItemClick: null,
        onFormClick: null
      },
      params: null,
      editingIndex: -1,
      widgets: widgets,
      formSortableObj: null,
      widgetSortableObj: null,
      antiShake: null,
      lastData: null,
      addControlParam: {},
      addingControl: false,
      collapseValue: ['item'],
      saveToTempShow: false,
      tempTypeData: {
        status: false,
        types: null,
        scenes: null
      },
      treeProps: {
        label: 'name',
        children: 'children',
        disabled: false,
        isLeaf: false
      },
      saveToTempData: {
        name: '',
        type: null,
        scenes: null
      }
    }
  },
  mounted () {
    this.params = $ZF.params

    if (this.ID) {
      this.getTemplate(this.ID)
    }
    new Sortable(this.$refs['widgets'], {
      group: {
        name: 'form-item',
        pull: 'clone',
        put: false
      },
      sort: false,
      draggable: '.pw-zform-item'
    })
  },
  watch: {
    'template': 'onTemplateChange',
    'zfData': {
      handler () {
        // 防抖更新界面
        if (this.lastData !== JSON.stringify(this.zfData)) {
          this.lastData = JSON.stringify(this.zfData)
          if (this.antiShake) {
            clearTimeout(this.antiShake)
          }
          this.antiShake = setTimeout(this.onDataChange.bind(this), 250)
        }
      },
      deep: true
    },
    'editingIndex': 'onSelectedItemChange',
    'addControlParam.type': 'onControlTypeChange'
  },
  methods: {
    /**
       * 初始化,获取模板类型
       */
    async initType () {
      let res = await axios.get('/ui/customforms/customFormType/treeData?editFlag=Y')
      res = res.data
      if (res.status === 1) {
        this.tempTypeData.status = true
        this.tempTypeData.types = res.data[0].children
        this.tempTypeData.scenes = res.data[1].children
        this.saveToTempShow = true
      }
    },

    /**
       * 获取模板数据(固定数据,后期改为异步请求)
       * @param id
       */
    async getTemplate (id) {
      let res = await axios.get(`/ui/customforms/templates/${id}`)
      this.templateZcms = res.data.data
      this.template = JSON.parse(this.templateZcms.content)
    },

    /**
       * 模板变化,转化数据
       */
    onTemplateChange () {
      this.zfData = $ZF.zcmsDataFormat(this.template)
    },

    /**
       * 数据变化,渲染
       */
    onDataChange () {
      this.antiShake = null
      $ZF.createForm(this.$refs['form-box'], this.zfData)
      this.doms.root = $(this.$refs['form-box'])
      this.doms.items = this.doms.root.find('.pw-zform-item')
      this.doms.header = this.doms.root.find('.pw-zform-title-box')
      this.doms.footer = this.doms.root.find('.pw-zform-footer')
      this.doms.title = this.doms.header.find('h4')
      this.doms.help = this.doms.header.find('p')
      this.doms.form = this.doms.root.find('form')
      this.doms.itemBox = this.doms.form.find('.pw-zform-item-box')
      this.initForm()
    },

    /**
       * 表单项点击事件
       */
    onItemClick () {
      const that = this
      if (!this.actions.onItemClick) {
        this.actions.onItemClick = function () {
          const $this = $(this)
          that.editingIndex = parseInt($this.attr('item-index'))
          that.doms.items.removeClass('selected')
          $this.addClass('selected')
          return false
        }
      }
      return this.actions.onItemClick
    },

    /**
       * 选中的表单项变化时触发
       */
    onSelectedItemChange () {
      this.doms.items.removeClass('selected')
      const item = this.doms.items[this.editingIndex]
      if (item) {
        $(item).addClass('selected')
      }
    },

    /**
       * 针对编辑功能初始化form
       * @param $dom
       */
    initForm ($dom) {
      // item内部鼠标穿透
      this.doms.items.addClass('editing')
      this.doms.items.children().css('pointer-events', 'none')
      this.doms.header.css('pointer-events', 'none')
      this.doms.footer.css('pointer-events', 'none')
      if (this.doms.form[0]) {
        this.doms.form[0].reset()
      }
      this.doms.items.on('click', this.onItemClick())

      if (!this.actions.onFormClick) {
        this.actions.onFormClick = function () {
          this.editingIndex = -1
        }.bind(this)
      }
      this.doms.form.on('click', this.actions.onFormClick)

      this.doms.items.append(
        '<div class="custom-form-item-action">' +
          '<a href="javascript: void(0)" class="action-item action-copy" title="复制">' +
          '<i class="fa fa-fw fa-plus"></i>' +
          '</a>' +
          '<a href="javascript: void(0)" class="action-item action-move" title="移动">' +
          '<i class="fa fa-fw fa-arrows action-move"></i>' +
          '</a>' +
          '<a href="javascript: void(0)" class="action-item action-remove" title="删除">' +
          '<i class="fa fa-fw fa-remove action-remove"></i>' +
          '</a>' +
          '</div>')

      // 移除表单项
      this.doms.items.find('a.action-item.action-remove').on('click', function (evt) {
        const index = parseInt($(evt.target).parents('div[item-index]').attr('item-index'))
        this.editingIndex = -1
        this.zfData.fields.splice(index, 1)
        return false
      }.bind(this))

      // 复制表单项
      this.doms.items.find('a.action-item.action-copy').on('click', function (evt) {
        const index = parseInt($(evt.target).parents('div[item-index]').attr('item-index'))
        const item = JSON.parse(JSON.stringify(this.zfData.fields[index]))
        item.controls.forEach(control => {
          control.input_name = tools.createInputName()
        })
        this.zfData.fields.splice(index + 1, 0, item)
        this.editingIndex++
        return false
      }.bind(this))

      // 拖拽排序
      if (this.formSortableObj) this.formSortableObj.destroy()
      if (this.doms.itemBox[0]) {
        this.formSortableObj = new Sortable(this.doms.itemBox[0], {
          group: {
            name: 'form-item',
            pull: false,
            put: true
          },
          sort: true,
          handle: '.action-move',
          draggable: '.pw-zform-item',
          onUpdate: function (evt) {
            this.zfData.fields.splice(evt.newIndex, 0, this.zfData.fields.splice(evt.oldIndex, 1)[0])
            this.editingIndex = evt.newIndex
          }.bind(this),
          onAdd: function (evt) {
            const widget = JSON.parse(JSON.stringify(this.widgets[evt.oldIndex].data))
            widget.controls.forEach(control => {
              control.input_name = tools.createInputName()
            })
            this.zfData.fields.splice(evt.newIndex, 0, widget)
            this.editingIndex = evt.newIndex
          }.bind(this)
        })
      }

      this.onSelectedItemChange()
    },

    /**
       * 预览操作
       */
    previewForm () {
      this.doms.items.removeClass('editing')
      this.doms.items.children().css('pointer-events', '')
      this.doms.header.css('pointer-events', '')
      this.doms.footer.css('pointer-events', '')
      this.doms.items.off('click', this.actions.onItemClick)
      this.doms.form.off('click', this.actions.onFormClick)
    },

    /**
       * 预览开关
       */
    onPreview () {
      this.preview = !this.preview
      if (this.preview) {
        this.previewForm()
      } else {
        this.initForm()
      }
    },

    /**
       * 布局label宽度变化
       * @param value
       * @param param
       * @param key
       */
    layoutChange (value, param, key) {
      param[key] = {
        label: value,
        content: 24 - value
      }
    },

    /**
       * 添加控件
       */
    onAddControl () {
      this.addingControl = true
    },
    addControl () {
      const addControlParam = JSON.parse(JSON.stringify(this.addControlParam))
      addControlParam.input_name = tools.createInputName()
      this.zfData.fields[this.editingIndex].controls.push(addControlParam)
      this.addingControl = false
      this.addControlParam = {}
    },
    onControlTypeChange () {
      let addControlParam = {}
      const params = this.params[this.addControlParam.type]
      if (params && params.params && params.params.length) {
        params.params.forEach(function (item) {
          switch (item.type) {
            case 'type':
              addControlParam.type = this.addControlParam.type
              break
            case 'input_name':
              addControlParam.input_name = tools.createInputName()
              break
            default:
              addControlParam[item.name] = item._default
              break
          }
        }.bind(this))
        this.addControlParam = addControlParam
      }
    },

    /**
       * 移除控件
       * @param index
       */
    onRemoveControl (index) {
      this.zfData.fields[this.editingIndex].controls.splice(index, 1)
    },

    /**
       * 下移控件
       * @param disabled
       * @param index
       */
    onDwControl (disabled, index) {
      if (!disabled) {
        const controls = this.zfData.fields[this.editingIndex].controls
        controls.splice(index + 1, 0, controls.splice(index, 1)[0])
      }
    },

    /**
       * 上移控件
       * @param disabled
       * @param index
       */
    onUpControl (disabled, index) {
      if (!disabled) {
        const controls = this.zfData.fields[this.editingIndex].controls
        controls.splice(index - 1, 0, controls.splice(index, 1)[0])
      }
    },

    /**
       * 保存
       */
    onSave (callback) {
      if (this.zfData) {
        let data = $ZF.formatJsonToData(this.zfData)
        let json = $ZF.zcmsDataFormat(data)
        let NameLabelMap = this.zfData.fields.map(field => {
          return {
            label: field.label,
            controls: field.controls.map(control => {
              return {name: control.input_name, type: control.type}
            })
          }
        })
        if (JSON.stringify(json) === JSON.stringify(this.zfData)) {
          axios.post('/ui/customforms/save', {
            id: this.templateZcms.ID,
            content: data,
            NameLabelMap: NameLabelMap,
            title: this.zfData.title
          }).then(res => {
            if (callback && typeof callback === 'function') {
              callback()
            } else {
              this.$alert(res.data.message, '消息', {confirmButtonText: '确定'})
            }
          })
        } else {
          this.$alert('数据异常,保存失败', '错误', {confirmButtonText: '确定'})
        }
      }
    },

    /**
       * 保存为模板
       */
    onSaveToTemplate () {
      if (!this.tempTypeData.status) {
        this.initType()
      } else {
        this.saveToTempShow = true
      }
    },

    renderContentType (h, {node, data, store}) {
      let selected = ''
      if (this.saveToTempData.type && data.ID === this.saveToTempData.type.ID) selected = 'selected'
      return (<span class={['el-tree-node__label', 'custom-form-tree-node', selected]}>{node.label}</span>)
    },
    renderContentScenes (h, {node, data, store}) {
      let selected = ''
      if (this.saveToTempData.scenes && data.ID === this.saveToTempData.scenes.ID) selected = 'selected'
      return (<span class={['el-tree-node__label', 'custom-form-tree-node', selected]}>{node.label}</span>)
    },

    saveToTempTypeClick (obj, node, nodeSelf) {
      this.saveToTempData.type = obj
    },

    saveToTempScenesClick (obj, node, nodeSelf) {
      this.saveToTempData.scenes = obj
    },

    /**
       * 保存为模板
       */
    saveToTemp () {
      if (this.zfData) {
        if (!this.saveToTempData.name || this.saveToTempData.name.length < 3 || this.saveToTempData.name.length > 25) {
          this.$alert('请输入正确的名称', '错误', {confirmButtonText: '确定'})
        } else if (!this.saveToTempData.type) {
          this.$alert('行业类型不能为空', '错误', {confirmButtonText: '确定'})
        } else if (!this.saveToTempData.scenes) {
          this.$alert('场景类型不能为空', '错误', {confirmButtonText: '确定'})
        } else {
          this.zfData.title = this.saveToTempData.name
          let data = $ZF.formatJsonToData(this.zfData)
          let json = $ZF.zcmsDataFormat(data)
          let NameLabelMap = this.zfData.fields.map(field => {
            return {
              label: field.label,
              controls: field.controls.map(control => {
                return {name: control.input_name, type: control.type}
              })
            }
          })
          if (JSON.stringify(json) === JSON.stringify(this.zfData)) {
            axios.post('/ui/customforms/saveTemp', {
              name: this.saveToTempData.name,
              IndustryTypeID: this.saveToTempData.type.ID,
              IndustryTypeInnerCode: this.saveToTempData.type.innerCode,
              SceneTypeID: this.saveToTempData.scenes.ID,
              SceneTypeInnerCode: this.saveToTempData.scenes.innerCode,
              content: data,
              NameLabelMap: NameLabelMap
            }).then(res => {
              this.saveToTempShow = false
              this.$alert(res.data.message, '消息', {
                confirmButtonText: '确定'
              })
            })
          } else {
            this.$alert('数据异常,保存失败', '错误', {confirmButtonText: '确定'})
          }
        }
      }
    },
    onKeyDown (key) {
      if (!this.preview && this.editingIndex >= 0) {
        switch (key) {
          case 'delete':
            var index = this.editingIndex
            this.editingIndex = -1
            this.zfData.fields.splice(index, 1)
            break

          case 'up':
            var oldIndexUp = this.editingIndex
            var newIndexUp = this.editingIndex - 1
            if (newIndexUp > -1) {
              this.editingIndex--
              this.zfData.fields.splice(newIndexUp, 0, this.zfData.fields.splice(oldIndexUp, 1)[0])
            }
            break

          case 'down':
            var oldIndexDown = this.editingIndex
            var newIndexDown = this.editingIndex + 1
            if (newIndexDown < this.zfData.fields.length) {
              this.editingIndex++
              this.zfData.fields.splice(newIndexDown, 0, this.zfData.fields.splice(oldIndexDown, 1)[0])
            }
            break
        }
      }
    },
    publish () {
      this.onSave(function () {
        axios.put(`/ui/customforms/${this.templateZcms.ID}/publish`).then(res => {
          if (res.data.status === 1) {
            this.$alert('发布成功', '成功', {confirmButtonText: '确定'})
          } else {
            this.$alert('发布失败', '失败', {confirmButtonText: '确定'})
          }
        })
      }.bind(this))
    },
    resetLayout () {
      this.zfData.fields.forEach(field => {
        field.layout.label = this.zfData.layout.label
        field.layout.content = this.zfData.layout.content
      })
    }
  }
}
</script>

<!--公开样式-->
<style>
  .editing .picker__holder {
    display: none !important;
  }

  .custom-form-form-edit-view .el-collapse-item__wrap {
    padding-right: 10px;
  }

  .pw-zform-item.editing {
    border: 1px solid #ECEDEF;
    border-radius: 4px;
    opacity: 0.9;
  }

  .pw-zform-item.editing:hover, .pw-zform-item.editing.selected {
    border-color: #3db389;
    opacity: 1;
  }

  .pw-zform-item.editing.selected {
    opacity: 1;
    background-color: #f5f5f5;
  }

  .custom-form-item-action {
    display: none;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .custom-form-item-action > .action-item {
    display: inline-block;
    width: 22px;
    height: 22px;
    color: #fff;
  }

  .custom-form-item-action > .action-item > .fa {
    display: inline-block;
    padding: 4px;
    width: 22px;
    height: 22px;
  }

  .custom-form-item-action > .action-item:first-child {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }

  .custom-form-item-action > .action-item:last-child {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }

  .custom-form-item-action > .action-move {
    cursor: move;
    background-color: #3db389;
  }

  .custom-form-item-action > .action-copy {
    background-color: #0099ff;
  }

  .custom-form-item-action > .action-remove {
    background-color: #ff5704;
  }

  .pw-zform-item.editing.selected > .custom-form-item-action {
    display: block;
  }

  .add-control-panel {
    width: 100%;
    height: calc(80vh - 125px);
  }

  .add-control-panel:after {
    content: '';
    display: table;
    clear: both;
  }

  .add-control-panel > .add-control-list, .add-control-panel > .add-control-editor {
    float: left;
    height: 100%;
  }

  .add-control-panel > .add-control-list {
    width: 30%;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    border: 1px solid #ECEDEF;
  }

  .add-control-panel > .add-control-editor {
    width: 70%;
    padding: 10px;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    border: 1px solid #ECEDEF;
  }

  .pw-zform .custom-form-widget {
    height: 34px;
    background-color: #3db389;
    overflow: hidden;
  }

  .pw-zform .custom-form-widget > div {
    display: none;
  }

  .pw-zform .el-collapse-item__header {
    border-top: 1px solid #ECEDEF;
  }

  .pw-zform .el-collapse-item__header.is-active {
    border-bottom: 1px solid #ECEDEF;
  }

  .custom-form-tree-node {
    display: inline-block;
    padding: 2px 4px;
    width: 100%;
    line-height: normal;
  }

  .custom-form-tree-node:hover, .custom-form-tree-node.selected {
    color: #fff;
    background-color: #3db389;
    border-radius: 4px;
  }
</style>

<!--内部样式-->
<style scoped>
  .custom-form-form-edit-view {
    display: block;
    position: relative;
    width: 100%;
    height: calc(100vh - 152px);
    box-sizing: border-box;
    overflow: hidden;
  }

  .custom-form-widget-view, .custom-form-form-view, .custom-form-edit-view {
    position: absolute;
    height: 100%;
    top: 0;
    overflow: hidden;
    box-sizing: border-box;
    transition: all 500ms;
    -o-transition: all 500ms;
    -moz-transition: all 500ms;
    -webkit-transition: all 500ms;
  }

  .custom-form-widget-view {
    width: 230px;
    left: 0;
    background: #f0f3f6;
  }

  .custom-form-form-view {
    width: calc(70% - 230px);
    left: 230px;
    background-color: #F6F7F9;
    border-left: 1px #ECEDEF solid;
  }

  .custom-form-edit-view {
    width: 30%;
    right: 0;
    background-color: white;
    border-left: 1px solid #ECEDEF;
    overflow: hidden;
  }

  .preview > .custom-form-widget-view {
    width: 0;
  }

  .preview > .custom-form-edit-view {
    width: 0;
  }

  .preview > .custom-form-form-view {
    width: calc(100% + 15px);
    left: 0;
  }

  .custom-form-form-view-head, .custom-form-edit-view-head {
    position: relative;
    height: 40px;
    padding: 2px 17px 2px 2px;
    text-align: right;
    background-color: white;
    border-bottom: 1px solid #ECEDEF;
  }

  .custom-form-form-view-head .go-back {
    position: absolute;
    left: 10px;
    top: 6px;
  }

  .custom-form-form-view-body, .custom-form-edit-view-body {
    height: calc(100% - 60px);
    overflow-x: hidden;
    overflow-y: scroll;
    box-sizing: border-box;
  }

  .custom-form-form-view-body {
    padding: 10px 25px 10px 10px;
  }

  .custom-form-edit-view-body {
    width: calc(100% + 15px);
    padding-right: 15px;
  }

  .custom-form-form-view-head > .custom-form-form-name {
    text-align: left;
    width: calc(100% - 500px);
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .custom-form-form-name {
    position: absolute;
    left: 12px;
    top: 0;
    line-height: 40px;
    font-weight: 700;
    color: #000;
  }

  .custom-form-edit-view .el-select {
    width: 100%;
  }

  .custom-form-edit-view-body .el-collapse-item {
    margin: auto;
  }

  .control-param-panel:focus .control-param-panel-body {
    border-color: #3db389;
  }

  .control-param-panel:focus .control-param-panel-head span {
    color: #3db389;
  }

  .custom-form-widget-view-body {
    padding: 0 10px;
    height: calc(100% - 60px);
    overflow-x: hidden;
    overflow-y: scroll;
  }

  .custom-form-widget {
    border: 1px solid #ECEDEF;
    background: #fff;
    border-radius: 3px;
    padding: 5px 0;
    text-align: center;
    margin-top: 10px;
  }

  .custom-form-widget:hover {
    cursor: move;
    border-color: #3db389;
  }

  .custom-form-widget img {
    max-width: 100%;
  }

  .custom-form-control-item {
    width: 100%;
    height: 100%;
    position: relative;
    display: block;
    font-size: 17px;
    font-weight: 600;
    line-height: 47px;
    color: #3D4C44;
    padding-right: 35px;
  }

  .custom-form-control-item-title, .custom-form-control-item-action {
    display: inline-block;
    font-weight: inherit !important;
    font-size: inherit !important;
    line-height: inherit !important;
  }

  .custom-form-control-item:after {
    content: '';
    display: table;
    clear: both;
  }

  .custom-form-control-item-action {
    float: right;
    width: 29px;
    height: 29px;
    padding: 6px;
    line-height: 33px !important;
  }

  .custom-form-control-item-action.up:hover, .custom-form-control-item-action.dw:hover {
    color: #3db389;
  }

  .custom-form-control-item-action.rm:hover {
    color: #ff5704;
  }

  .custom-form-control-item-action.disabled {
    color: #a0a0a0 !important;
    cursor: not-allowed;
  }

  .custom-form-temp-type-panel {
    width: 100%;
    border-top: 1px solid #ECEDEF;
    border-radius: 4px;
  }

  .custom-form-temp-type-panel > tr {
    border-bottom: 1px solid #ECEDEF;
  }

  .custom-form-temp-type-panel > tr > td {
    border-left: 1px solid #ECEDEF;
    border-right: 1px solid #ECEDEF;
  }

  .custom-form-temp-type-panel-title {
    text-align: center;
    font-weight: 600;
  }
</style>
