import axios from '@/common/services/axios-instance'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import eventBus from '@/common/services/event-bus'
import loginService from '@/login/login-service'
import SdProcessedSteps from '@/flowcenter/sd-processed-steps.vue'
import Vue from 'vue'
import { sdSessionStorage } from '@/common/services/storage-service'
import { router } from '@/common/router-ready'
import store from '@/common/store'
import { getUserInfo } from '@/common/store-mixin'
class TodoListService {
  getList({ current, pageSize, listType, ...rest }) {
    this.loading = true
    return axios
      .post('api/framework/v1/user-tasks/' + listType + '-with-trustor', {
        startPosition: (current - 1) * pageSize,
        maxResults: pageSize,
        ...rest,
      })
      .then((res) => {
        return res.data
      })
  }

  makePath(task, listType) {
    // start 解决把A起草的数据干预到起草环节时发给B，导致A和B都能在列表中看到，但A打不开。需要在列表中配置当前处理人
    const userName = getUserInfo()?.name
    const activeUserName = task.CURRENT_ACTIVE_USERS_NAME
    if (activeUserName && userName !== activeUserName) {
      task.openLink = ''
      listType = 'todo'
    }
    // end
    if (task.openLink) {
      return task.openLink?.split('task-form-process/')[1] + '/' + task[task.openParam]
    }
    // 下面是兼容之前的
    if (listType === 'todo') {
      if (task.openMode === 1) {
        return 'todo-pages/' + task.id
      } else {
        return 'done-pages/' + task.instId
      }
    }
    if (
      ['replied-inform', 'inform', 'informleader', 'communication', 'commFeedback'].includes(
        listType
      )
    ) {
      return 'pages/' + listType + '/' + task.id
    }
    if (
      [
        'processed',
        'application',
        'completed',
        'application-completed',
        'application-inprocess',
        'attention',
        'processing',
      ].includes(listType)
    ) {
      return 'done-pages/' + task.instId
    }
    if (['draft', 'inform', 'informleader'].includes(listType)) {
      return 'pages/' + listType + '/' + task.instId
    }
    if (['trash'].includes(listType)) {
      return 'done-pages/' + task.instId
    }
    // 催办提醒,到期提醒
    if (['reminder', 'searchtodo'].includes(listType)) {
      return 'todo-pages/' + task.todoId
    }
    // 到期提醒
    if (['expiry'].includes(listType)) {
      if (task.openMode === '1') {
        return 'todo-pages/' + task.todoId
      } else {
        return 'done-pages/' + task.instId
      }
    }
  }

  // 获取领导待批列表
  getLeadersApproved(params) {
    return axios
      .post(`api/framework/v1/user-tasks/todo/taskinfos`, params, {
        headers: {
          'Content-Type': 'application/json',
        },
      })
      .then(function (res) {
        return res.data
      })
  }

  getProcessedSteps(params) {
    return axios.post('api/framework/v1/hd-processed/processed-steps', params)
  }

  openTaskItem(task, listType, target) {
    debugger
    if (task.module === 'icWork' && task.link !== '')
      return crossWindowWatcher.waitForChanged(task.link + '&todoId=' + task.id)
    if (!task.wfBusiId) return this.spliceurlToOpen(task, listType, target)
    else if (task.wfBusiId && task.pcAddr) {
      let url = `/sd-interapp-processed-steps?wfBusiId=${task.wfBusiId}&srcTrustId=${task.srcTrustId}&listType=${listType}`
      let pcAddr = task.pcAddr.split('#')[0]
      if (pcAddr.substr(-1) !== '/') pcAddr = pcAddr + '/'
      url =
        pcAddr +
        `#/sd-thirdparty-login?redirect=${encodeURIComponent(url)}&local_token=${encodeURIComponent(
          loginService.getTokens().access_token
        )}`
      return crossWindowWatcher.waitForChanged(url, task.srcTrustId, target)
    } else return this.searchProcessedSteps(task, listType, target)
  }

  searchProcessedSteps(task, listType, target) {
    const params = {
      wfBusiId: task.wfBusiId,
      mainInstId: task.instId,
      srcTrustId: task.srcTrustId,
    }
    const _this = this
    return this.getProcessedSteps(params).then((res) => {
      res.data?.forEach((item) => {
        item.srcTrustId = task.srcTrustId
        item.title = task.title
        item.key = item.instId
      })
      if (res.data?.length > 1) {
        const mixin = {
          data() {
            return {
              processedSteps: res.data,
            }
          },
          methods: {
            openRecord(record) {
              this.processedVisible = false
              _this.spliceurlToOpen(record, listType, target)
            },
          },
        }
        const mixins = { mixins: [mixin] }
        const c = { ...SdProcessedSteps, ...mixins, store }
        const vm = new Vue(c).$mount()
        document.body.appendChild(vm.$el)
      } else return this.spliceurlToOpen(res.data[0], listType, target)
    })
  }

  spliceurlToOpen(task, listType, target) {
    const path = router.currentRoute.fullPath
    if (
      task.openMode === 1 &&
      sdSessionStorage.getItem('ApprovalMode') === '2' &&
      path.indexOf('sd-easy-webflow') === -1
    ) {
      return crossWindowWatcher.waitForChanged(`/sd-easy-webflow?id=${task.id}`, task.srcTrustId)
    }
    let url = `/sd-webflow/${this.makePath(task, listType)}`
    const setUrl = (value) => (url = value)
    return eventBus.emit('sdTaskItemClick', task, { setUrl }).then((evt) => {
      if (evt.defaultPrevented) return
      if (task.pcAddr && !url.startsWith('http')) {
        let pcAddr = task.pcAddr.split('#')[0]
        if (pcAddr.substr(-1) !== '/') pcAddr = pcAddr + '/'
        url =
          pcAddr +
          `#/sd-thirdparty-login?redirect=${encodeURIComponent(
            url
          )}&local_token=${encodeURIComponent(loginService.getTokens().access_token)}`
      }
      return crossWindowWatcher.waitForChanged(url, task.srcTrustId, target)
    })
  }

  batchSubmit(params, srcTrustId) {
    const headers = {
      'Content-Type': 'application/json',
    }
    if (srcTrustId) {
      headers['X-RUN-AS'] = srcTrustId
    }
    return axios
      .post('api/framework/v1/todo/batch-submit', params, {
        headers,
      })
      .then(function (res) {
        return res.data
      })
  }
}

export default new TodoListService()
