<template>
    <div>
        <Modal 
            v-model="currentShowEditModal"  
            scrollable 
            width="60"
            @on-cancel="hideModal">
            <!-- :loading="loading" -->
            <p slot="header">
                <span>{{modelTitle}}-SQL模型管理</span>
            </p>
            <Form 
                ref="sqlmodelForEdit" 
                :model="currentsqlmodel" 
                :rules="ruleValidate" 
                :label-width="180"
                >
				<FormItem label="SQL模型名称" prop="modelname">
					<Input v-model="currentsqlmodel.modelname" :max-length=256 placeholder="请输入SQL模型名称" class="inpw"></Input>
				</FormItem>
				<FormItem label="SQL模型简介" prop="modeldes">
					<Input v-model="currentsqlmodel.modeldes" :max-length=256 placeholder="请输入SQL模型简介" class="inpw" style="width:600px"></Input>
				</FormItem>
				<FormItem label="基于已有SQL模型新建" prop="alrSqlModel">
                    <Select v-model="currentsqlmodel.alrSqlModel" placeholder="请选择已有SQL模型新建" class="inpw" >
                        <Option v-for='item in alrSqlModels' :value='item.value' :key='item.value'>{{item.label}}</Option>
                    </Select>
				</FormItem>
                <!-- 数据库 -->
				<FormItem label="数据源" prop="datasour">
                    <Select v-model="currentsqlmodel.datasour" placeholder="请选择数据源" class="inpw" >
                        <Option v-for='item in dataSours' :value='item.value' :key='item.value'>{{item.label}}</Option>
                    </Select>
				</FormItem>
				<FormItem label="SQL语句" prop="modelsetence" style="margin-right:10%;">
                    <!-- //value编辑器内容 ；//options编辑器配置；//focus事件；//input输入时触发-->
                    
                    <div style="margin-left:4%;background-color: #F7F7F7">
                        <Button type="text" style="margin-left:5%;width:28%;background-color:none"  @click="preview"><Icon type="ios-paper-plane" />预览</Button>
                        <Button type="text" style="width:28%" @click="format"><Icon type="ios-paper" />格式化</Button>
                        <Button type="text" style="width:28%"><Icon type="md-build" />代码检查</Button>
                      
                    </div>

                    <codemirror class="CodeMirror"  
                        ref="myCm"
                        :value="code"  
                        :options="cmOptions" 
                        @ready="onCmReady"
                        @focus="onCmFocus" 
                        @input="onCmCodeChange"
                        style="margin-left:4%">
                        </codemirror>
                    <!-- <textarea id="code" :value="currentsqlmodel.modelsetence" :options="cmOptions"></textarea> -->
				</FormItem>
            </Form>
            <div>
                <Table :columns="tableHead" :data="tableData">
                    <template slot-scope="scope" slot="fieldcode">
                        <Input ref="test" v-model="tableData[scope.index].fieldcode.value"  style="width: 100px" />
                    </template>
                    <template slot-scope="scope" slot="fieldname">
                        <Input v-model="tableData[scope.index].fieldname.value"  style="width: 100px" />
                    </template>
                    <template slot-scope="scope" slot="dataTy">
                        <!-- 直接写transfer=true，不加：或v-bind:,检测出true是字符串 -->
                        <Select v-model="tableData[scope.index].dataTy.value" :transfer=true style="width:130px" >
                            <Option v-for="item in scope.row.dataTy.dataTypes" :value="item.value" :key="item.value">{{ item.label }}</Option>
                        </Select>
                    </template>
                    <template slot-scope="scope" slot="mapping">
                        <Select v-model="tableData[scope.index].mapping.value" :transfer=true style="width:130px">
                            <Option v-for="item in scope.row.mapping.tMaps" :value="item.value" :key="item.value">{{ item.label }}</Option>
                        </Select>
                    </template>
                     <!-- <template slot-scope="{ row, index }" slot="action">
                        <Button type="primary" size="small" style="margin-right: 5px" @click="show(index)">View</Button>
                        <Button type="error" size="small" @click="remove(index)">Delete</Button>
                    </template> -->
                    <!-- <template slot-scope="scope" slot="date1">
                    <date-picker type="datetime" v-model="tableData[scope.index].date1.value" style="width: 150px">
                    </date-picker>
                    </template>-->
                </Table >
            </div>                           
            <div slot="footer">
                <Button type="primary" @click="handleSubmit">保存</Button>
                <Button @click="hideModal">取消</Button>
            </div>
            <pre-modal
                v-if="showPreModal"
                :show-pre-modal="showPreModal"
                :predata="predata"
                @clickedhidemodal="hidePreModal"></pre-modal>
        </Modal>
