<template>
  <div v-if="!activeElement.page && tab === 2" class="panel-wrap">
    <div class="panel-row" >
      <vpd-icon name="target" />
      <div class="panel-label">数据绑定方式</div>
      <!-- <div class="panel-value">{{ activeElement.buttonType }}</div> -->
      <div class="panel-value">
        <Select v-model="activeElement.dataSetType" @on-change="changeDataSetType">
          <Option
            v-for="item in dataSetTypeList"
            :value="item.value"
            :key="item.value"
          >{{ item.label }}</Option>
        </Select>
      </div>
    </div>

    <div v-show="activeElement.dataSetType == 1">
      <div class="panel-row">
        <vpd-icon name="target" />
        <div class="panel-label">API地址</div>
        <div class="panel-value">
          <Input v-model="activeElement.apiAdrr" @on-change="getTableData" />
        </div>
      </div>
    </div>
    <div v-show="activeElement.dataSetType == 2">
      <div class="panel-row" >
        <vpd-icon name="target" />
        <div class="panel-label" style="width: 100%;" v-show="activeElement.type.indexOf('braid')!=-1">braid表格数据</div>
        <div class="panel-label" style="width: 100%;" v-show="activeElement.type.indexOf('echarts')!=-1">echarts数据项</div>
        <div class="panel-label" style="width: 100%;" v-show="activeElement.type.indexOf('dataV')!=-1">dataV数据项</div>
      </div>
            <!--
            @ready="onCmReady"
            @focus="onCmFocus" 
            @input="onCmCodeChange" -->
      <div class="panel-codem">
        <vpd-icon name="target" />
        <div class="panel-value" v-show="activeElement.type.indexOf('echarts')!=-1||activeElement.type.indexOf('dataV')!=-1">
          <codemirror
            
            v-model="testStr"
            ref="codemi"
            :options="cmOptions"
            style="margin-left:4%;font-family:'Microsoft YaHei';border:1px solid #ccc;height:500px;width:400px;overflow: auto" > 
          </codemirror>
        </div>
         <!-- <div v-show="activeElement.type.indexOf('braid')!=-1">可编辑的表格</div> -->
      </div>
      <div class="panel-row">
        <vpd-icon name="target" />
        <div class="panel-value" style="display: inline-block;text-align: center">
           <!-- <Button type="warning" @click="adjust">调试</Button>&nbsp;&nbsp;&nbsp;&nbsp; -->
            <Button type="info" @click="refresh"> 刷新图表</Button>
        </div>
      </div>
    </div>
    <div v-show="activeElement.dataSetType == 3">
      <div class="panel-row">
        <vpd-icon name="target" />
        <div class="panel-label">模型名称</div>
        <div class="panel-value">
          <Select clearable v-model="activeElement.sqlModel" placeholder="请新建或选择SQL模型" style="margin-right:5px" @on-change="" >
            <Option
              v-for="item in sqlModelList"
              :value="item.value"
              :key="item.value"
            >{{ item.label }}</Option>
          </Select>
          <Icon type="md-create" size="25" v-show="sqlModelList[activeElement.sqlModel]" @click="editSqlModel(sqlModelList[activeElement.sqlModel])" style="margin-right:3px;cursor: pointer;"/>
          <Icon type="md-add-circle" size="25" @click="editSqlModel" style="cursor: pointer;"/>
        </div>
      </div>
      <div class="panel-row">
        <vpd-icon name="target" />
        <div class="panel-label">分类</div>
        <div class="panel-value">
          <Select clearable v-model="activeElement.xdata" placeholder="请选择分类" style="margin-right:5px">
            <Option
              v-for="item in xList"
              :value="item.value"
              :key="item.value"
            >{{ item.label }}</Option>
          </Select>
        </div>
      </div>
      <div class="panel-row">
        <vpd-icon name="target" />
        <div class="panel-label" style="display:block">系列</div>
      </div>
      <div class="panel-row" style="display: inline-block;width:100%">
        <Table :columns="tableHead" :data="tableData">
              <template slot-scope="scope" slot="fieldcode">
                  <Select clearable v-model="tableData[scope.index].fieldcode.value" :transfer=true style="width:100px;overflow:auto" >
                      <Option v-for="item in scope.row.fieldcode.dataTypes" :value="item.value" :key="item.value">{{ item.label }}</Option>
                  </Select>
              </template>
              <template slot-scope="scope" slot="fieldname">
                  <Input clearable v-model="tableData[scope.index].fieldname.value"  style="width: 100px" />
              </template>
        </Table >
      </div>
      <div class="panel-row">
        <vpd-icon name="target" />
        <div class="panel-value" style="display: inline-block;text-align: center">
          <!-- <Button type="info" @click="adjust">调试</Button>&nbsp;&nbsp;&nbsp;&nbsp; -->
          <!-- type="warning" -->
          <Button type="info">刷新图表</Button>
        </div>
      </div>
      <edit-modal
        v-if="showEditModal"
        :show-edit-modal="showEditModal"
        :sql-model="sqlModel"
        :model-title="modelTitle"
        @clickedhidemodal="hideEditModal"></edit-modal>
    </div>
    
  </div>
