import {ElMessage} from "element-plus";
import store from '@/store'
import {xcMessage} from "@/utils/xiaochan-element-plus";
import router from "@/router";

// 患者数据
export function EMRInteractive(data, editorEvent) {

    this.setEditor = (editor, runtime) => {
        this.editor = editor;
        this.runtime = runtime;
        for (let key in editorEvent) {
            editor.on(key, function (...args) {
                editorEvent[key](...args)
            })
        }
    };

    this.getEditor = () => {
        return this.editor
    }

    this.deleteElement = (params) => {
        this.editor.execute('execFn', {
            value: {
                fn: function () {
                    let EMR = this.editor.getScriptRuntime().EMR
                    let emrDoc = EMR.getDocument()
                    let components = emrDoc.getComponentsByCode(params);
                    components.forEach((component) => {
                        let view = component.target;
                        let viewDom = view.el;
                        let viewParagraphDom = viewDom.parentElement;
                        viewDom.remove();
                        if (viewParagraphDom.textContent === "") {
                            viewParagraphDom.remove()
                        }
                    })
                },
                scope: this, params: params
            }
        })
    }

    this.getRoot = () => {
        return this.editor.model.document.getRoot()
    }

    this.callMethod = (name, ...value) => {
        return this.editor[name](...value)
    }

    this.insertSnippet = (content, styles, patientData) => {
        //病历片段相关参数
        let insertContent = {
            // 内容
            value: content,
            // 样式
            styles: styles,
            isFragment: true,
            // 就是在这里填充的值
            defaultData: patientData
        }
        this.editor.execute("insertContents", insertContent);
    }

    this.getAppContext = () => {
        return {
            endpoints: {
                app: "/bdp/dataservice/api",
                his: import.meta.env.VITE_BASE_URL,
            }, input: {
                user: store.state.user.info.code,
                name: store.state.user.info.name
            }, login: {
                token: store.state.user.info.token,
                user: {
                    id: store.state.user.info.code,
                    name: store.state.user.info.name,
                }
            },
            data
        }
    };

    this.saveDocument = (value) => {
        return new Promise((resolve, reject) => {
            let document = this.editor.getDocument();
            document.properties.categoryCode = value.emrCategoryCode
            document.properties.patientId = value.patNo;
            document.properties.creator = data['编辑者编码'];
            document.properties.createTime = new Date()
            document.properties.modifier = data['编辑者编码'];
            document.properties.modifyTime = new Date()
            document._id = value.emrDocumentId
            this.runtime.saveDocument(document, (res) => {
                    console.log(res)
                    resolve(res)
                },
                (err) => {
                    xcMessage.error('保存失败' + err)
                    reject(err)
                }
            )
        })

    };

    this.deleteDocument = (documentId, cb) => {
        return new Promise((resolve, reject) => {
            this.runtime.delDocument(documentId, (res) => {
                resolve(res)
                xcMessage.success('删除成功')
            }, (err) => {
                ElMessage.error("删除失败" + err)
                reject(err)
            });


        })

    };
}

export const query = ref({
    patNo: '',
    times: 0,
    maxTimes: 1,
    state: 0
})

export function resolveRoute(val) {
    query.value = JSON.parse(window.atob(val))
}

export const emrConfig = ref({
    // 当前是否可以编辑，用来分辨出院只读，和在院患者的
    editor: true,
})


export function getEmrUrl(patNo, times) {
    let query = {
        patNo,
        times,
        state: 3,
        maxTimes: 1
    }
    let temp = JSON.stringify(query)
    return router.resolve({
        name: 'emrEditor',
        query: {
            pat: window.btoa(temp)
        }
    }).href
}

export function getInEmrUrl(patNo, times) {
    let query = {
        patNo,
        times,
        state: 2,
        maxTimes: 1
    }
    let temp = JSON.stringify(query)
    return router.resolve({
        name: 'emrEditor',
        query: {
            pat: window.btoa(temp)
        }
    }).href
}
