/** 编辑链接工具栏 */
function initLinkToolbar(me, domUtils) {
  var linkToolbar;
  //鼠标移上显示折叠
  me.addListener('mouseover', function (type, e) {
    var aLink;
    if (e.target.nodeName == 'A') {
      aLink = e.target;
    } else if(linkToolbar){
      linkToolbar.hide();
    }
    if (aLink) {
      if(aLink.innerText.trim() == '' || domUtils.isFillChar(aLink.innerText.trim()) || aLink.innerText.trim() == '​' || aLink.getAttribute('href') == '' || aLink.getAttribute('name')){
        return
      }

      if (!linkToolbar) {
        linkToolbar = new Link();
        linkToolbar.init(me, aLink);
        me.ui.getDom().appendChild(linkToolbar.resizer);
      }
      linkToolbar.show(aLink,domUtils);
    }
  });
  me.addListener('mouseleave',function (type,e) {
    var aLink;
    if (/a/i.test(e.target.nodeName)) {
      aLink = e.target;
    }
    if(aLink){
      
    }
  })
  $('body').on('mouseover', function (e) {
    if ($(e.target).hasClass('edui-editor-linkToolbar') || $(e.target).parents('.edui-editor-linkToolbar').length > 0) {
      var resizer = $(e.target).hasClass('edui-editor-linkToolbar') ? e.target : $(e.target).parents('.edui-editor-linkToolbar')[0];
      var editorId = $(resizer).parents('.edui-editor.edui-default').parent().attr('id');
      var editor = UE.getEditor(editorId);
      //列表悬浮隐藏
      $(editor.body).find('li').removeClass('hover');
      $(resizer).parents('.edui-editor.edui-default').parent().find('.listtoolList,.modifyListNum,.edui-editor-listtoolbar .hoverTips').hide();
      $(resizer).parents('.edui-editor.edui-default').parent().find('.continueListNumBtn,.startNewListBtn,.modifyListNumBtn').removeClass('disabled');
      $(resizer).parents('.edui-editor.edui-default').parent().find('.edui-editor-listtoolbar').removeClass('hover');
      if ($(editor.container).find('.edui-editor-linkToolbar')[0] == resizer) {
        $(editor.body).find('a').eq($(resizer).attr('index')).addClass('hover');
      }
    }
  })
  $(me.container).on('mouseleave', function (e) {
    if(linkToolbar){
        linkToolbar.hide();
    }
  })
  me.addListener("contentchange", function () {
    $(me.container).find('.edui-editor-linkToolbar').removeClass('hover')
  })
  //打开编辑链接弹窗
  me.openEditLinkModal = function (iframeType, linkindex, editorId) {
    //新泛雅弹窗覆盖顶部和左侧
    if (top) {
      top.postMessage('{"cmd":1,"toggle":true}', "*");
    }
    if ($('.popUeditorEditLinkShowHide').length == 0) {
      var imgPrefix = (RichTextUitl.prefix || RichTextUitl.noteDomain) + '/res/plugin/ueditor/';
      if(RichTextUitl.intranetMode){
        imgPrefix = RichTextUitl.prefix
      }
      var div = document.createElement('div');
      div.className = 'maskDiv popUeditorEditLinkShowHide editorMaskDiv';
      div.style.cssText = 'display: none;'
      div.innerHTML = '<div class="popDiv wid640 popMove">'
        + '<div class="popHead">'
        + '<a href="javascript:void(0);" class="popClose fr"><img src="' + imgPrefix + 'themes/default/images/popClose.png"></a>'
        + '<p class="fl fs18 colorDeep lh60" >' + me.getLang('popModal.link') + '</p>'
        + '</div>'
        + '<div class="het62"></div>'
        + '<div class="popWebsite_form">'
        + '<div class="popWebsite_row hyperlink-dialog-wrapper">'
        + '<span class="popWebsite_name colorIn fs14 fl">更换图标</span>'
        + '<img id="linkIcon" src="'+imgPrefix+'themes/default/images/iconLink.png"  />'
        + '<span class="changeIcon"></span>'
        + '<input id="uploadIcon" style="display:none" accept="image/png, image/jpeg" type="file">'
        + '</div> '
        + '<div class="popWebsite_row">'
        + '<span class="popWebsite_name colorIn fs14 fl linkTitle">' + me.getLang('popModal.linkTitle') + '</span>'
        + '<input type="text" name="" id="text" value="" class="popWebsite_input fl" placeholder="' + me.getLang('popModal.linkTitlePlaceholder') + '" autocomplete="off" spellcheck="false">'
        + '</div>'
        + '<div class="popWebsite_row">'
        + '<span class="popWebsite_name colorIn fs14 fl linkUrl">' + me.getLang('popModal.linkHref') + '</span>'
        + '<input type="text" name="" id="href" value="" class="popWebsite_input fl" placeholder="' + me.getLang('popModal.linkHrefPlaceholder') + '" autocomplete="off" spellcheck="false" >'
        + '<span class="popWebsite_xing fl">*</span>'
        + '<p class="popWebsite_tishi" id="msg" style="display:none;">' + me.getLang('popModal.linkErrorTips') + 'https://www.baidu.com</p>'
        + '</div>'
        + '<div class="popWebsite_row mode_row">'
        +'<span class="popWebsite_name colorIn fs14 fl linkMode">附件模式</span>'
        + '<input type="radio" id="option1" name="option" value="1" checked>'
        + '<label for="option1">卡片模式</label>'
        + '<input type="radio" id="option2" name="option" value="2">'
        + '<label for="option2">文本模式</label>'
        + '</div>'
        + '</div>'
        + '<div class="popBottom shadowBox">'
        + '<a href="javascript:void(0);" class="btn-blue fr fs14 confirm">' + me.getLang('popModal.done') + '</a>'
        + '<a href="javascript:void(0);" class="btn-white fr fs14 cancle">' + me.getLang('popModal.cancel') + '</a>'
        + '</div>'
        + '<div class="het72"></div>'
        + '</div>';
      document.body.appendChild(div);
      //  start 更换图标
      let uploadElm = document.querySelector('#uploadIcon')
      let linkIconElm = document.querySelector('#linkIcon')

      linkIconElm.addEventListener('click', () => {
        uploadElm.click()
      })
      uploadElm.addEventListener('change', () => {
        let uploadData = getUploadData(uploadElm.files[0])
        let uploadUrl = me.getActionUrl('uploadimage')
        $.ajax({
          url: uploadUrl,
          type: "post",
          processData: false,
          contentType: false,
          data: uploadData,
          dataType: 'json',
          // async:false,
          xhrFields: {
            withCredentials: true
          },
          success: function (res) {
            if (res.result && res.data) {
              uploaIcon = true
              linkIconElm.src = res.data.previewUrl
            }
          },
        });
      })
      function getUploadData(file) {
        let data = new FormData()
        if (file.name) {
          data.append("name", file.name)
        } else {
          data.append("name", (new Date()).getTime())
        }
        data.append("lastModifiedDate", file.lastModifiedDate)
        data.append("size", file.size)
        data.append("type", file.type)
        if(RichTextUitl.puid && RichTextUitl.yunToken){
          data.append("puid", RichTextUitl.puid)
          // data.append("prdid",442)
          data.append("_token", RichTextUitl.yunToken)
        }
        data.append("file", file)
        return data
      }

      //keyup 实时校验url
      $('body').on('keyup', '.popUeditorEditLinkShowHide input#href', function (e) {
        me.editLinkCheckUrl(e.target);
      })
      //编辑链接弹窗--确认修改
      $('body').on('click', '.popUeditorEditLinkShowHide .confirm', function () {
        var linkindex = $('.popUeditorEditLinkShowHide').attr('linkindex');
        var iframeType = $('.popUeditorEditLinkShowHide').attr('iframeType') || '';
        var editorId = $('.popUeditorEditLinkShowHide').attr('editorId');
        var modeType = $('.popUeditorEditLinkShowHide #option1').prop('checked')? 1 : 2;
        if ($(".popUeditorEditLinkShowHide #msg").css("display") == 'block') {
          return;
        }
        var editor = UE.getEditor(editorId);
        var link;
        if (iframeType == 'iframe') {
          link = $(editor.body).find('iframe').eq(linkindex);
        } else {
          link = $(editor.body).find('a').eq(linkindex);
        }
        var newLogo = linkIconElm.src ? linkIconElm.src : '/res/pc/images/richtext/icon_att_web.png'
        var newtitle = $('.popUeditorEditLinkShowHide #text').val();
        var newhref = $('.popUeditorEditLinkShowHide #href').val();
        if (newhref.indexOf('http://') == -1 && newhref.indexOf('https://') == -1 && newhref.indexOf('ftp://') == -1) {
          newhref = 'https://' + newhref;
        }
        if (newtitle == '') newtitle = newhref;
        link.text(newtitle);
        if(link[0].name){
          var data = RichTextUitl.b64DecodeUnicode(link[0].name);
          data.att_web.logo =  newLogo
          data.att_web.title = newtitle;
          data.att_web.url = newhref;
          link.attr('name', RichTextUitl.b64EncodeUnicode(JSON.stringify(data)))
        }
        //获取更改链接后的图标
        if (iframeType == 'iframe') {
          link[0].contentWindow.postMessage({
            'msgType': 'updateTitle',
            'name': link[0].name,
          }, "*");
        } else {
          link.attr('href', newhref);
        }
        if (iframeType == 'iframe' && modeType == 2 || iframeType != 'iframe' && modeType == 1) {
          if(!link[0].name){
            link.attr('name', RichTextUitl.b64EncodeUnicode(JSON.stringify({
              "att_web": {
                "content": "",
                "logo": newLogo,
                "showContent": 0,
                "title": newtitle,
                "url": newhref
              },
              "attachmentType": 25,
              "cid": RichTextUitl.randomUUID()
            })))
            link.attr('module','insertWeb')
            link.attr('class','dynacALink link')
          }
          me.changeAttachmentModel(link)
        }

        me.fireEvent('contentchange');
        me.fireEvent('saveScene');
        $('.popUeditorEditLinkShowHide').removeClass('maskFadeOut').hide()
        $('body').removeClass('popOverflow');
        if (top) {
          top.postMessage('{"cmd":1,"toggle":false}', "*");
        }
      });

      //编辑链接弹窗--关闭按钮
      $('body').on('click', '.popUeditorEditLinkShowHide .popClose,.popUeditorEditLinkShowHide .btn-white', function () {
        $('.popUeditorEditLinkShowHide').removeClass('maskFadeOut').hide()
        $('body').removeClass('popOverflow');
        if (top) {
          top.postMessage('{"cmd":1,"toggle":false}', "*");
        }
      });
    }
    if (iframeType == 'iframe') {
      var iframe = $(me.document.body).find('iframe').eq(linkindex);
      var data = RichTextUitl.b64DecodeUnicode(iframe[0].name);
      let logo =  data.att_web.logo ?  data.att_web.logo : '/res/pc/images/richtext/icon_att_web.png'
      $('.popUeditorEditLinkShowHide #linkIcon').attr('src', logo)
      $('.popUeditorEditLinkShowHide #text').val(data.att_web.title);
      $('.popUeditorEditLinkShowHide #href').val(data.att_web.url);
      $('.popUeditorEditLinkShowHide #option1')[0].checked = true;
    } else {
      var a = $(me.document.body).find('a').eq(linkindex);
      $('.popUeditorEditLinkShowHide #text').val(a.text());
      $('.popUeditorEditLinkShowHide #href').val(a.attr('href'));
      $('.popUeditorEditLinkShowHide #option2')[0].checked = true;
    }
    $('.popUeditorEditLinkShowHide').addClass('maskFadeOut').attr('iframeType', iframeType).attr('linkindex', linkindex).attr('editorId', editorId).show();
    $('body').addClass('popOverflow');
    $('.popUeditorEditLinkShowHide .popDiv').css({
      top: function () {
        return ($(window).height() - $(this).height()) / 2;
      },
      left: function () {
        return ($(window).width() - $(this).width()) / 2;
      },
      transform: 'none'
    });
  }
}

