"use strict";

/**
 * 删除事件
 */
define(function (require, exports, module) {

    function handle(event) {
        const ctx = require("../../common/ctx");
        const utils = require("../../common/utils");
        const MyRecovery = require("../../common/MyRecovery");
        let curP = utils.GetEventTarget(event);
        let cNo = parseInt(curP.getAttribute("id"));

        //维护最近一次编辑的内容
        if (ctx.latestOpDoc === undefined
            || ctx.latestOpDoc === null
            || ctx.latestOpDoc.getData().getAttribute("data-id") !== curP.getAttribute("data-id")) {

            //记录最近一次删除 for 撤销
            ctx.latestOpDoc = new MyRecovery(curP.cloneNode(true), function () {
                let cNo = parseInt(this.data.getAttribute("id"))
                console.log("恢复", this.data, cNo, "  this: ", this)
                if (cNo > 1) {

                    utils.InsertAfter(this.data, document.getElementById((cNo - 1) + ""))
                } else {
                    //添加元素到首位 todo_xxx
                    // ctx.MyRoot.insertBefore(this.data, ctx.MyRoot.children[0])
                    ctx.MyRoot().insertBefore(this.data, ctx.MyRoot.children[0]);
                }

                // 恢复该元素展示
                ctx.getMapItem(cNo).setHidden(false);
            })
        }


        //如果是第一行
        let previousSibling = curP.previousSibling
        // console.log(curP, previousSibling === undefined, previousSibling.id === undefined)
        if (previousSibling === undefined || previousSibling.id === undefined) {
            //显示用户的输入内容
            ctx.showTestText();
            return
        }


        console.log('触发删除', curP.innerHTML, cNo)
        let curS = utils.GetSelection();
        // console.log("当前内容: ", curP.innerHTML, " 当前选区 :", curS)
        //处理前面没有内容,后面还有内容需要拼接到上层的场景
        if ((curS.isCollapsed && curS.anchorOffset === 0) || curP.innerHTML === '<br>') {
            let curNodeRetainHtml = curP.innerHTML
            //阻止事件传递
            utils.ProhibitDefaultEvent(event);
            //设置该元素隐藏
            ctx.MyDocMap.get(cNo).setHidden(true)
            //删除当前元素
            // curP.remove()
            curP.innerHTML = "<br/>"
            let emptyRowNoList = ctx.getMapItem("emptyRowNoList");
            if (emptyRowNoList === undefined || emptyRowNoList === null) {
                emptyRowNoList = [];
                ctx.MyDocMap.set("emptyRowNoList", emptyRowNoList);
            }
            emptyRowNoList.push(cNo);
            //拼接
            if (curNodeRetainHtml !== '<br>') {
                previousSibling.innerHTML = previousSibling.innerHTML + curNodeRetainHtml
            }

            //收起选区到一个点,光标落在一个可编辑元素上
            window.getSelection().setPosition(previousSibling, 1);
        }

        //显示用户的输入内容
        ctx.showTestText();
    }

    //导出
    exports.handle = handle;
});