import Vue from 'vue'
import { wxRequest } from './aWxRequest'
import qs from 'qs'
import router from '../router'

const zlog = console.log.bind(console)

// Z-BasicInfo
let INFO = {
  // corpId: 'wwd1cdbca7b8b2b6c4',
  // agentId: '1000015',
  corpId: 'ww4df265003b43fa0d',
  agentId: '1000033',
}

async function getXToken() {
  let postData = {
    corpId: INFO.corpId,
    agentId: INFO.agentId,
  }
  await wxRequest('/workWx/auth/oauth2/getAccessToken', qs.stringify(postData)).then(res => {
    if (res.result === 'success') {
      sessionStorage.setItem('XToken', res.data)
    } else {
      // this.$message({
      //   message: res.errorMsg,
      //   type: 'error'
      // })
    }
  }).catch(err => {
    console.log(err,'err');    
  })
}

function isIosOrAndroid() {
  // alert('isIosOrAndroid')
  let u = navigator.userAgent;
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
  let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
  let isStr = ''
  if (isAndroid) {
    isStr = 'android'
  }
  if (isiOS) {
    isStr = 'ios'
  }
  return isStr
}

Vue.prototype.getAgentAuth = function () {
  // alert(location.href)
  let postData = {
    // businessId: sessionStorage.getItem('businessId'),
    // pageUrl: encodeURIComponent(this.isIosOrAndroid() === 'android' ? location.href.split('#')[0] : window.initUrl)
    pageUrl: encodeURIComponent(location.href.split('#')[0])
  }
  // alert(`--->zCommon.js: postData =${JSON.stringify(postData)}`)

  let header = {
    token: sessionStorage.getItem('XToken'),
    corpId: INFO.corpId,
    agentId: INFO.agentId,
  }
  // alert(`--->zCommon.js: header =${JSON.stringify(header)}`)

  wxRequest('/workWx/auth/base/getJsSdkSignature', qs.stringify(postData), header)
    .then(res => {
      if (res.result === 'success') {
        let config = res.data
        wx.config({
          beta: true,
          debug: false, //调试的时候可以开启
          appId: config.jsApiSignature.appId, // 必填，公众号的唯一标识
          timestamp: config.jsApiSignature.timestamp, // 必填，生成签名的时间戳
          nonceStr: config.jsApiSignature.nonceStr, // 必填，生成签名的随机串
          signature: config.jsApiSignature.signature, // 必填，签名
          // 根据自己的需求，填写 jsapilist 内容
          jsApiList: ['agentConfig', 'sendChatMessage','selectExternalContact','shareToExternalContact'],
          success: function(res) {
          },
          fail: function(err) {
          }
        })

        //  alert(`--->zCommon.js: getJsSdkSignature: then: wx.config: end.`)
        wx.ready(function () {
          zlog('%c--->getAgentAuth: getJsSdkSignature: Ready.', 'color: red;')
          // alert(`--->zCommon.js: getJsSdkSignature: then: wx.ready: IN.`)

          // JS-SDK配置信息验证失败时会进入此方法
          wx.error(function (res) {
            // alert('sdk配置失败')
          })

          // 配置成功后验证API接口在当前客户端是否支持：判断当前客户端版本是否支持指定JS接口
          wx.checkJsApi(
            {
              jsApiList: ['config', 'agentConfig', 'sendChatMessage','selectExternalContact','shareToExternalContact'],
              success: function (res) {
                if (res.errMsg != "checkJsApi:ok") {
                  // alert("JS-SDK接口检测失败:" + JSON.stringify(res));
                  return false;
                } else {
                  wxRequest('/workWx/auth/base/getAgentJsSdkSignature', qs.stringify(postData), header)
                  .then(res => {
                    // alert(`!-->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: res.`)
                    // alert(`!-->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: res =${JSON.stringify(res)}`)

                    // alert('getAgentJsSdkSignature:ok')
                    if (res.result === 'success') {
                      let agentConfig = res.data
                      wx.agentConfig({
                        corpid: agentConfig.agentJsApiSignature.appId, // 必填，企业微信的 corpid，必须与当前登录的企业一致
                        agentid: agentConfig.agentId, // 必填，企业微信的应用id
                        timestamp: agentConfig.agentJsApiSignature.timestamp, // 必填，生成签名的时间戳
                        nonceStr: agentConfig.agentJsApiSignature.nonceStr, // 必填，生成签名的随机串
                        signature: agentConfig.agentJsApiSignature.signature,// 必填，签名，agentConfig所以为应用签名
                        jsApiList: ['sendChatMessage','selectExternalContact','shareToExternalContact'], //必填
                        success: function (res) {
                          // alert('agentConfigSuccess')
                          // alert(`!-->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: wx.agentConfig: res.`)
                          // alert(`!-->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: wx.agentConfig: res =${JSON.stringify(res)}`)
                          // alert('agentConfig:ok')
                          // router.push(to)
                          // 回调
                          //1、发起申请申请时后，审批状态发生变化时
                          //2、发起申请申请时后，在“审批中”状态，有任意审批人进行审批操作时
                          // alert('wx.agentConfig 回调'+res.errMsg);
                        },
                        fail: function (res) {
                          // alert('agentConfigFailed')
                          // alert('回调失败：'+res.errMsg)
                          if (res.errMsg.indexOf('is not a function') > -1) {
                            alert('<i class="weui-icon-warn">版本过低请升级</i>')
                          }
                        }
                      })

                    }
                  })
                  .catch(err => {
                    // alert(`--->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: err.`)
                    // alert(`--->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: err =${JSON.stringify(err)}`)
                  })
                }
              }
            }
          )
        })
      } else {
        // this.$message({
        //   type: 'error',
        //   message: res.errorMsg
        // })
      }
    })
    .catch(err => {
      // alert(`--->zCommon.js: getJsSdkSignature: catch.`)
      // alert(`--->zCommon.js: getJsSdkSignature: catch: err =${JSON.stringify(err)}`)
      console.log(err, 'err')
    })
}

