<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="jsonEditBox">
    <div style="display:flex;">
      <div class="editItemBox1">
          <div class="editeTitleItem">配置</div>
          <div :id='ideditor1'  style="width: 100%; height: 100%;"></div>
      </div>
      <div  class="editItemBox2">
         <div class="editeTitleItem">模拟数据</div>
         <div :id='ideditor2' style="width: 100%; height: 100%;"></div>
      </div>
      <div  class="editItemBox3" v-show="false">
        <div class="editeTitleItem">SQL</div>
        <div :id='ideditor3' style="width: 100%; height: 100%;"></div>
      </div>
      <div  class="editItemBox3">
        <div class="editeTitleItem">SQL</div>
        <div  ref='monacoEdit' style="width: 100%; height: 100%;border:1px solid #1160f1"></div>
      </div>
    </div>

    <el-row :gutter="20">
      <div class="buttonBox">
        <div class="infopageItem">
          <div class="pageItem">
              <span>组件名称：{{elInfo.el}}</span>
          </div>
          <div class="pageItem">
              <span>版本号：{{this.editDataAll.version}}</span>
          </div>
          <div class="pageItem">
              <span>时间：{{this.editDataAll.update_time}}</span>
          </div>
        </div>
        <div class="button_hanlde">
              <el-button size='mini' plain type="success" @click='execSql'>模拟数据</el-button>
              <el-button size='mini' type="primary" @click='showView'>查看效果</el-button>
              <el-button size='mini' type="danger" @click="submitToDb">提交到数据库</el-button>
              <el-button size='mini' type="warning" @click='resetEdit'>撤销修改</el-button>
              <el-button size='mini' type="success" @click='downSql_'>另存</el-button>
        </div>
      </div>
      <template v-if='elInfo.el=="hsLineBar"||elInfo.el=="hsPie"||elInfo.el=="hsRadar"'>
        <commonEchart  :initStyle='initStyle' :setOptions="commonData"></commonEchart>
      </template>
      <template  v-if='elInfo.el==="hsCarousel"'>
        <commonCarousel :setOptions="commonData"></commonCarousel>
      </template>
      <template  v-if='elInfo.el==="hsTable"'>
        <commonTable :tableAll="commonTableData" :configAll="commonConfigData"></commonTable>
      </template>
    </el-row>
  </div>
 </el-dialog>
</template>

