import { template } from "lodash"

export default {
    props: {
        code: {
            type: String
        },
        copyTemplate: {
            type: Boolean,
            default: false
        }
    },

    methods: {
        baseCopy(content) {
            try {
                const $textarea = document.createElement('textarea')
                $textarea.style = 'opacity: 0;position: fixed;top: -10000;left: -10000'
                document.body.append($textarea)
                $textarea.value = content
                $textarea.select()
                document.execCommand('copy')
                $textarea.remove()
                this.$message.success('已复制到剪贴板')
            }
            catch
            {
                this.$message.error('复制失败')
            }
        },
        onCopy() {
            this.baseCopy(this.code)
        },
        onCopyTemplate() {
            let code = '"' +
                this.code
                    // 转义双引号 => \"
                    .replace(/"/g, '\\"')
                    // 转义$ => $$
                    .replace(/\$/g, '$$$$')
                    // 替换行首 => "
                    .replace(/\n/g, '"')
                    // 替换行末 = ",
                    .replace(/\r/g, '",\r') +
                '"'
            let flag = true
            while (flag) {
                const p = code.match(/\$\${.*?}/)
                if (p && p[0]) {
                    code = code.replace(p[0], `\$\{${p[0].slice(1)}\}`)
                } else {
                    flag = false
                }
            }
            this.baseCopy(code)
        },
    },

    render() {
        const props = {
            ...this.$props,
            ...this.$attrs,
        }

        return props.code && (
            <section>
                <highlightjs {...{ props }} style={{ maxHeight: '400px', overflow: 'auto' }} />
                <div class="text-right">
                    {this.$scopedSlots.actions && this.$scopedSlots.actions().map(p => {
                        return (
                            <span>
                                {p}
                                <a-divider type="vertical" />
                            </span>
                        )
                    })}
                    {
                        this.copyTemplate &&
                        <span>
                            <a-tooltip title="复制用户片段模版">
                                <a-button size="small" type="dashed" onClick={this.onCopyTemplate} class="mb-xs">Copy template</a-button>
                            </a-tooltip>
                            <a-divider type="vertical" />
                        </span>
                    }
                    <a-tooltip title="复制内容">
                        <a-button size="small" type="dashed" onClick={this.onCopy} class="mb-xs">Copy</a-button>
                    </a-tooltip>
                </div>
            </section>
        )
    }
}