</template>

<script>
import axios from "axios";
const EditModal= () => import('./sqlModelEdit.vue')
export default {
  props: ["activeElement", "tab"],
  components: {
    EditModal
  },
  data() {
    return {
      testJson: {},  
      testStr: '',// 文本域默认显示的文本
      cmOptions: {
        // width: '100%',
        height: '500px',
        mode: { // 模式
          name: "javascript",
          json: true
        },
        // theme : "base16-dark",  // CSS样式选择
        indentUnit: 2,  // 缩进单位，默认2
        smartIndent: true,  // 是否智能缩进
        tabSize: 4,  // Tab缩进，默认4
        readOnly: false,  // 是否只读，默认false
        showCursorWhenSelecting: true,
        lineNumbers : true,  // 是否显示行号
        lineWrapping:true,
        foldGutter: true,
        gutters:["CodeMirror-linenumbers", "CodeMirror-foldgutter","CodeMirror-lint-markers"],
        //CodeMirror-lint-markers是实现语法报错功能
        lint: true,
         //全屏模式
        fullScreen:true,
 
        //括号匹配
        matchBrackets:true,
        // // codemirror options
        tabSize: 4,
        theme: "eclipse",
       //快捷键
        extraKeys:{
            "Alt-Space": "autocomplete",//ctrl-space唤起智能提示
            "F11": function(cm) {
                cm.setOption("fullScreen", !cm.getOption("fullScreen"));
            },
           "Esc": function(cm) {
               if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
            },
            "Ctrl-/": "toggleComment",
            "Ctrl-S": function () {
                $('#save').click();
            },
            "Ctrl-Z":function (editor) {
                editor.undo();
            },//undo
            "F8":function (editor) {
                editor.redo();
            },//Redo
            "F7": function autoFormat(cm) {
                var totalLines = cm.lineCount();
                cm.autoFormatRange({line:0, ch:0}, {line:totalLines});
            }//代码格式化
        }
      },
      dataSetTypeList: [
        {
          value: "1",
          label: "API拉取"
        },
        {
          value: "2",
          label: "静态JSON"
        },
        {
          value: "3",
          label: "SQL建模"
        }
      ],
      modelTitle: '新增',
      showEditModal: false,
      sqlModelList: [
        {
          value: 0,
          label: "SQL模型1",
          modelname: 'SQL模型1',
          modeldes: '模型的简介',
          alrSqlModel: [
            {
              value:1,
              label: 'sq1'
            },
            {
              value:2,
              label: 'sq2'
            }
          ],
          datasour: [{
              value: 1,
              label: '数据库表1'
            },
            {
              value: 2,
              label: '数据库表2'
          }],
          modelsetence: 'select * from population',
          tableData: [{
            
          }]

        },
        {
          value: 1,
          label: "数据模型2"
        },
        {
          value: 2,
          label: "数据模型3"
        }
      ],
      sqlmodel: {
      },
      xList:[
       {
          value: "1",
          label: "name"
        },
        {
          value: "2",
          label: "area"
        },
        {
          value: "3",
          label: "num"
        }
      ],
      tableData: [
          {
            fieldcode: {
                value:'',
                dataTypes: [
                    {
                        value: 0,
                        label: 'name'
                    },{
                        value: 1,
                        label: 'area'
                    },{
                        value: 2,
                        label: 'num'
                    }
                ],
            },
            fieldname: {
                value : ''
            },
          }],
            //表头相关数据
        tableHead: [
            {title:"字段名",slot:"fieldcode"},
            {title:"系列名",slot:"fieldname"},
            {title:"操作列",slot:"action"}
        ],
    };
  },
  watch: {
    activeElement (newV, oldV) {
      if (newV.option) { //去掉没有组件的页面
        var se=[] , ca = [], testData = {}
        for(var i = 0; i < newV.option.series.length; i++){
          se.push(newV.option.series[i].data)
        }
        for(var i = 0; i < newV.option.xAxis.length; i++){
          ca.push(newV.option.xAxis[i].data)
        }
        testData.data = {
          'categories': ca,
          'series': se
        }
        testData =  JSON.stringify(testData, null, 2)
        this.testStr = testData
      }
    },
  },
  computed: {
    codemirror() {
      // console.log(222222222222)
        
    } 
  },
  // computed: {
  //   testStr: {
  //    get: function(){
  //       var se=[] , ca = [], testData = {}
  //       // this.testJson = JSON.parse(this.testStr)
  //       for(var i = 0; i < this.activeElement.option.series.length; i++){
  //         se.push(this.activeElement.option.series[i].data)
  //       }
  //       for(var i = 0; i < this.activeElement.option.xAxis.length; i++){
  //         ca.push(this.activeElement.option.xAxis[i].data)
  //       }
  //       testData.data = {
  //         'categories': ca,
  //         'series': se
  //       }
  //     return JSON.stringify(testData)
  //     },
  //     set: function (value) {
  //       this.testStr = value;
  //       // this.testJson = JSON.parse(value)
  //       // this.refreshData()
  //       }
  //     }  
  // },
 
  methods: {
    changeDataSetType() {
      if (this.activeElement.dataSetType == 2) {
        var that = this
        setTimeout(function timer() { //延迟，不然初始化没有数据
          if (that.$refs.codemi) {
            debugger
            that.$refs.codemi.codemirror.setSize(600,500)
          }
        }, 100 )
      }
    },
    refresh(){
      //data里的数据都可以通过this.testStr获取到，computed的不可以，由里面包含的变量确定。
      this.testJson = JSON.parse(this.testStr) 
      for(var i = 0; i < this.activeElement.option.series.length; i++){
          this.activeElement.option.series[i].data = this.testJson.data.series[i]
          // console.log(this.activeElement.option.series,testJson.data.series,77777777)
        }
        for(var i = 0; i < this.activeElement.option.xAxis.length; i++){
          this.activeElement.option.xAxis[i].data = this.testJson.data.categories[i]
          // console.log(this.activeElement.option.xAxis[i].data,testJson.data.categories,9999999)
        }
        this.$emit('refactiveElement',this.activeElement);
    },
    getTableData() {
      console.log("getData");
      return axios
        .request({
          url: this.activeElement.apiAdrr,
          method: "get"
        })
        .then(res => {
          console.log(res, 7666);
        });
    },
    hideEditModal () {
      this.showEditModal = false
      this.pageChange()
    },
    editSqlModel (item) {
      this.showEditModal = true
      if (item !== undefined) {
        this.modelTitle = '编辑'
        // 类似angular.copy()深复制
        this.sqlModel = JSON.parse(JSON.stringify(item))
      } else {
        this.modelTitle = '新增'
        this.sqlModel = {}
      }
    },
    // adjust () {

    // },
    pageChange (page) {
      if (page) {
        this.currentPage = page
      }
      // const params = getAssign(this.searchCondition, { page: this.currentPage, rows: this.rows })
      // queryForPage(params).then(res => {
      //   // console.log(res, 111)
      //   this.total = res.data.total
      //   this.slmonitorcontrollerList = res.data.rows
      // })
    },
     getData : function(){
            let that = this;
            for(let i=0;i<that.tableData.length;i++){
                let row = that.tableData[i];
                let str = '第'+i+'行的数据为';
                for(let key in row){
                    if(typeof row[key].value != "undefined"){
                        str += row[key].value+"   ";
                    }
                }
                console.log(str);
            }
        },
        //添加一行的方法
        tblRowAdd : function(){
            let row = this.tableData[0];
            let newRow = JSON.parse(JSON.stringify(row));
            for(let key in newRow){
                newRow[key].value = "";
            }
            this.tableData.push(newRow);    
        },
        tblRowDel : function(index){
            if(this.tableData.length<=1){
                alert("至少留一行，如果一行都不存在，添加行的方法会有问题！");
                return false;
            }
            this.tableData.splice(index,1);
        }
  },
  created: function () {
        // //如果没有这句代码，select中初始化会是空白的，默认选中就无法实现
        // this.tableData[scope.index].dataTy.dataTypeSelected  = this.scope.row.dataTy.dataTypes[0]
        // this.tableData[scope.index].dataTy.tMapSelected  = this.scope.row.mapping.tMaps[0]
         //最后一列需要使用render函数加一列，添加数据或删除数据使用
        let header = this.tableHead;
        var that = this
        //列头添加一个+号用于添加行
        header[header.length-1].renderHeader = function(column,data){
            return column('Icon',{
                    props: {
                        type: 'md-add'
                    },
                    style: {
                        fontSize: "25px",
                        fontWeight: "bolder",
                        color: "blue",
                        cursor:"pointer"
                    },
                    on:{
                        click:function(){ // 点击事件（新增一行）
                            that.tblRowAdd();
                        }
                    }
                })
        }
        //列头添加一个-号用于删除行
        header[header.length-1].render = function(column,data){
            return column('Icon',{
                        props: {
                            type: 'md-remove'
                        },
                        style: {
                            fontSize: "25px",
                            fontWeight: "bolder",
                            color: "red",
                            cursor:"pointer"
                        },
                        on:{
                            click:function(){ // 点击事件（删除一行）
                                that.tblRowDel(data.index);
                            }
                        }
                    }
                )
        }
  },
  mounted(){
    // this.$refs.codemi.codemirror.setSize(600,500)
  }
}

</script>
<style>
.panel-codem {
  display: flex;
  font-size: 13px;
  line-height: 20px;
}
</style>