<script>
import commonEchart from './commonEchart'
import commonCarousel from './commonCarousel'
import commonTable from '../common/commonTable'
import uuidv1 from 'uuid/v1'
import * as monaco from 'monaco-editor'
import sqlFormatter from 'sql-formatter'
export default {
  components: { commonEchart, commonCarousel, commonTable },
  name: 'jsoneditor',
  props: {
    elInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    jsoneditorData: {// 包含配置config和原始数据
      type: Object,
      default() {
        return {}
      }
    },
    dealWithSourceFun: {// 这个函数用来处理 配置和数据 处理的结果是一个完整options,可以用于echart直接展示
      type: Function
    },
    saveConfigDataFun: {
      type: Function
    },
    initStyle: {
      type: Object,
      default() {
        return {}
      }
    },
    complatData: {
      type: Array,
      default() {
        return []
      }
    },
    value: Boolean,
    downSql: {
      type: Function
    }
  },
  watch: {
    value(val) {
      this.dialogVisible = val
    },
    dialogVisible(val) {
      this.$emit('input', val)
    }
  },
  data() {
    return {
      options: {
        mode: 'text',
        indentation: 2,
        search: true
      },
      ideditor1: 'b' + uuidv1(),
      ideditor2: 'b' + uuidv1(),
      ideditor3: 'b' + uuidv1(),
      editor1: null,
      editor2: null,
      commonData: {},
      copyJsoneditorData: null,
      monacoEdit: null,
      pageTitle: '配置',
      dialogVisible: false,
      editDataAll: {},
      commonTableData: [],
      commonConfigData: {
        'styles': {
          'tableStyle': 'color:#babaff;font-size:.18rem;background-color:#232449;',
          'maxHeight': 'none',
          'border': false,
          'hideHeader': false,
          'headerRow': {
            'allStyle': 'border-bottom: 0.02rem solid #181635;color:#babaff;font-size:.14rem;text-align:center;padding: .2rem 0;'
          },
          'row': {
            'allStyle': ''
          },
          'column': {
            'columnIndexArr': [0, 2, 3, 4],
            'styleArr': ['fontSize:0.14rem;', 'color:#00DCE3;', 'color:#5E80FF;'],
            'allStyle': 'border-color: #232449;text-align:center;padding: .15rem 0 !important;'
          },
          'hover': {
            'hoverBackground': 'no',
            'leaveBackground': 'no'
          }
        }
      }
    }
  },
  mounted() {
  },
  methods: {
    execSql() {
      const exec = this.monacoEdit.getValue()
      this.$API.execSql(exec).then(res => {
        this.editor2.set(res)
      })
    },
    getPageInfo() {
      const parm = {}
      parm.position = this.elInfo.position
      this.$API.getSql(parm).then(data => {
        if (data && data.length) {
          this.editDataAll = data[0]
          const { app_code, control_name, json_config, json_data, page_name, query_sql } = this.editDataAll
          this.pageTitle = `配置: AppCode: <${app_code}>---page_name: <${page_name}>---control_name: <${control_name}>`
          const jsonData = {
            config: JSON.parse(json_config),
            sourceData: JSON.parse(json_data),
            sql: query_sql || ''
          }
          this.copyJsoneditorData = JSON.parse(JSON.stringify(jsonData))
          this.setJson(jsonData)
          this.initSqlEdit('monacoEdit', 'monacoEdit', query_sql || '')
        } else {
          this.initData()
        }
      })
    },
    downSql_() {
      this.downSql()
    },
    dialogClose() {
      this.dialogVisible = false
    },
    dialogOpen() {
      this.getPageInfo()
    },
    initData() {
      const app_code = sessionStorage['AppCode_'] || ''
      this.pageTitle = `配置: AppCode: <${app_code}>---page_name: <${this.elInfo.page}>---control_name: <${this.elInfo.position}>`
      this.copyJsoneditorData = JSON.parse(JSON.stringify(this.jsoneditorData))
      this.setJson(this.jsoneditorData)
      this.initSqlEdit('monacoEdit', 'monacoEdit', this.copyJsoneditorData.sql || '')
    },
    formatterSql(monacoEdit) {
      if (!monacoEdit) {
        // 尚未初始化
        this.$message.error('尚未初始化! 请刷新页面')
        return
      }
      const contanterSql = monacoEdit.getValue()
      monacoEdit.setValue(sqlFormatter.format(contanterSql))
    },
    initSqlEdit(el, monacoEdit, initValue) {
      const that = this
      this.$refs[el].innerHTML = ''
      this[monacoEdit] = monaco.editor.create(that.$refs[el], {
        value: initValue, // sqlFormatter.format(initValue),
        language: 'sql',
        wordWrapColumn: 0,
        wrappingIndent: 'indent',
        fontSize: 14,
        autoIndent: true,
        folding: true,
        foldingStrategy: 'indentation',
        minimap: {
          enabled: false
        }
      })
      this[monacoEdit].onDidChangeModelContent(function(event) {
        initValue = that[monacoEdit].getValue()
      })
      // window.addEventListener('resize', function() {
      //   that.initSqlEdit()
      // })
    },
    resetEdit() {
      this.openTips('是否确定撤销修改？', this.setOldJson)
    },
    setOldJson() {
      this.setJson(this.copyJsoneditorData)
    },
    submitToDb() {
      const that = this
      this.openTips('此操作将覆盖数据库中的数据, 是否继续?', that.submitData)
    },
    openTips(message, fun) {
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          fun()
        })
        .catch((e) => {
          console.log(e)
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    submitData() {
      if (this.complatData.length) {
        const complatData = JSON.parse(JSON.stringify(this.complatData))
        const index = complatData.findIndex(item => {
          return item.config.id === this.editor1.get().id
        })
        complatData[index].config = this.editor1.get()
        complatData[index].sourceData = this.editor2.get()
        const sql = this.monacoEdit.getValue()
        this.saveConfigDataFun(this.editor1.get(), complatData, sql, this.elInfo)
      } else {
        const sql = this.monacoEdit.getValue()
        this.saveConfigDataFun(this.editor1.get(), this.editor2.get(), sql, this.elInfo)
      }
    },
    setJson(data) {
      const { config, sourceData, sql } = JSON.parse(JSON.stringify(data))
      if (!this.editor1) {
        this.drow(this.ideditor1, config, 'editor1')
        this.drow(this.ideditor2, sourceData, 'editor2')
        this.drow(this.ideditor3, sql, 'editor3')
      } else {
        this.editor1.set(config)
        this.editor2.set(sourceData)
      }
    },
    showView() {
      if (this.elInfo.el === 'hsTable') {
        this.showEchartTable()
      } else {
        this.showEchart()
      }
    },
    showEchart() {
      const config = this.editor1.get()
      const sourceData = this.editor2.get()
      this.commonData = this.dealWithSourceFun(config, sourceData)
    },
    showEchartTable() {
      this.commonConfigData = this.editor1.get() || {}
      this.commonTableData = this.editor2.get()
    },
    drow(el, json = {}, flage) {
      const container = document.getElementById(el)
      this[flage] = new this.$jsoneditor(container, this.options)
      this[flage].set(json)
    }
  }
}
</script>
<style>
.el-message-box{
    background-color: #f6f6f9!important;
    color: #040404 !important;
}
.el-message-box__content{
    color: #040404 !important;
}
.el-message-box > .el-button{
   color: #040404 !important;
   background-color:#4a4d5d4f!important;
}
.buttonBox{
    padding-top: 30px;
    padding-bottom: 20px;
    display: flex;
}
.editItemBox1{
 flex:1;
 height: 400px;
}
.editItemBox2{
  flex:1;
   height: 400px;
}
.editItemBox3{
  flex:2;
   height: 400px;
}
.editeTitleItem{
  text-align: center;
  font-weight: bold;
   font-family:"宋体"
}
.pageItem{
  margin-right: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.infopageItem{
    display: flex;
}
.button_hanlde{
  position:absolute;
  right: 10px;
}
</style>
