<template>
    <BaseModal title="配置数据集" :width="800">
        <Row>
            <Col span="6">数据集名称:</Col>
            <Col span="18">
                <Input v-model="data.name" />
            </Col>
        </Row>
        <div>SQL</div>
        <textarea ref="sqlEditor"></textarea>
        <Row>
            <Col span="6">权限控制:</Col>
            <Col span="18">
                <Select v-model="data.permissionProvider" @on-change="changeProvider" clearable>
                    <Option v-for="p in permissionProviders" :value="p.id" :key="p.id">{{p.name}}</Option>
                </Select>

                <div>{{permissionInfo}}</div>
            </Col>
        </Row>
        <Row>
            <Col span="6">权限控制参数:</Col>
            <Col span="18">
                <Input v-model="data.permissionParamMap" clearable/>
            </Col>
        </Row>
        <div>查询参数(SQL中用到的参数)</div>
        <Button @click="addSqlParam">添加参数</Button>
        <Table border :columns="columns" :data="parameters" height="160"></Table>
    </BaseModal>
</template>
<script>
import ApiDesigner from '@/api/designer'
import SqlParametersDialog from './SqlParametersDialog'
import CodeMirror from 'codemirror'
import 'codemirror/addon/hint/show-hint.js'
import 'codemirror/addon/lint/lint.js'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/mode/sql/sql'
import Utils from '@/libs/utils'

export default {
    name: 'DatasetDialog',
    data() {
        return {
            permissionProviders: [],
            permissionInfo: '',
            columns: [
                {
                    title: '参数名',
                    key: 'name',
                },
                {
                    title: '数据类型',
                    key: 'type',
                },
                {
                    title: '默认值',
                    key: 'defaultValue',
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 150,
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                    },
                                    style: {
                                        marginRight: '5px',
                                    },
                                    on: {
                                        click: () => {
                                            this.editSqlParam(params.index)
                                        },
                                    },
                                },
                                '修改'
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'error',
                                        size: 'small',
                                    },
                                    on: {
                                        click: () => {
                                            this.delSqlParam(params.index)
                                        },
                                    },
                                },
                                '删除'
                            ),
                        ])
                    },
                },
            ],
            parameters: [],
            codeMirror: null,
        }
    },
    components: {},
    methods: {
        changeProvider(provider) {
            let p = this.permissionProviders.find((elem) => {
                return elem.id === provider
            })

            this.permissionInfo = p ? p.desc : ''
        },
        buildScriptLintFunction() {
            return function (text, updateLinting, options, editor) {
                if (text === '') {
                    updateLinting(editor, [])
                    return
                }
                if (!text || text === '') {
                    return
                }
                const prefix = text.substring(0, 2),
                    suffix = text.substring(text.length - 1, text.length)
                if (prefix === '${' && suffix === '}') {
                    text = text.substring(2, text.length - 1)
                } else {
                    return
                }

                ApiDesigner.scriptValidate(text).then(function (result) {
                    if (result) {
                        let message = []
                        for (let item of result) {
                            let m = {
                                from: {
                                    line: item.line - 1,
                                },
                                to: {
                                    line: item.line - 1,
                                },
                                message: item.message,
                            }

                            message.push(m)
                        }
                        updateLinting(editor, message)
                    } else {
                        updateLinting(editor, [])
                    }
                })
            }
        },
        beforeOk() {
            this.data.sql = this.codeMirror.getValue()
            this.data.parameters = this.parameters

            return true
        },

        addSqlParam() {
            Utils.showModal(SqlParametersDialog, {
                data: {
                    data: {},
                },
                methods: {
                    afterOk: (data) => {
                        this.parameters.push(data)
                    },
                },
            })
        },
        editSqlParam(index) {
            Utils.showModal(SqlParametersDialog, {
                data: {
                    data: Object.assign({}, this.parameters[index]),
                },
                methods: {
                    afterOk: (data) => {
                        this.parameters.splice(index, 1, data)
                    },
                },
            })
        },
        delSqlParam(index) {
            this.parameters.splice(index, 1)
        },
    },
    async created() {
        await ApiDesigner.getPermissionProviders().then((json) => {
            this.permissionProviders = json
        })

        this.changeProvider(this.data.permissionProvider)
    },
    mounted() {
        setTimeout(() => {
            this.codeMirror = CodeMirror.fromTextArea(this.$refs.sqlEditor, {
                mode: 'text/x-sql',
                lineNumbers: true,
                coverGutterNextToScrollbar: true,
                gutters: ['CodeMirror-linenumbers', 'CodeMirror-lint-markers'],
                lint: {
                    getAnnotations: this.buildScriptLintFunction(),
                    async: true,
                },
            })

            this.codeMirror.setSize('100%', '180px')

            if (this.data.sql) {
                this.codeMirror.setValue(this.data.sql)
            }
        }, 500)

        this.parameters = this.data.parameters || []
    },
}
</script>
<style>
.cm-s-default {
    border: 1px solid #e9eaec;
}
</style>
