<template>
 <el-dialog
 @opened="dialogOpen"
 :title='pageTitle'
 :visible.sync="dialogVisible"
 @closed="dialogClose" width="95%"
 :append-to-body='true'
 :close-on-click-modal='false'>
  <div id='pageBox'>
        <ul class="controlUl">
          <li
          class="controlUlli"
          :class='item.activity?"activity":""'
          v-for="(item,index) in layout"
          :key='index' @click="positionChage(item)">
          <div class="innerli">
            <div>
              <span>{{index+1}}:</span>
              <span>{{item.control.el|componentFilter}}</span>
              <span>{{item.control.position}}</span>
            </div>
            <div>
              <i class="el-icon-delete" @click='deleteItem(index)'></i>
            </div>
          </div>

          </li>
          <li class="controlUlli addButtonel"  :class='isAddControl?"activity":""'  @click='positionChage()'>新增</li>
        </ul>
      <div  style='flex:2;height:500px;'>
        <el-form id='formBox' :model="itemForm" ref="itemForm" label-width="120px" class="demo-itemForm">
          <el-form-item label="页面标识" prop="page" v-if='false'>
            <el-input :disabled="true" v-model="itemForm.control.page" placeholder="请输入页面名称"></el-input>
          </el-form-item>
          <el-form-item label="控件名称" prop="position">
            <el-input v-model="itemForm.control.position" placeholder="请输入控件名称(最好是英文)"></el-input>
          </el-form-item>
          <el-form-item label="控件类型" prop="el">
            <el-select @change='controlChange' v-model="itemForm.control.el" placeholder="请选择控件类型">
              <el-option v-for='(item,index) in elOptions' :key='index' :label="item.label" :value="item.value"></el-option>
            </el-select>
            <el-input v-if='controlPropVisity' v-model="itemForm.control.prop" placeholder="请输入绑定字段"></el-input>
            <el-input  v-if='controlPlaceholderVisity' v-model="itemForm.control.placeholder" placeholder="请输入提示语palceholder"></el-input>
            <el-input  v-if='controlButtonLabelVisity' v-model="itemForm.control.label" placeholder="请输入label名称"></el-input>
          </el-form-item>
          <el-form-item label="是否是请求组件" prop="isRequestControl" v-show='false'>
            <el-switch v-model="itemForm.control.isRequestControl"></el-switch>
          </el-form-item>
          <el-form-item label="定位" prop="x">
            <div class="xywhBox">
                <div class="xywhItem">
                  x: <el-input-number v-model="itemForm.x" size="mini"></el-input-number>
                </div>
                <div class="xywhItem">
                  y:  <el-input-number v-model="itemForm.y" size="mini"></el-input-number>
                </div>
                <div class="xywhItem">
                  w:  <el-input-number v-model="itemForm.w" size="mini"></el-input-number>
                </div>
                <div class="xywhItem">
                  h:  <el-input-number v-model="itemForm.h" size="mini"></el-input-number>
                </div>
            </div>
          </el-form-item>
          <el-form-item label='备注'>
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="remark">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button size='mini' type="primary" @click="submit">保存</el-button>
            <el-button size='mini' type="primary" @click="submitOther">另存</el-button>
          </el-form-item>
        </el-form></div>
  </div>
 </el-dialog>
</template>