function configWx(to) {
  let postData = {
    // businessId: sessionStorage.getItem('businessId'),
    // pageUrl: encodeURIComponent(this.isIosOrAndroid() === 'android' ? location.href.split('#')[0] : window.initUrl)
    pageUrl: encodeURIComponent(location.href.split('#')[0])
  }
  let header = {
    token: sessionStorage.getItem('XToken'),
    corpId: INFO.corpId,
    agentId: INFO.agentId,
  }
  wxRequest('/workWx/auth/base/getJsSdkSignature', qs.stringify(postData), header).then(res => {
    if (res.result == 'success') {
      let config = res.data
      wx.config({
        beta: true,
        debug: false, //调试的时候可以开启
        appId: config.jsApiSignature.appId, // 必填，公众号的唯一标识
        timestamp: config.jsApiSignature.timestamp, // 必填，生成签名的时间戳
        nonceStr: config.jsApiSignature.nonceStr, // 必填，生成签名的随机串
        signature: config.jsApiSignature.signature, // 必填，签名
        // 根据自己的需求，填写 jsapilist 内容
        jsApiList: ['agentConfig', 'getCurExternalContact']
      })
      wx.ready(function () {
        // JS-SDK配置信息验证失败时会进入此方法
        wx.error(function (res) {
        })
        // 配置成功后验证API接口在当前客户端是否支持：判断当前客户端版本是否支持指定JS接口
        wx.checkJsApi({
          jsApiList: ['agentConfig', 'getCurExternalContact'],
          success: function (res) {
            // alert(`--->wx.checkJsApi: success. res =${JSON.stringify(res)}`);
            // router.push(to)

            if (res.errMsg != "checkJsApi:ok") {
              alert("JS-SDK接口检测失败:" + JSON.stringify(res));
              return false;
            }
          }
        })

        // alert(`--->configWx/getJsSdkSignature: next: getAgentJsSdkSignature.`)
        // alert(`--->configWx/getJsSdkSignature: next: getAgentJsSdkSignature: data =${qs.stringify(postData)}. header =${JSON.stringify(header)}`)

        wxRequest('/workWx/auth/base/getAgentJsSdkSignature', qs.stringify(postData), header)
          .then(res => {
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: IN.`)
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: res =${JSON.stringify(res)}`)

            if (res.result == 'success') {
              let agentConfig = res.data
              // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: res.result == 'success'.`)

              wx.agentConfig({
                corpid: agentConfig.agentJsApiSignature.appId, // 必填，企业微信的corpid，必须与当前登录的企业一致
                agentid: agentConfig.agentId, // 必填，企业微信的应用id
                timestamp: agentConfig.agentJsApiSignature.timestamp, // 必填，生成签名的时间戳
                nonceStr: agentConfig.agentJsApiSignature.nonceStr, // 必填，生成签名的随机串
                signature: agentConfig.agentJsApiSignature.signature,// 必填，签名，agentConfig所以为应用签名
                jsApiList: ['getCurExternalContact','selectExternalContact','shareToExternalContact'], //必填
                success: function (res) {
                  //  alert('agentConfig:ok')
                  // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: agentConfig: res =${res}`)
                  // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: agentConfig: to =${JSON.stringify(to)}`)
                  sessionStorage.setItem('zConfigWx', 'Pass')

                  router.push(to)
                  // getUnionid(to)
                  // 回调
                  //1、发起申请申请时后，审批状态发生变化时
                  //2、发起申请申请时后，在“审批中”状态，有任意审批人进行审批操作时
                  // alert('wx.agentConfig 回调'+res.errMsg);
                },
                fail: function (res) {
                  if (res.errMsg.indexOf('is not a function') > -1) {
                    alert('<i class="weui-icon-warn">版本过低请升级</i>')
                  }
                }
              })
            }
          })
          .catch(err => {
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: catch: err.`)
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: catch: err =${JSON.stringify(err)}`)
          })
      })
    } else {
      // this.$message({
      //   type: 'error',
      //   message: res.errorMsg
      // })
    }
  }).catch(err => {
    console.log(err, 'err')
  })
}

