import axios from '@/common/services/axios-instance'
import download from '@/common/services/download'
import { sdLocalStorage } from '@/common/services/storage-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'

const DOCSUFFIX = ['wps', 'wpt', 'doc', 'docx', 'dot', 'dotx', 'docm', 'dotm']
const EXCELSUFFIX = ['xls', 'xlsx', 'xlsm', 'xlt', 'xltx', 'et', 'xltm']
const PPTSUFFIX = ['ppt', 'pptx', 'pptm', 'ppsx', 'ppsm', 'pps', 'potx', 'potm', 'dpt', 'dps']

// WPS中台：正文附件编辑、清稿、套打、转版等
let wpsDocX = {
  version: '2023.0424.01',
  createInstance() {
    let wpsdocxObj = {
      slCtl: {
        $$idx: {}, //对象属性
        SupportFormat: {
          // wps 在线编辑支持的格式
          edit: [...DOCSUFFIX, ...EXCELSUFFIX, ...PPTSUFFIX, 'pdf'],
          // wps 在线预览支持的格式
          view: [...DOCSUFFIX, 'rtf', 'txt', ...EXCELSUFFIX, 'csv', ...PPTSUFFIX, 'pdf', 'ofd'],
        },
        ErrorMessage: { NotSupport: 'FormatNotSupport' },
        checkInstall: function(argsobj) {
          wpsdocxObj.slCtl.$$idx = wpsdocxObj.slCtl.formatParams(argsobj)
          return Promise.resolve(true)
        },
        getEnv: function() {
          var platform = window.navigator.platform.toLocaleLowerCase()
          return platform.includes('win32') || platform.includes('win64') ? 'x86' : 'xc'
        },
        getRef: function(str, start, substr, seperator) {
          let pos, endpos
          pos = str.indexOf(substr, start)
          if (pos == -1) return ''
          endpos = str.indexOf(seperator, pos + 1)
          if (endpos == -1) return str.substring(pos + substr.length, str.length)
          else return str.substring(pos + substr.length, endpos)
        },
        setFileList: function(data) {
          let strlist = new Array()
          for (let i = 0; i < data.length; i++) {
            strlist.push(
              data[i].properties +
                '<FileServerUrl>' +
                fnGetFileLink(data[i].code) +
                '</FileServerUrl>' +
                '<attr>' +
                JSON.stringify(data[i].attr || {}) +
                '</attr>'
            )
          }
          if (strlist != null && strlist != undefined) {
            wpsdocxObj.slCtl.Content.Files._FileInfoString = strlist
            wpsdocxObj.slCtl.Content.Files.FileList = wpsdocxObj.slCtl.analyzeFileList(strlist) // 解析filelist
          }
        },
        analyzeFileList: function(FileInfoString) {
          let arrFileMap = FileInfoString.map(function(onefile, index) {
            let filelink = ''
            if (typeof fnGetFileLink === 'function') {
              filelink = fnGetFileLink(
                wpsdocxObj.slCtl.getRef(onefile, 0, '<file_unid>', '</file_unid>')
              )
            }
            let attr = JSON.parse(wpsdocxObj.slCtl.getRef(onefile, 0, '<attr>', '</attr>') || '{}')
            return {
              FileName: wpsdocxObj.slCtl.getRef(onefile, 0, '<file_name>', '</file_name>'),
              Unid: wpsdocxObj.slCtl.getRef(onefile, 0, '<file_unid>', '</file_unid>'),
              CatNum: wpsdocxObj.slCtl.getRef(onefile, 0, '<CatNum>', '</CatNum>'),
              Size: wpsdocxObj.slCtl.getRef(onefile, 0, '<file_size>', '</file_size>'),
              FileType: wpsdocxObj.slCtl.getRef(onefile, 0, '<filetype>', '</filetype>'),
              Completed: parseInt(
                wpsdocxObj.slCtl.getRef(onefile, 0, '<completed>', '</completed>')
              ),
              doAdd:
                wpsdocxObj.slCtl.getRef(onefile, 0, '<doAdd>', '</doAdd>') == 'True' ? true : false,
              Type: wpsdocxObj.slCtl.getFileType(
                wpsdocxObj.slCtl.getRef(onefile, 0, '<file_name>', '</file_name>')
              ),
              CreateInfo: wpsdocxObj.slCtl.getRef(onefile, 0, '<CreateInfo>', '</CreateInfo>'),
              UpdateInfo: wpsdocxObj.slCtl.getRef(onefile, 0, '<UpdateInfo>', '</UpdateInfo>'),
              TaodaInfo: wpsdocxObj.slCtl.getRef(onefile, 0, '<TaodaInfo>', '</TaodaInfo>'),
              NeedUpdate: wpsdocxObj.slCtl.getRef(onefile, 0, '<NeedUpdate>', '</NeedUpdate>'),
              AllowPrint: false,
              Editable: attr.editable ?? false,
              DocUnid: wpsdocxObj.slCtl.getRef(onefile, 0, '<doc_unid>', '</doc_unid>'),
              Uploading:
                parseInt(wpsdocxObj.slCtl.getRef(onefile, 0, '<completed>', '</completed>')) == 0 &&
                wpsdocxObj.slCtl.getRef(onefile, 0, '<doAdd>', '</doAdd>') == 'False'
                  ? true
                  : false,
              Link: filelink,
            }
          })

          return arrFileMap
        },
        formatParams: function(argsobj) {
          let $$idxtemp = {}
          let options = {}
          let UploadParam = argsobj.UploadParam || ''
          UploadParam.split('|').forEach((item) => {
            let tmpArr = item.split('=')
            options[tmpArr[0]] = tmpArr[1]
          })
          $$idxtemp.options = options
          return $$idxtemp
        },
        getFileType: function(strFileName) {
          let arrtmp = strFileName.split('.')
          return '.' + arrtmp.pop().toLowerCase()
        },
        isSupport(fname) {
          let ext = fname.match(/\.(?<ext>\w*)$/i).groups.ext
          return this.SupportFormat.edit.some((x) => ext == x)
        },
        Content: {
          Files: {
            FileList: [],
            _FileInfoString: [],
          },
          Control: {
            getFileByName: function(fname) {
              let userfile = null
              wpsdocxObj.slCtl.Content.Files.FileList.map(function(onefile, index) {
                if (onefile.Unid == fname || onefile.FileName == fname) {
                  userfile = onefile
                }
              })
              return userfile
            },
            getNewFileName(fname, suffix, index = 1) {
              const fileName = fname + (index > 1 ? `(${index})` : '') + '.' + suffix
              if (
                wpsdocxObj.slCtl.Content.Files.FileList.find((item) => item.FileName === fileName)
              ) {
                // 存在同名附件，重命名
                return wpsdocxObj.slCtl.Content.Control.getNewFileName(fname, suffix, index + 1)
              } else {
                // 附件名不重复，可使用
                return fileName.substring(0, fileName.length - suffix.length - 1)
              }
            },
            // 创建文件
            createFile: function(groupId, params) {
              return new Promise((resolve, reject) => {
                // 默认文件名
                if (!params.fileName) {
                  params.fileName = wpsdocxObj.slCtl.Content.Control.getNewFileName(
                    '新建文档',
                    params.type
                  )
                }
                // 文字（word/wps）
                if (params.type === 'docx') {
                  axios
                    .get(`api/framework/v1/wps-doc-middle-end/create-docx/${groupId}`, { params })
                    .then((res) => resolve(res.data))
                    .catch((e) => reject(e))
                } else {
                  reject('无法创建文档')
                }
              })
            },
            // 编辑
            EditFile: function(fname, fileparam, argsobj) {
              return new Promise((resolve, reject) => {
                if (!wpsdocxObj.slCtl.isSupport(fname)) {
                  reject(wpsdocxObj.slCtl.ErrorMessage.NotSupport)
                } else {
                  let { activeStepId, mode } = wpsdocxObj.slCtl.$$idx.options
                  let file = wpsdocxObj.slCtl.Content.Control.getFileByName(fname)
                  crossWindowWatcher
                    .waitForChanged(
                      `/sd-wps-editor?code=${file.Unid}&editable=${file.Editable}&mode=${mode}&activeStepId=${activeStepId}&filename=${fname}&fileStatus=${fileparam.Status}&openAuthType=${fileparam.openAuthType}&openAuthParameter=${fileparam.openAuthParameter}`
                    )
                    .then(() => {
                      resolve(true)
                    })
                }
              })
            },
            // 编辑：按URL
            EditFileByUrl: function(fname, url) {
              return new Promise((resolve, reject) => {
                crossWindowWatcher
                  .waitForChanged(
                    `/sd-wps-editor?url=${encodeURIComponent(url)}&filename=${encodeURIComponent(
                      fname
                    )}`
                  )
                  .then(() => {
                    resolve(true)
                  })
              })
            },
            getLockId: function(instId) {
              return JSON.parse(sdLocalStorage.getItem(`Lock${instId}`) || '{}').sessionId || 0
            },
            // 清稿
            QingGao: function(fname, fileparam, argsobj) {
              return new Promise((resolve, reject) => {
                if (!wpsdocxObj.slCtl.isSupport(fname)) {
                  reject(wpsdocxObj.slCtl.ErrorMessage.NotSupport)
                } else {
                  let { instId, activeStepId, groupId } = wpsdocxObj.slCtl.$$idx.options
                  let lockId = wpsdocxObj.slCtl.Content.Control.getLockId(instId)
                  let file = wpsdocxObj.slCtl.Content.Control.getFileByName(fname)
                  let environment = wpsdocxObj.slCtl.getEnv()
                  axios
                    .get(`api/framework/v1/wps-doc-middle-end/clear-draft/${groupId}`, {
                      params: {
                        fileCode: file.Unid,
                        lockId,
                        instId,
                        activeStepId,
                        environment,
                      },
                    })
                    .then(() => {
                      resolve(true)
                    })
                    .catch((e) => {
                      reject(e)
                    })
                }
              })
            },
            // 套打
            TaoDa: function(
              ModelUrl,
              ContentFieldName,
              fname,
              fileparam,
              OldDocName,
              values,
              taodainfo,
              argsobj
            ) {
              return new Promise((resolve, reject) => {
                if (!wpsdocxObj.slCtl.isSupport(fname)) {
                  reject(wpsdocxObj.slCtl.ErrorMessage.NotSupport)
                } else {
                  let { instId, activeStepId, groupId } = wpsdocxObj.slCtl.$$idx.options
                  let lockId = wpsdocxObj.slCtl.Content.Control.getLockId(instId)
                  let file = wpsdocxObj.slCtl.Content.Control.getFileByName(fname)
                  let environment = wpsdocxObj.slCtl.getEnv()

                  axios
                    .post(`api/framework/v1/wps-doc-middle-end/wrap-header/${groupId}`, values, {
                      params: {
                        fileCode: file.Unid,
                        lockId,
                        instId,
                        activeStepId,
                        readHeadFileCode:
                          ModelUrl.match(/\/download-attachments\/(?<code>.*)\?/)?.groups?.code ||
                          '',
                        environment,
                      },
                    })
                    .then(() => {
                      resolve(true)
                    })
                    .catch((e) => {
                      reject(e)
                    })
                }
              })
            },
            // 更新正文
            UpdateRegion: function(fname, values, picvalues, fileparam, argsobj) {
              return wpsdocxObj.slCtl.Content.Control.TaoDa(
                '',
                '',
                fname,
                fileparam,
                '',
                values,
                '',
                argsobj
              )
            },
            // 盖章
            GaiZhang: function(
              ModelUrl,
              ContentFieldName,
              fname,
              fileparam,
              OldDocName,
              values,
              argsobj
            ) {
              return Promise.reject('请自行定制盖章功能')
            },
            // 转版：PDF
            DOCConvertToPDF: function(fname, fileparam, argsobj) {
              return new Promise((resolve, reject) => {
                if (!wpsdocxObj.slCtl.isSupport(fname)) {
                  reject(wpsdocxObj.slCtl.ErrorMessage.NotSupport)
                } else {
                  let { instId, activeStepId, groupId } = wpsdocxObj.slCtl.$$idx.options
                  let lockId = wpsdocxObj.slCtl.Content.Control.getLockId(instId)
                  let file = wpsdocxObj.slCtl.Content.Control.getFileByName(fname)
                  let environment = wpsdocxObj.slCtl.getEnv()
                  // 接口中会自动判断当前环境，信创环境转ofd，x86环境转pdf
                  axios
                    .get(`api/framework/v1/wps-doc-middle-end/convert/${groupId}`, {
                      params: {
                        fileCode: file.Unid,
                        lockId,
                        instId,
                        activeStepId,
                        environment,
                      },
                    })
                    .then(() => {
                      resolve(true)
                    })
                    .catch((e) => {
                      reject(e)
                    })
                }
              })
            },
            // 转版：OFD
            DOCConvertToOFD: function(fname, fileparam, argsobj) {
              return wpsdocxObj.slCtl.Content.Control.DOCConvertToPDF(fname, fileparam, argsobj)
            },
            SaveFileToLocal: function(fname, fileparam, argsobj) {
              return new Promise(function(resolve, reject) {
                var userfile = wpsdocxObj.slCtl.Content.Control.getFileByName(fname)
                download(userfile.Link, fname)
                  .then(function() {
                    resolve()
                  })
                  .catch(reject)
              })
            },
            SaveMultiFiles: function(strFiles, fileparam, argsobj) {
              let { groupId } = wpsdocxObj.slCtl.$$idx.options
              return new Promise((resolve, reject) => {
                var arrFileNames = strFiles.split('|')
                var fileName = arrFileNames[0]
                var codes = arrFileNames
                  .map((v) => wpsdocxObj.slCtl.Content.Control.getFileByName(v))
                  .filter(Boolean)
                download(
                  `api/framework/v1/attachment-extend/attachments-download/multi?groupId=${groupId}&codes=${codes.map(
                    (x) => x.Unid
                  )}`,
                  `${fileName}等${codes.length}个附件.zip`
                )
                  .then((_) => resolve())
                  .catch(reject)
              })
            },
          },
        },
      },
    }

    return wpsdocxObj
  },
}

export default wpsDocX
