<template>
  <div
    id="app"
    :style="{
      background: variables[`${style}-container-background`],
      '--background': variables[`${style}-top-bar-background`],
      '--menuColor': variables[`${style}-menu-color`],
      '--topColor': variables[`${style}-tab-color`],
    }"
  >
    <keep-alive :include="keepaliveIncludes">
      <router-view />
    </keep-alive>
    <Watermark :text="username" />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { keepaliveIncludes } from '@/utils/handleRoutes.js'
  import { getMainByDefKey, getCode } from '@/api/appCenter.js'
  import variables from '@/styles/variables.scss'
  import _ from 'lodash'
  import * as dd from 'dingtalk-jsapi'
  import Watermark from '@/components/commons/Watermark.vue'
  export default {
    name: 'App',
    components: {
      Watermark,
    },
    computed: {
      ...mapGetters({
        style: 'settings/style',
        themeColor: 'settings/themeColor',
        username: 'user/username',
      }),
      variables() {
        return variables
      },
      keepaliveIncludes() {
        return keepaliveIncludes
      },
    },
    data() {
      return {
        isDingIntent: true,
      }
    },
    created() {
      // 确保用户信息已加载
      if (!this.username && this.$store.state.user.accessToken) {
        this.$store.dispatch('user/getUserInfo')
      }
      // 因为resize事件在整个项目中只能监听一次，所以这里通过全局广播发送这个事件
      window.onresize = _.debounce(() => {
        this.$root.$emit('resize')
      }, 300)
      String.prototype.getValue = function (parm) {
        var reg = new RegExp('(^|&)' + parm + '=([^&]*)(&|$)')
        var r = this.substr(this.indexOf('?') + 1).match(reg)
        if (r != null) return unescape(r[2])
        return null
      }

      var url = decodeURI(window.location.href)
      url = decodeURI(url)
      console.log(url)
      var corpId = url.getValue('corpId') //钉钉企业id
      var taskId = url.getValue('taskId') //任务id
      var instId = url.getValue('instId') //实例id
      var todoId = url.getValue('todoId') //实例id
      var messageId = url.getValue('messageId') //实例id
      var appId = url.getValue('appId') //应用id
      console.log('corpId======' + corpId)
      console.log('taskId======' + taskId)
      console.log('instId======' + instId)
      console.log('todoId======' + todoId)
      console.log('messageId======' + messageId)
      console.log('appId======' + appId)
      var dateEnti = {}
      if (taskId || todoId || messageId || appId) {
        dateEnti = {
          corpId: corpId,
          taskId: taskId,
          instId: instId,
          todoId: todoId,
          messageId: messageId,
          appId: appId,
        }
        var that = this
        dd.runtime.permission.requestAuthCode({
          corpId: corpId, // 企业id
          onSuccess: function (info) {
            console.log(info.code)
            that.getDingUserInfo(info.code, corpId, appId, dateEnti)
          },
          onFail: function (error) {},
        })
      } else {
        this.isDingIntent = false
      }
    },
    methods: {
      /**
       * 获取用户信息并且写入缓存
       * @param code
       * @param corpId
       * @param appId
       */
      getDingUserInfo(code, corpId, appId, dateEnti) {
        console.log(dateEnti)
        let url = `${window.context.auth}/sso/getDingUserByCode?code=${code}&corpId=${corpId}&appId=${appId}`
        let _this = this
        this.$http.get(url).then((resp) => {
          console.log(resp)
          let code = resp.code
          if (code == '200') {
            let value = resp.value
            this.$store.dispatch('user/getDingUserByCodeFun', value)
            if (dateEnti.taskId) {
              this.$router.push({
                path: '/matter/approvalForm',
                query: {
                  instId: dateEnti.instId,
                  taskId: dateEnti.taskId,
                  isGetApprovalBtn: true,
                  type: 'fromTodoList',
                  // key:'onlyOneTask'
                },
              })
            }
            if (dateEnti.appId) {
              this.getAppInfo(appId)
            }

            if (dateEnti.todoId) {
              this.getTodoDetailById(dateEnti)
            }
            if (dateEnti.messageId) {
              this.messageReceiver(dateEnti)
            }
          }
        })
      },

      /**
       * 获取待办详细信息
       * @param code
       * @param corpId
       * @param appId
       */
      getTodoDetailById(dateEnti) {
        console.log(dateEnti)
        let url = `${window.context.bpmRunTime}/runtime/todo/v1/getDetailById?id=${dateEnti.todoId}`
        let _this = this
        this.$http.get(url).then((resp) => {
          console.log(resp)
          let code1 = resp.code
          if (code1 == '200') {
            let value = resp.value
            _this.getCodeFun(value, '0')
          }
        })
      },
      getCodeFun(resp, type) {
        getCode().then((res) => {
          if (res.code === 200) {
            let code = res.value
            if (type == '1') {
              var sourceClient = 'PC'
              var param = resp.messageParams
              var preFlag = '?'
              var url = resp.ownerSourceCurAppCallback
              if (url.indexOf('?') > 0) {
                preFlag = '&'
              }
              var resultUrl =
                url +
                preFlag +
                'code=' +
                code +
                '&sourceClient=' +
                sourceClient +
                '&pageData=' +
                encodeURIComponent(param)
              window.location.href = resultUrl
            }
            if (type == '0') {
              var sourceClient = 'PC'
              var param = resp.messageParams
              var preFlag = '?'
              var url = resp.ownerSourceCurAppCallback
              if (url.indexOf('?') > 0) {
                preFlag = '&'
              }
              var resultUrl =
                url +
                preFlag +
                'code=' +
                code +
                '&sourceClient=' +
                sourceClient +
                '&pageData=' +
                encodeURIComponent(param)
              window.location.href = resultUrl
            }
          }
        })
      },
      /**
       * 获取待办详细信息
       * @param code
       * @param corpId
       * @param appId
       */
      messageReceiver(dateEnti) {
        console.log(dateEnti)
        let url = `${window.context.portal}/innermsg/messageReceiver/v1/get?id=${dateEnti.messageId}`
        let _this = this
        this.$http.get(url).then((resp) => {
          console.log(resp)
          let messageSourceType = resp.messageSourceType
          if (messageSourceType == '1') {
            window.location.href = resp.messageUrl
          } else if (
            messageSourceType == '3' ||
            messageSourceType == '4' ||
            messageSourceType == '5' ||
            messageSourceType == '6'
          ) {
            _this.getCodeFun(resp, '1')
          }
        })
      },
      /**
       * 根据appid获取app数据
       * @param appId
       */
      getAppInfo(appId) {
        let url = `${window.context.portal}/portal/sysApp/v1/getDetail?id=${appId}`
        let _this = this
        this.$http.get(url).then((resp) => {
          console.log(resp)
          let code = resp.status
          if (code == '200') {
            let value = resp.data
            _this.clickGrid(value)
          }
        })
      },
      async startApp(app) {
        //1常规应用 2数据报表 3自定义视图 4图表 6表单 7模块 8启动流程
        ///appContent/:type/:id/:otherId/:appName
        let url = ''
        let prefix = window.context.front
        if (app.type == 4) {
          let content = JSON.parse(app.content)
          url = `/appContent?type=${app.type}&id=${content.id}&appName=${app.name}`
        } else if (app.type === 2) {
          let content = JSON.parse(app.content)
          url = `/appContent?type=${app.type}&id=${content.alias}&appName=${app.name}`
        } else if (app.type === 3) {
          let content = JSON.parse(app.content)
          url = `/appContent?type=${app.type}&id=${content.id}&appName=${app.name}`
        } else if (app.type === 1) {
          url = `/appContent?type=${app.type}&id=${app.id}&appName=${app.name}`
        } else if (app.type === 6) {
          let content = JSON.parse(app.content)
          url = `/appContent?type=${app.type}&id=${content.id}&appName=${app.name}`
        } else if (app.type === 7) {
          let content = JSON.parse(app.content)
          url = `/appContent?type=${app.type}&id=${content.id}&appName=${app.name}`
        } else if (app.type === 8) {
          let content = JSON.parse(app.content)
          let resp = {}
          if (content.key) {
            resp = await getMainByDefKey(content.key)
            url = `/matter/startProcess?defId=${resp.id}&name=${content.name}`
          } else {
            url = `/matter/startProcess?defId=${content.id}&name=${content.name}`
          }
        } else if (app.type === 9) {
          let content = JSON.parse(app.content)
          url = `/appContent?type=${app.type}&id=${content.id}&appName=${app.name}&alias=${content.alias}`
        } else if (app.type === 5) {
          url = app.content
          if (app.localAuthCode === 1) {
            this.getCode(url)
          } else {
            window.open(url, '_blank')
          }
          return
        }
        if (url) {
          this.$router.push({ path: url })
        }
      },
    },
  }
</script>
<style lang="scss">
  #app {
    height: 100%;
  }
  .el-button--primary {
    background-color: #2563eb;
    border-color: #2563eb;
  }
</style>