function getUnionid(to) {
  wx.invoke('getCurExternalContact', {}, function (res) {
    if (res.err_msg == "getCurExternalContact:ok") {
      let header = {
        token: sessionStorage.getItem('XToken'),
        corpId: INFO.corpId,
        agentId: INFO.agentId,
      }
      let postData = {
        userId: res.userId
      }
      wxRequest('/workWx/auth/contact/getExternalContact', postData, header, 'get').then(res => {
        if (res.result == 'success') {
          sessionStorage.setItem('unionid', res.data.externalContact.unionId)
          router.push(to)
        }
      })
    } else {
      console.log()
      
    }
  });
}

function getUserInfo(inData) {
  wx.invoke('getUserInfo', {}, function (res) {
    if (res.err_msg == "getUserInfo:ok") {
      let header = {
        token: sessionStorage.getItem('XToken'),
        corpId: INFO.corpId,
        agentId: INFO.agentId,
      }
      let postData = {
        code: inData.code
      }
      wxRequest('/workWx/auth/oauth2/getUserInfo', postData, header, 'post').then(res => {
        if (res.result == 'success') {
          sessionStorage.setItem('userInfo', res.data)
          console.log('%c--->getUserInfo: RES: ', 'background: limegreen;', res.data)
          // router.push(to)
        }
      })
    } else {
      console.log('%c--->UnionId: N/A', 'background: red;')
      console.log(res, 'res')
    }
  });
}


export { getXToken, configWx, getUnionid, getUserInfo }