function Link() {
  this.editor = null;
  this.resizer = null;
  this.doc = document;
  this.Link = null;
}

Link.prototype = {
  init: function (editor) {
    var me = this;
    me.editor = editor;

    var resizer = me.resizer = document.createElement('div');
    resizer.innerHTML = '<div class="link-toolbar-wrap">' +
      '<div class="copy link">'+editor.getLang('toolbarCmds.copy') +'</div><div class="editLink">'+editor.getLang('toolbarCmds.edit') +'</div>' +
      '</div>';
    resizer.id = me.editor.ui.id + '_linkToolbar';
    resizer.className = 'edui-editor-linkToolbar edui-editor-resizer';
    resizer.style.cssText += ';z-index:' + (me.editor.options.zIndex) + ';';
    me.editor.ui.getDom().appendChild(resizer);
    me.initEvents();
  },
  initEvents: function () {
    var me = this;
    // 复制
    $(me.resizer).on('click', '.copy', function() {
      var _this = this;
      var target = me.target;
      me.editor.copyEle(this);
    })
    //编辑链接
    $(me.resizer).on('click', '.editLink', function() {
      var index = $(this).parents('.edui-editor-resizer').attr('index');
      me.editor.openEditLinkModal('a', index, me.editor.key);
    })
  },
  show: function (targetObj,domUtils) {
    var me = this;
    if (targetObj) {
      me.resizer.classList.add('hover');
      me.attachTo(targetObj,domUtils);

    }
  },
  hide: function () {
    var me = this;
    me.resizer.classList.remove('hover');
  },
  attachTo: function (targetObj,domUtils) {
    var me = this,
      target = me.target = targetObj,
      resizer = this.resizer,
      titlePos = domUtils.getXY(target),
      iframePos = domUtils.getXY(me.editor.iframe),
      editorPos = domUtils.getXY(resizer.parentNode);
    var index = $(me.editor.body).find('a').index(target);
    resizer.setAttribute('index', index);
    var clientRects = target.getClientRects();
    var width = clientRects[0].width;
    domUtils.setStyles(resizer, {
      'width': width,
      'height': 0,
      'left': 0,
      'top': iframePos.y + titlePos.y - me.editor.document.body.scrollTop - editorPos.y + 'px'
    });
  }
}

