<template>
 <el-dialog
   id="jsonEditorBox"
   @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" id="sqlBox">
        <div class="editeTitleItem">SQL</div>
        <el-input
          style="width: 100%; height: 100%;border:1px solid #1160f1"
          type="textarea"
          placeholder="请输入内容"
          v-model="textareaSql">
        </el-input>
      </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-switch v-model="is_mock" active-text="模拟" inactive-text="正式"></el-switch>
              <el-button v-if="elInfo.el==='hsDyncFormComponent'" size='mini' plain type="success" @click='editAnyncColums'>修改表单</el-button>
              <el-button v-if="elInfo.el&&elInfo.el.includes('hsTable')" size='mini' plain type="success" @click='editTableColums'>修改表头</el-button>
              <el-button v-show="layout" size='mini' plain type="danger" @click='changControl(1)'>上一个</el-button>
              <el-button v-show="layout" size='mini' plain type="warning" @click='changControl(2)'>下一个</el-button>
              <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' plain  @click='lookPageLogView'>查看日志</el-button>
              <el-button size='mini' type="success" @click='downSql_'>另存</el-button>
        </div>
      </div>
      <div v-show="!lookPageLogVisible">
      <template v-if='elInfo.el=="hsLineBar"||elInfo.el=="hsPie"||elInfo.el=="hsRadar"'>
        <hsLineBar :elInfo='elInfo'  :initStyle='initStyle' :allSourceData="commonData"></hsLineBar>
      </template>
      <template  v-if='elInfo.el==="hsCarousel"'>
        <hsCarousel :initStyle='initStyle'  :allSourceData='commonData'></hsCarousel>
      </template>
      <template  v-if='elInfo.el==="hsTable"'>
        <hsTable :initStyle='initStyle'  :allSourceData='commonData'></hsTable>
      </template>
       <template  v-if='elInfo.el==="hsSelectPlus"'>
        <hsSelectPlus  :allSourceData="commonData"></hsSelectPlus>
      </template>
      </div>
    </el-row>
  </div>
      <lookPageLog @revertVersion='revertVersion_' :isrequest='isrequest' @showView='showViewLog'
        v-if="lookPageLogVisible" :elInfo='elInfo'/>
      <tbaleColumsSet v-model="dialogVisibleTbaleColums" :tableDataColums='tableDataColums'
         :allSourceData='allSourceData' :mockSourceData='mockSourceData'
         :elInfo='elInfo'
         :isEditColumns='isEditColumns'
         @submit='submitTbaleColumsSet' :isSubmitSuccessFlage='isSubmitSuccessFlage' />
      <asyncFormPropSet v-model="dialogVisibleAsyncFormColumn" :asyncFormColumns='asyncFormColumns'
          @submit='asyncFormPropSubmit'
          :elInfo='elInfo'
          :controlType='controlType' />
      <el-dialog
            title="布局类型选择"
            :visible.sync="tipAdminDialogVisible"
            width="50%"
            :append-to-body='true'
            :close-on-click-modal='false'
            >
            <span class="tipLayoutStyle">请选择保存布局的类型?</span>
            <span slot="footer" class="dialog-footer">
              <el-button size="mini" type="primary" @click="submitConfig(0)">全局</el-button>
              <el-button size="mini" type="primary" @click="submitConfig(1)">强制并全局使用</el-button>
              <el-button size="mini" type="primary" @click="submitConfig(2)">个人</el-button>
              <el-button size="mini" @click="tipAdminDialogVisible = false">取 消</el-button>
            </span>
      </el-dialog>
 </el-dialog>