</div>
</template>
<script>
// import { saveItem, updateItem } from './slmonitorcontroller-api-service'
import sqlFormatter from "sql-formatter"
// import 'codemirror/theme/base16-light.css'// 编辑的主题文件
const PreModal= () => import('./previewdata.vue')
export default {
    props: ['showEditModal', 'sqlModel', 'modelTitle'],
    components: {
        PreModal
    },
    data() {
        return {
            // -- 按ctrl唤起智能提示
            code: `SELECT area,num,name FROM  `,//初始默认编辑器内容
            cmOptions: {
                // 编辑器设置
                tabSize: 4,//tab大小
                mode: 'text/x-mysql',//编辑器模式支持文件
                // mode:{name: "javascript", json: true},
                // theme: 'base16-light',//编辑器主题
                lineNumbers: true,//编辑器行号
                line: true,
                dragDrop: true,//拖拽
                lineWrapping: true, //代码折叠 //没生效？？？
                matchBrackets: true,  //括号匹配
                // autofocus: true,//自动聚焦
                indentWithTabs: true,//首行缩进
                smartIndent: true,
                keyMap: 'default',//没生效？？？？？？
                extraKeys:{"Ctrl":"autocomplete"},//ctrl唤起智能提示
                // more codemirror options, 更多 codemirror 的高级配置...
                hintOptions: {tables: {
                    users: ["name", "score", "birthDate"],
                    countries: ["name", "population", "size"]
                }}
            },
            tableData: [
              {
                // date1: {
                //     value : new Date()
                // },
                dataTy: {
                    value:'',
                    dataTypes: [
                        {
                            value: 0,
                            label: '字符串'
                        },{
                            value: 1,
                            label: '整数'
                        },{
                            value: 2,
                            label: '小数'
                        },{
                            value: 3,
                            label: '日期'
                        },{
                            value: 4,
                            label: '时间'
                        }
                    ],
                },
                mapping: {
                    value:'',
                    tMaps: [
                        {
                            value: 0,
                            label: '不映射'
                        }
                    ],
                
                },
                fieldcode: {
                    value : ''
                },
                fieldname: {
                    value : ''
                },
              }],
               //表头相关数据
            tableHead: [
                {title:"字段",slot:"fieldcode"},
                {title:"展示名称",slot:"fieldname"},
                {title:"数据类型",slot:"dataTy"},
                {title:"数据值映射绑定",slot:"mapping"},
                // {title:"操作列"}
                {title:"操作列",slot:"action"}
            ],
            // loading: false,
            currentShowEditModal: this.showEditModal,
            currentsqlmodel: this.sqlModel,
            ruleValidate: {
                modelname: [{ required: true, message: 'SQL模型名称不能为空', trigger: 'blur' }],
				datasour: [{ required: true, message: '数据源不能为空', trigger: 'blur' }],
				modelsetence: [{ required: true, message: 'SQL语句不能为空', trigger: 'blur' }]
            },
            showPreModal: false,
            dataSours: [{
                value: 1,
                label: '供热数据库'
            },{
                value: 2,
                label: '供水数据库'
            },{
                value: 3,
                label: '照明数据库'
            }],
            alrSqlModels: [
               {
                value: 1,
                label: 'db1'
            },{
                value: 2,
                label: 'db2'
            },{
                value: 3,
                label: 'db3'
            }],
            predata:[
                {
                   area:'河北省',
                   num: 100
                },
                 {
                   area:'黑龙江省',
                   num: 20
                },
                 {
                   area:'辽宁省',
                   num: 80
                }
            ]
        }
    },
    computed: {
        codemirror() {
            // console.log(this.$refs.codemi.codemirror.lineCount()) 
        }      
    },
    watch: {
        showEditModal (newV, oldV) {
            this.currentShowEditModal = newV
        },
        currentsqlmodel (newV, oldV) {
            this.currentsqlmodel = newV
        }
    },
    methods: {
        onCmReady(cm) {
            console.log('the editor is readied!', cm)
        },
        onCmFocus(cm) {
            console.log('the editor is focus!', cm)
        },
        onCmCodeChange(newCode) {
            console.log('this is new code', newCode)
            this.code = newCode
        },
        clearTextArea (){
            this.editor.$refs.myCm.codemirror.setValue('')
        },
        hidePreModal () {
            this.showPreModal = false
        },
        format(){
            let sqlContent="";
            sqlContent=this.$refs.myCm.codemirror.getValue();
            console.log(sqlContent,sqlFormatter.format(sqlContent),888)
            this.$refs.myCm.codemirror.setValue(sqlFormatter.format(sqlContent))
        },  
        setMirror () {
            this.$refs.myCm.codemirror.setOption('lineWrapping', true);
            this.$refs.myCm.codemirror.setSize(600,500)//设置编辑框的尺寸
            //这里可以写方法，比如下面的设置内容
            this.$refs.myCm.codemirror.setValue(this.code + ' '+ 'sr_city_content')
            // 修改的快捷键，测试用
            this.$refs.myCm.codemirror.setOption("extraKeys",{
                 "Tab": (cm) => {
                     
                    if (cm.getSelection()) {      // 存在文本选择
                        cm.indentSelection('add');    // 正向缩进文本
                    } else {                    // 无文本选择  
                        //cm.indentLine(cm.getCursor().line, "add");  // 整行缩进 不符合预期
                        cm.replaceSelection(Array(cm.getOption("indentUnit") + 1).join(" "), "end", "+input");  // 光标处插入 indentUnit 个空格
                    }   
                },  
                "Shift-Tab": (cm) => {              // 反向缩进   
                    if (cm.getSelection()) {
                        cm.indentSelection('subtract');  // 反向缩进
                    } else {
                        // cm.indentLine(cm.getCursor().line, "subtract");  // 直接缩进整行
                        const cursor = cm.getCursor();
                        cm.setCursor({line: cursor.line, ch: cursor.ch - 4});  // 光标回退 indexUnit 字符
                    }   
                    return ;
                },  
                // "Tab": function(cm){
                //     var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
                //     cm.replaceSelection(spaces);
                // },
            //     "F11": function(cm) {
            //         cm.setOption("fullScreen", !cm.getOption("fullScreen"));
            //     },
            //     "Esc": function(cm) {
            //          if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
            //    }
            });
            this.$refs.myCm.codemirror.setOption("keyMap",{
                'Backspace': function (cm) {
                    console.log(cm,898989)
                    var ch = cm.getTokenAt(cm.getCursor());
                    if(ch.type == 'field') {
                        cm.execCommand('delWordBefore');
                        cm.execCommand('delCharBefore');
                    } else {
                        cm.execCommand('delCharBefore');
                    }
                },

            });
            return this.$refs.myCm.codemirror
      
        },     
        hideModal() {
            this.$emit("clickedhidemodal", false);
        },
        handleSubmit () {
            // this.loading = true
            this.$refs['sqlmodelForEdit'].validate((valid) => {
                if (valid) {
                    if (this.modelTitle == '新增') {
                        saveItem(this.currentsqlmodel).then(res => {
                            // this.loading = false
                            if (res.data.code == 0) {
                                this.$Message.success('添加成功!');
                            } else {
                                this.$Message.error(res.data.message);
                            }
                            this.$emit("clickedhidemodal", false)
                        })
                    } else {
                        updateItem(this.currentsqlmodel).then(res => {
                            // this.loading = false
                            if (res.data.code == 0) {
                                this.$Message.success('修改成功!');
                            } else {
                                this.$Message.error(res.data.message);
                            }
                            this.$emit("clickedhidemodal", false)
                        })
                    }
                    
                } else {
                    this.$Message.error('请注意格式!');
                }
            })
        },
        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);
        },
        preview : function(){
            this.showPreModal = true
        },
    },
    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 () {
         console.log('this is current codemirror object', this.codemirror)
         this.setMirror()
         this.format()
        // you can use this.codemirror to do something...
        // this.$refs.myCm.codemirror.getValue()//设置值
        
       
  }
}
</script>

<style>
/* @import '../../assets/icon/iconfont.css'; */
.inpw{
    width: 300px;
    margin-left:4%
}
</style>
