tinymce.PluginManager.add('mfThemeWritingApply', (editor) => {
  editor.on('init', () => {
    const win = editor.getWin()

    class MfThemeWritingApply extends win.HTMLElement {
      static observedAttributes = ['data-init-text', 'data-is-response-end', 'data-is-show-renew-btn', 'data-document-title']

      constructor() {
        super()

        this.initConnect = false

        const shadowRoot = this.attachShadow({ mode: 'open' })

        const tpEl = document.createElement('template')

        tpEl.insertAdjacentHTML('beforeend', `
          <div contenteditable="false" class="container-wrapper theme-writing-apply-container">
            <div class="header">
              <span>生成内容预览</span>
            </div>
            <h3 class="document-title">标题：</h3>
            <div id="content"></div>
            <div class="footer">
              <div class="left">内容由AI生成，请注意甄别真实性</div>
              <div class="right btn-wrapper">
                <button class="btn insert-btn">插入下方</button>
                <button class="btn">全文替换</button>
                <button class="btn renew-btn">重新生成</button>
                <button class="btn cancel-btn">取消</button>
              </div>
            </div>
          </div>
        `)

        const btnWrapEl = tpEl.children[0].lastElementChild.lastElementChild

        /* 插入下方  按钮 */
        btnWrapEl.children[0].onclick = () => {
          editor.execCommand('onBtnClick', 'insertBelow')

          const divEl = document.createElement('div')
          const contentEl = this.shadowRoot.getElementById('content')
          divEl.append(...contentEl.childNodes)

          editor.dom.replace(divEl, this, false)
        }

        /* 全文替换  按钮 */
        btnWrapEl.children[1].onclick = () => {
          editor.execCommand('onBtnClick', 'fullTextReplacement')

          const divEl = document.createElement('div')
          const contentEl = this.shadowRoot.getElementById('content')
          divEl.append(...contentEl.childNodes)

          editor.resetContent('')
          editor.insertContent(`<div>${divEl.innerHTML}</div>`)
        }

        /* 重新生成  按钮 */
        btnWrapEl.children[2].onclick = () => {
          editor.execCommand('onBtnClick', 'contentRegenerate')

          editor.execCommand('creationContentRegenerate')
          editor.dom.remove(this, false)
        }

        /* 取消  按钮 */
        btnWrapEl.children[3].onclick = () => {
          editor.execCommand('onBtnClick', 'cancel')

          editor.dom.remove(this, false)
        }

        const styleEl = document.createElement('style')
        styleEl.textContent = `
          .container-wrapper {
            border-radius: 10px;
            box-shadow: 0 5px 10px 0 rgba(184, 184, 184, 0.50);
            padding: 12px;
            box-sizing: border-box;
            width: 100%;
            user-select: none;
          }
      
          .container-wrapper .header {
            color: #999;
            font-size: 12px;
            margin-bottom: 14px;
          }
      
          .container-wrapper .footer {
            margin-top: 10px;
            padding-top: 18px;
            display: flex;
            justify-content: space-between;
            border-top: solid 1px #EEE;
          }

          .container-wrapper .footer .btn-wrapper {
            display: none;
          }
      
          .container-wrapper .footer .left {
            color: #999;
            font-size: 12px;
            display: flex;
            align-items: center;
          }
      
          .container-wrapper .footer .btn {
            border-radius: 30px;
            padding: 6px 20px;
            border: 1px solid #0085ff;
            font-size: 12px;
            cursor: pointer;
            background-color: #eff7ff;
            color: #0085ff;
          }
      
          .container-wrapper .footer .right .insert-btn {
            background-color: #0085ff;
            color: #fff;
          }

          .container-wrapper .footer .right .renew-btn {
            display: none;
          }
      
          .container-wrapper .footer .right .cancel-btn {
            background-color: #fff;
            color: unset;
            border-color: #cacaca;
          }
        `
        tpEl.insertAdjacentElement('afterbegin', styleEl)

        this.shadowRoot.append(...tpEl.children)
      }
  
      connectedCallback() {
        if (!this.initConnect) {
          const contentEl = this.shadowRoot.getElementById('content')
          const contentString = editor.dom.getAttrib(this, 'data-init-text') || ''
          contentEl.innerHTML = decodeURIComponent(contentString)
          editor.dom.setAttrib(this, 'data-init-text', '')

          this.initConnect = true
        }

        // const isResponseEnd = editor.dom.getAttrib(this, 'data-is-response-end')
        // if (isResponseEnd === 'true') {
        //   const btnWrapperEl = this.shadowRoot.querySelector('.btn-wrapper')
        //   btnWrapperEl && (btnWrapperEl.style.display = 'block')
        // }
      }

      attributeChangedCallback(name, oldValue, newValue) {
        // console.log(`====( 属性 ${name}：${oldValue} --》 ${newValue} )====`)

        if (name === 'data-is-response-end') {
          const btnWrapperEl = this.shadowRoot.querySelector('.theme-writing-apply-container .btn-wrapper')

          if (newValue === 'true') {
            btnWrapperEl && (btnWrapperEl.style.display = 'block')
          } else {
            if (btnWrapperEl && btnWrapperEl.style.display !== 'none') {
              btnWrapperEl.style.display = 'none'
            }
          }
        }

        if (name === 'data-is-show-renew-btn' && newValue === 'true') {
          const renewBtnEl = this.shadowRoot.querySelector('.theme-writing-apply-container .btn-wrapper .renew-btn')
          renewBtnEl && (renewBtnEl.style.display = 'inline-block')
        }

        if (name === 'data-document-title' && newValue) {
          const titleEl = this.shadowRoot.querySelector('.theme-writing-apply-container .document-title')

          titleEl.innerHTML = `标题：${newValue}`
        }
      }
    }
    
    win.customElements.define('mf-theme-writing-apply', MfThemeWritingApply)
  
    // editor.on('keydown', (e) => {
    //   if (e.code === 'PageDown') {
    //     editor.execCommand('InsertHTML', false, `<mf-theme-writing-apply data-is-response-end="true" data-is-show-renew-btn="true"></mf-theme-writing-apply>`)

    //     editor.selection.collapse()
    //   }
      
    //   // if (e.code === 'PageUp') {
    //   //   const el = editor.dom.get('fXDZDqAKHA')
    //   //   console.log(el.shadowRoot)
    //   //   // editor.dom.setAttrib(el, 'data-text', `${decodeURIComponent(editor.dom.getAttrib(el, 'data-text') || '')}${Date.now()}`)
    //   // }
    // })
  })

  return {
    getMetadata: () => ({
      name: 'theme writing apply',
      url: 'https://marketingai-sit.gsstcloud.com',
    }),
  }
})