</template>
<script>
import uuidv1 from 'uuid/v1'
import mockData from './initDbConfigDataJson'
import commonUtility from '../funTools/commonUtility'
import request from '../funTools/request'
import lookPageLog from './lookPageLog.vue'
import asyncFormPropSet from './asyncFormPropSet.vue'
import tbaleColumsSet from './tbaleColumsSet.vue'
// const lookPageLog = r => require.ensure([], () => r(require('./lookPageLog.vue')), 'lookPageLog')
// const asyncFormPropSet = r => require.ensure([], () => r(require('./asyncFormPropSet.vue')), 'asyncFormPropSet')
// const tbaleColumsSet = r => require.ensure([], () => r(require('./tbaleColumsSet.vue')), 'tbaleColumsSet')
export default {
  components: { lookPageLog, asyncFormPropSet, tbaleColumsSet },
  name: 'jsoneditor',
  props: {
    elInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    initStyle: {
      type: Object,
      default() {
        return {}
      }
    },
    complatData: {
      type: Array,
      default() {
        return []
      }
    },
    value: Boolean,
    layout: {},
    jsoneditorCloseAfter: {
      type: Function,
      default() {
        return () => {}
      }
    },
    jsoneditorOpenAfter: {
      type: Function,
      default() {
        return () => {}
      }
    },
    allSourceData: {},
    controlType: {},
    isEditColumns: {}
  },
  watch: {
    value(val) {
      this.dialogVisible = val
    },
    dialogVisible(val) {
      this.$emit('input', val)
    }
  },
  data() {
    return {
      options: {
        mode: 'text',
        indentation: 2,
        search: false
      },
      ideditor1: 'b' + uuidv1(),
      ideditor2: 'b' + uuidv1(),
      editor1: null,
      editor2: null,
      commonData: {},
      copyJsoneditorData: null,
      pageTitle: '配置',
      dialogVisible: false,
      editDataAll: {},
      lookPageLogVisible: false,
      isrequest: false,
      is_mock: true,
      textareaSql: '',
      dialogVisibleTbaleColums: false,
      mockSourceData: [],
      tableDataColums: [],
      dialogVisibleAsyncFormColumn: false,
      asyncFormColumns: [],
      isSubmitSuccessFlage: '',
      errorEdit: 0,
      tipAdminDialogVisible: false
    }
  },
  methods: {
    submitConfig(num) {
      this.openTips('此操作将覆盖数据库中的数据, 是否继续?', this.submitData, num)
    },
    getAppCodePageName() {
      const { db_name, is_mock, db_code } = commonUtility.parseUrlQueryString()
      const { appCode, pagename } = commonUtility.parseUrlQueryBIDyncAppcodePageName()
      return {
        appCode,
        pagename,
        db_name,
        db_code,
        is_mock
      }
    },
    getPageLogFun(parm) {
      return request.getPageLog(parm)
    },
    submitTbaleColumsSet(columnsConfig, flage) {
      const config = this.editor1.get()
      config.columnsConfig = columnsConfig
      this.editor1.set(config)
      const sql = this.textareaSql
      const data = {
        dbName: this.editDataAll.dbName,
        sAppCode: this.editDataAll.app_code,
        sPage: this.editDataAll.sPage,
        sControl: this.editDataAll.control_name,
        sConfig: config, // this.editor1.get(),
        sData: this.editor2.get(),
        sQuerySql: sql,
        elInfo: this.elInfo,
        is_mock: this.is_mock ? 1 : 0
      }
      request.runSave(data).then(() => {
        this.$message.success('设置成功')
        if (flage === 'columnStyleSet') {
          this.isSubmitSuccessFlage = 'columnStyleSet'
        } else {
          this.isSubmitSuccessFlage = 'tbaleColumsSet'
          this.dialogVisibleTbaleColums = false
        }
        this.editor1.set(config)
      })
    },
    asyncFormPropSubmit(data) {
      const config = this.editor1.get()
      config.formColumn = data
      const datas = {
        config: config
      }
      this.saveData(datas).then(res => {
        this.dialogVisibleAsyncFormColumn = false
        this.editor1.set(datas.config)
      })
    },
    saveData(datas) {
      const data = {
        dbName: this.editDataAll.dbName,
        sAppCode: this.editDataAll.app_code,
        sPage: this.editDataAll.sPage,
        sControl: this.editDataAll.control_name,
        sConfig: datas.config || this.editor1.get(),
        sData: this.editor2.get(),
        sQuerySql: this.textareaSql,
        elInfo: this.elInfo,
        is_mock: this.is_mock ? 1 : 0
      }
      return request.runSave(data)
    },
    editAnyncColums() {
      this.dialogVisibleAsyncFormColumn = true
      const config = this.editor1.get()
      this.asyncFormColumns = config.formColumn
    },
    editTableColums() {
      this.dialogVisibleTbaleColums = true
      const config = this.editor1.get()
      this.mockSourceData = this.editor2.get()
      if (config && config.columnsConfig && config.columnsConfig.length) {
        this.tableDataColums = [...config.columnsConfig]
      } else {
        this.tableDataColums = [{}]
      }
      this.tableDataColums.forEach((item, index) => {
        if (item.childs) {
          this.tableDataColums.splice(index, 1, ...item.childs)
        }
      })
    },
    // 折线图的模拟数据
    getMockData(type) {
      return mockData[type]
    },
    changControl(flage) {
      if (this.layout) {
        const list = this.layout.filter(item => item.isRequestControl)
        const currIndex = list.findIndex(item => item.control.position === this.elInfo.position)
        let nextIndex = 0
        let target = null
        if (flage === 1) { // 上一个
          if (currIndex === 0) {
            this.$message('已经是第一个了')
            return
          }
          nextIndex = currIndex - 1
          target = list[nextIndex]
        } else { // 下一个
          if (currIndex === list.length - 1) {
            this.$message('已经是最后个了')
            return
          }
          nextIndex = currIndex + 1
          target = list[nextIndex]
        }
        this.elInfo = target.control
        this.getPageInfo(target.control)
      }
    },
    lookPageLogView() {
      this.lookPageLogVisible = true
      this.isrequest = !this.isrequest
    },
    showViewLog(data) {
      this.editor1.set(data.config)
      this.editor2.set(data.sourceData)
      this.textareaSql = data.sql || ''
      this.showView()
    },
    revertVersion_(parm) {
      request.revertPageLog(parm).then(res => {
        this.getPageInfo()
        this.isrequest = !this.isrequest
      })
    },
    execSql() {
      const data = {
        sQuerySql: this.query_sql,
        dbName: this.editDataAll.dbName
      }
      request.execSql(data).then(res => {
        this.editor2.set(res)
      })
    },
    getPageInfo(info = this.elInfo) {
      const routeParams = this.getAppCodePageName()
      const { position, page, sAppCode } = info
      const app_code = sAppCode || routeParams.appCode || ''
      const sPage = page || routeParams.pagename
      const data = {
        sControl: position,
        sAppCode: app_code,
        sPage: sPage
      }
      request.getSql(data).then(data => {
        if (data && data.length) {
          this.editDataAll = data[0]
          const { app_code: app_code_, control_name, json_config, json_data, page_name, query_sql, is_mock } = this.editDataAll
          const appCode = app_code || app_code_
          if (!app_code_ || app_code_ === 'undefined') {
            this.editDataAll.app_code = app_code
          }
          this.pageTitle = `配置: AppCode: <${appCode}>---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.textareaSql = query_sql || ''
          this.is_mock = !!is_mock
        } else {
          this.initData()
        }
      })
    },
    downSql_() {
      const data = {
        dbName: this.editDataAll.dbName,
        sAppCode: this.editDataAll.app_code,
        sPage: this.editDataAll.sPage
      }
      request.downSql(data)
    },
    dialogClose() {
      this.dialogVisible = false
      this.jsoneditorCloseAfter()
    },
    dialogOpen() {
      this.revertVersion = false
      this.getPageInfo()
      this.jsoneditorOpenAfter()
    },
    initData() {
      const AppCodePageOBj = this.getAppCodePageName()
      const app_code = AppCodePageOBj.appCode
      const page_name = AppCodePageOBj.pagename
      this.pageTitle = `配置: AppCode: <${app_code}>---page_name: <${page_name}>---control_name: <${this.elInfo.position}>`
      const mockdata = this.getMockData(this.elInfo.el)
      if (!mockdata) {
        this.$message.error(this.elInfo.el + '----请配置模拟数据!')
        this.setJson({ config: {}, sourceData: [] })
        return
      }
      this.copyJsoneditorData = JSON.parse(JSON.stringify(mockdata))
      this.setJson(mockdata)
      this.textareaSql = this.copyJsoneditorData.sql
    },
    resetEdit() {
      this.openTips('是否确定撤销修改？', this.setOldJson)
    },
    setOldJson() {
      this.setJson(this.copyJsoneditorData)
    },
    submitToDb() {
      this.openTips('此操作将覆盖数据库中的数据, 是否继续?', this.submitData)
    },
    openTips(message, fun, parm) {
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          fun(parm)
        })
        .catch((e) => {
          console.log(e)
          this.$message.error('已取消-请保证json格式的完整性!,最左边没有就配置为{},中间没有就配置为[]')
        })
    },
    submitData() {
      const editor1Config = this.editor1.get()
      const editor2Config = this.editor2.get()
      this.errorEdit = 2
      let data_ = {}
      if (this.complatData.length) {
        const complatData = JSON.parse(JSON.stringify(this.complatData))
        const index = complatData.findIndex(item => {
          return item.config.id === editor1Config.id
        })
        complatData[index].config = editor1Config
        complatData[index].sourceData = editor2Config
        const sql = this.textareaSql
        const data = {
          dbName: this.editDataAll.dbName,
          sAppCode: this.editDataAll.app_code,
          sPage: this.editDataAll.sPage,
          sControl: this.editDataAll.control_name,
          sConfig: editor1Config,
          sData: complatData,
          sQuerySql: sql,
          elInfo: this.elInfo,
          is_mock: this.is_mock ? 1 : 0
        }
        data_ = data
      } else {
        let app_code = this.editDataAll.app_code
        const routeParams = this.getAppCodePageName()
        if (app_code === 'undefined' || app_code === undefined || !app_code) {
          app_code = this.elInfo.sAppCode || routeParams.appCode
        }
        const sql = this.textareaSql
        const data = {
          dbName: this.editDataAll.dbName,
          sAppCode: app_code,
          sPage: this.editDataAll.sPage,
          sControl: this.editDataAll.control_name,
          sConfig: editor1Config,
          sData: editor2Config,
          sQuerySql: sql,
          elInfo: this.elInfo,
          is_mock: this.is_mock ? 1 : 0
        }
        data_ = data
      }
      request.runSave(data_).then(() => {
        this.$message.success('设置成功')
      })
    },
    setJson(data) {
      const { config, sourceData } = JSON.parse(JSON.stringify(data))
      if (!this.editor1) {
        this.drow(this.ideditor1, config, 'editor1')
        this.drow(this.ideditor2, sourceData, 'editor2')
      } else {
        this.editor1.set(config)
        this.editor2.set(sourceData)
      }
    },
    showView() {
      this.lookPageLogVisible = false
      this.showEchart()
    },
    showEchart() {
      const config = this.editor1.get()
      const sourceData = this.editor2.get()
      this.commonData = {
        config,
        sourceData
      }
    },
    drow(el, json = {}, flage) {
      const container = document.getElementById(el)
      this[flage] = new this.$jsoneditor(container, this.options)
      this[flage].set(json)
    }
  }
}
</script>
<style scoped>
.jsonEditorBox >>> .el-message-box{
    background-color: #f6f6f9!important;
    color: #040404 !important;
}
.jsonEditorBox >>> .el-message-box__content{
    color: #040404 !important;
}
.jsonEditorBox >>> .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;
}
 #sqlBox >>> .el-textarea__inner{
  height: 400px;
}
.tipLayoutStyle{
text-align: center
}
</style>
