<template>
  <Page styleReset="headerClass">
    <template v-slot:headerLeft>
      <div class="homeheaderleft">
        <img src="/src/assets/image/home_logo.png">
        <div class="text-white">客户管家</div>
      </div>
    </template>
    <template v-slot:headerRight>
      <div class="newButton" @click="showModule = true">＋ 新建</div>
    </template>

    <template v-slot:body>
      <div class="w-full h-full flex flex-col overflow-hidden">
        <!-- 头部 -->
        <div class="custom-tabs rounded-b-lg z-10">
          <div class="custom-tabs-box text-size-in custom-tabs-rad flex items-center overflow-hidden">
            <div :class="`w-1/2 h-full rounded-r-lg items-justify-center ${homepageType == 'workbench' ? 'themeTextColor bg-white font-bold' : ''}`" @click="homepageType = 'workbench'">工作台</div>
            <div :class="`w-1/2 h-full rounded-l-lg items-justify-center ${homepageType == 'dataAnalysis' ? 'themeTextColor bg-white font-bold' : ''}`" @click="homepageType = 'dataAnalysis'">数据分析</div>
          </div>
        </div>
        <!-- 内容 -->
        <div class="flex-1 overflow-y-auto relative aopiuyt">
            <Workbench v-if="homepageType == 'workbench'" />
            <DataAnalysis v-if="homepageType == 'dataAnalysis'" />
        </div>
      </div>
      


      <!-- 显示对应的模块 -->
      <van-popup v-model:show="showModule" closeable position="bottom" round>
        <div class="newModuleAdded relative">
          <div class="text-size-large text-[#474A56] absolute topTitle">客户管家</div>
          <div class="flex flex-wrap">
            <template v-for="(item) in moduleList" :key="item.id">
              <div class="w-16 flex flex-col items-center mrSpacing" @click.stop="toAddEditor(item)">
                <div class="newModuleImage">
                  <img class="w-full h-full" :src="returnImageAddress(item)" alt="">
                </div>
                <div class="mt-3 text-[#474A56]">{{ item.name }}</div>
              </div>
            </template>
          </div>
        </div>
      </van-popup>
    </template>

    <template v-slot:footer>
      <Footer />
    </template>
  </Page>
</template>

<script setup>
import { ref } from "vue";
import { useLifecycle } from "@hooks/useCommon.js";
import useInfoStore from "@store/useInfoStore"
import useRouterStore from "@store/useRouterStore.js";
import { routingInfos } from "@utility/generalVariables.js";
import Footer from "@components/page/footer.vue";
import Workbench from "./component/workbench.vue";
import DataAnalysis from "./component/dataAnalysis.vue";
import requests from "@common/requests"


const userInfo = useInfoStore()
const router = useRouterStore()
const homepageType = ref('workbench')
const showModule = ref(false)
const moduleList = ref(userInfo.modularList)

function toAddEditor(rows) {
  const jumpTo = routingInfos[rows.path.replace('/', '')]
  router.navigateTo({
    pathName: 'addEditor',
    success: () => {
      router.emit('addEditorParameter', {
        routerInfo: JSON.stringify(jumpTo)
      })
    }
  })
}

function returnImageAddress(rows) {
  const row = routingInfos[rows.path.replace('/', '')]
  return row.homeImage
}

function obtainEnterpriseWeChatParameters(data = {}) {
  const token = data.id
  // const curUrl = window.location.href.split('home')[0]
  const curUrl = window.location.href
  requests.post('/wxcorp/getCorpWXConfig', { url: curUrl, token }).then((res) => {
    wx.config({
      beta: true,
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: res.data.appid, // 必填，公众号的唯一标识 
      timestamp: res.data.timestamp, // 必填，生成签名的时间戳 
      nonceStr: res.data.noncestr, // 必填，生成签名的随机串 
      signature: res.data.sign, // 必填，签名，见附录1 
      jsApiList: ['chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'previewFile', 'getLocation', 'agentConfig']
    })

    wx.ready(function () {
      // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
      requests.post('/wxcorp/getCorpWXAgentConfig', { url: curUrl, token }).then((res) => {
        console.log(res, '<====== 返回的参数 /wxcorp/getCorpWXAgentConfig')
        wx.agentConfig({
          corpid: res.data.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
          agentid: res.data.agentid, // 必填，企业微信的应用id （e.g. 1000247）
          timestamp: res.data.timestamp, // 必填，生成签名的时间戳
          nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
          signature: res.data.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
          jsApiList: ['selectExternalContact', 'openThirdAppServiceChat', 'openAppManage'], //必填，传入需要使用的接口名称
          success: function (result) {
            //  wx.agentConfig成功回调后，WWOpenData 才会注入到 window 对象上面
            window.WWOpenData.bind(document.querySelector('ww-open-data'))
          },
          fail: function (res) {
            if (res.errMsg.indexOf('function not exist') > -1) {
              alert('版本过低请升级')
            }
          },
        })
      }).catch(err => {
        if (err.errMsg.indexOf('function not exist') > -1) {
          alert('版本过低请升级')
        }
      })
    })
    wx.error(function (res) {
      // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
      // alert('wxConfig发生异常:'+JSON.stringify(res));
      // 企业第一次授权安装进入后会报not in reliable domain的错误，刷新后正常
      // location.reload();
    });
  }).catch(err => {
    alert(err);
  })
}

useLifecycle({
  load: () => {

  },
  init: () => {
    const currentEnvironment = navigator.userAgent.toLowerCase();
    const isCorpWX = currentEnvironment.indexOf("wxwork") > 0 ? true : false
    if(isCorpWX) {
      obtainEnterpriseWeChatParameters(userInfo.userInfo)
    }
  }
});


</script>

<style lang="scss" scoped>
:deep(.van-tabs__content) {
  flex: 1;
  overflow-y: auto;
}
:deep(.van-tabs__wrap) {
  background-color: $themeColor;
}
.homeheaderleft {
  font-size: 20px;
  font-weight: bold;
  display: flex;
  align-items: center;
  img {
    width: 30px;
  }
  div {
    margin-left: 10px;
  }
}
.newButton {
  width: 86px;
  line-height: 30px;
  background: #fff;
  color: $themeColor;
  border-radius: 75px;
}
 
.custom-tabs {
  background: $themeColor;
  padding: 22px 15px;
  color: #fff;
}

.custom-tabs-box {
  width: 100%;
  border: 1.5px solid #fff; 
  height: 50px;
}
.custom-tabs-rad {
  border-radius: 6px;
}
.aopiuyt {
  margin-top: -6px;
}
.newModuleAdded {
  padding: 45px 25px 45px 25px;
}

.newModuleImage {
  width: 50px;
  height: 50px;
  border-radius: 10px;
}
.mrSpacing {
  margin-top: 16px;
  margin-right: 33px;
  &:nth-child(4n) {
    margin-right: 0;
  }
}
.topTitle {
  top: 14px;
}
</style>