<script>
import uuidv1 from 'uuid/v1'
const elOptions = [{
  value: 'hsLineBar',
  label: '柱状-折线图',
  isRequestControl: true,
  controlPropVisity: false,
  controlPlaceholderVisity: false,
  controlButtonLabelVisity: false
}, {
  value: 'el-input',
  label: '输入框',
  isRequestControl: false,
  controlPropVisity: true,
  controlPlaceholderVisity: true,
  controlButtonLabelVisity: false
}, {
  value: 'el-button',
  label: '按钮',
  isRequestControl: false,
  controlPropVisity: false,
  controlPlaceholderVisity: false,
  controlButtonLabelVisity: true
}, {
  value: 'el-date-picker-daterange',
  label: '日期选择',
  isRequestControl: false,
  controlPropVisity: true,
  controlPlaceholderVisity: false,
  controlButtonLabelVisity: false
}, {
  value: 'el-date-picker-monthrange',
  label: '月份选择',
  isRequestControl: false,
  controlPropVisity: true,
  controlPlaceholderVisity: false,
  controlButtonLabelVisity: false
}, {
  value: 'hsCarousel',
  label: '轮播图',
  isRequestControl: true,
  controlPropVisity: false,
  controlPlaceholderVisity: false,
  controlButtonLabelVisity: false
}]
export default {
  props: {
    pagePath: {
      type: String,
      default: ''
    },
    value: Boolean
  },
  watch: {
    pagePath(val) {
      this.pageTitle = 'queryBI-----' + val
    },
    value(val) {
      this.dialogVisible = val
    },
    dialogVisible(val) {
      this.$emit('input', val)
    },
    itemForm: {
      handler: function(newVal, oldVal) {
        if (!newVal) return
        this.controlChange(newVal.control.el)
      },
      deep: true
    }
  },
  data() {
    return {
      pageTitle: 'queryBI',
      isAddControl: false,
      dialogVisible: false,
      pagePathO: '',
      remark: '布局页面被划分为 垂直方向划分为20等份，水平方向为12等份，可以按照这个来初始布局',
      itemForm: {
        control: {
          el: '',
          isRequestControl: false,
          page: '',
          position: '',
          searchParms: []
        },
        x: 0,
        y: 0,
        w: 3,
        h: 3
      },
      itemFormCopy: {
        control: {
          el: '',
          isRequestControl: false,
          page: '',
          position: '',
          searchParms: []
        },
        x: 0,
        y: 0,
        w: 3,
        h: 3
      },
      layout: [],
      searchParms: [],
      elOptions: elOptions,
      controlPropVisity: false,
      controlPlaceholderVisity: false,
      controlButtonLabelVisity: false
    }
  },
  filters: {
    componentFilter: function(val) {
      const label = elOptions.find(item => item.value === val)
      return label.label
    }
  },
  methods: {
    download(name, data) {
      var urlObject = window.URL || window.webkitURL || window
      var downloadData = new Blob([data])
      var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
      save_link.href = urlObject.createObjectURL(downloadData)
      save_link.download = name
      this.fake_click(save_link)
    },
    fake_click(obj) {
      var ev = document.createEvent('MouseEvents')
      ev.initMouseEvent(
        'click', true, false, window, 0, 0, 0, 0, 0
        , false, false, false, false, 0, null
      )
      obj.dispatchEvent(ev)
    },
    // 另存
    submitOther() {
      this.download('test.txt', 'hahaha')
      this.$message.error('暂未实现')
    },
    controlChange(val) {
      const item = elOptions.find(x => x.value === val)
      if (item) {
        const { controlPropVisity, controlPlaceholderVisity, controlButtonLabelVisity } = item
        this.controlPropVisity = controlPropVisity
        this.controlPlaceholderVisity = controlPlaceholderVisity
        this.controlButtonLabelVisity = controlButtonLabelVisity
      }
    },
    dialogOpen() {
      this.pagePathO = this.pagePath
      this.getPageConfig()
    },
    dialogClose() {
      this.dialogVisible = false
    },
    pageChange(path) {
      this.itemForm.control.page = path
    },
    checkProp() {
      const { el, page, position } = this.itemForm.control
      if (!el) {
        this.$message.error('请输入控件名称')
        return
      }
      if (!page) {
        this.$message.error('请输入页面标识')
        return
      }
      if (!position) {
        this.$message.error('请输入控件所在区域')
        return
      }
      return true
    },
    deleteItem(index) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitDelete(index)
      }).catch((e) => {
        if (e.message) {
          this.$message({
            type: 'warning',
            message: e.message
          })
        }
      })
    },
    submitDelete(index) {
      const data = JSON.parse(JSON.stringify(this.layout))
      data.splice(index, 1)
      this.savePageConfig(data, false)
    },
    submit() {
      if (!this.checkProp()) return
      const data = JSON.parse(JSON.stringify(this.layout))
      if (this.itemForm.i) { // 修改
        const index = this.layout.findIndex(x => x.i === this.itemForm.i)
        if (index !== -1) {
          data[index] = this.itemForm
        }
      } else { // 新增
        const item = this.layout.find(x => x.control.position === this.itemForm.control.position)
        if (item) {
          this.$message.error('已存在相同控件名称')
          return
        }
        this.itemForm.id = uuidv1()
        this.itemForm.i = uuidv1()
        // 设置是否为数据组件
        const targetContrl = elOptions.find(x => x.value === this.itemForm.control.el)
        this.itemForm.isRequestControl = targetContrl.isRequestControl
        data.push(this.itemForm)
      }
      this.savePageConfig(data)
    },
    savePageConfig(data, flage = true) {
      if (flage && !this.checkProp()) return
      const parm = {
        page: this.pagePathO || (data[0] && data[0].control.page) || '',
        position: 'pageConfig'
      }
      this.$API.runSave(parm, {}, data).then(_ => {
        this.$message.success(flage ? '保存成功！' : '删除成功！')
        this.getPageConfig()
      })
    },
    positionChage(item) {
      const currentActivity = this.layout.find(item => item.activity)
      if (currentActivity) {
        currentActivity.activity = false
      }
      if (item) {
        this.isAddControl = false
        const table = this.layout.find(x => x.control.position === item.control.position)
        item.activity = true
        if (!table.control.searchParms) {
          table.control.searchParms = []
        }
        this.itemForm = JSON.parse(JSON.stringify(table))
      } else {
        this.isAddControl = true
        this.itemForm = JSON.parse(JSON.stringify(this.itemFormCopy))
        this.itemForm.control.page = this.pagePath
      }
    },
    getPageConfig() {
      const params = {
        page: this.pagePathO,
        position: 'pageConfig'
      }
      this.$API.getData(params).then(res => {
        this.itemForm = JSON.parse(JSON.stringify(this.itemFormCopy))
        this.itemForm.control.page = this.pagePathO
        this.layout = res.filter(x => x.control)
        this.layout.forEach(item => {
          item.activity = false
        })
      })
    }
  }
}
</script>
<style scoped>
#formBox{
  width: 500px;
}
#formBox >>> .el-form-item{
background: white !important;
}
#pageBox{
  background: white !important;
  height: 100%;
  padding: 10px;
  display: flex;
}
#pageBox>>> .el-input__inner{
  background-color: #FFF !important;
  border: 1px solid #DCDFE6 !important;
  color: #606266!important;
}
.xywhBox,.xywhItem{
  display: flex;
}
.controlUl{
    border: 1px solid #f1f0f0;
    padding: 10px;
    height:500px;
    flex:1;overflow: scroll;
}
.controlUlli{
    border: 1px solid whitesmoke;
    border-radius: 3px;
    padding: 3px;
    background: #efefef;
    margin-bottom: 5px;
}
.activity{
  background: #409eff;
}
.innerli{
  display: flex;
  justify-content: space-between;
}
.addButtonel{
  text-align: center;
}
</style>
