import {
  ApiModel
} from "../../../utils/api";
const _Http = new ApiModel();
Page({
  data: {
    formats: {},
    readOnly: false,
    placeholder: '开始输入...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    showRichText: '', //富文本文件
    isDisabled: false, //只读
    closure: false, //保存截流
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  /* 回调 */
  callBack() {
    if (this.data.closure) return;
    wx.showToast({
      title: '保存成功',
    })
    this.setData({
      closure: true
    })
    this.getOpenerEventChannel().emit('richTextCallBack', {
      richText: this.data.showRichText
    })
    setTimeout(() => {
      wx.navigateBack()
    }, 500);
  },
  onLoad(options) {
    let isDisabled = false;
    if (wx.getStorageSync('userData').fisadministrator == 1) isDisabled = true;
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS,
      showRichText: decodeURIComponent(options.fintroduction),
      isDisabled
    })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)
    })
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },

  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
      that.editorCtx.setContents({
        html: that.data.showRichText //将数据写入编辑器内
      })
      event.on('resetEditor', that, that.onEditorReady.bind(that))
    }).exec()

  },
  compileText(e) {
    console.log(e.detail.html)
    this.setData({
      showRichText: e.detail.html
    })
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        console.log(res)
        //获取文件后缀
        var index = res.tempFiles[0].path.lastIndexOf(".");
        var ext = res.tempFiles[0].path.substr(index + 1);
        //文件名称
        const timestamp = Date.parse(new Date());;
        //发送请求
        wx.getFileSystemManager().readFile({
          filePath: res.tempFiles[0].path,
          success: result => {
            console.log("临时路径", result)
            //返回临时文件路径
            const fileData = result.data
            _Http.basic({
              "accesstoken": wx.getStorageSync('userData').token,
              "classname": "system.system.docManage",
              "method": "getFileName",
              "content": {
                "filename": timestamp,
                "filetype": ext,
                "ownertable": "tagents",
                "ownerid": wx.getStorageSync('userData').tagentsid,
                "ftype": "richtext"
              }
            }).then(res => {
              console.log("上传成功", res)
              if (res.msg != "成功") return wx.showToast({
                title: "文件上传失败，请稍后再试",
                icon: "none"
              });
              that.uploadFile(res, fileData)
            }).catch(err => {})
          },
          fail: console.error
        })
      }
    })
  },
  /* 上传成功反馈 */
  uploadFile(res, data) {
    console.log("文件上传")
    var that = this;
    wx.request({
      url: res.data.obsuploadurl,
      method: "PUT",
      data: data,
      header: {
        'content-type': 'application/octet-stream' // 默认值
      },
      success() {
        _Http.basic({
          "accesstoken": wx.getStorageSync('userData').token,
          "classname": "system.system.docManage",
          "method": "uploadSuccess",
          "content": {
            "obsfilename": res.data.obsfilename
          }
        }).then(res => {
          console.log("上传成功反馈", res)
          that.editorCtx.insertImage({
            src: res.data[0].fobsurl,
            data: {
              id: res.data[0].tattachmentid,
              role: 'god'
            },
            /* width: '80%', */
            success: function () {
              console.log('insert image success')
            }
          })
        }).catch(err => {
          console.log(err)
        })
      }
    })
  },
})