<template>
  <Page styleReset="headerNoBack">
    <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:body>
      <div class="home-theBack"></div>
      <div class="home-theContent">
        <!-- 固定头部 -->
        <div class="home-theContent-title">
          <div class="item" v-for="(item, index) in addQuickList" :key="index">
            <div class="item-img" @click="jumpAdd(item)">
              <img :src="getRouterImg(item.path, 'newPng')" alt="">
            </div>
            <div class="item-text">建{{ item.name }}</div>
          </div>
        </div>
        <!-- 可以滚动 -->
        <div class="rollingLayout">
          <!-- 模块配置 -->
          <div class="layoutOfEachModule">
            <div class="item" v-for="(item, index) in addCommonlyUsedList" :key="index" @click="jumpList(item)">
              <div class="item-img"><img :src="getRouterImg(item.path)" alt=""></div>
              <div class="item-text">{{ item.name }}</div>
            </div>
            <div class="item" @click="showBottom = true">
              <div class="item-img">
                <img src="/src/assets/image/add.png"></img>
              </div>
              <div class="item-text">配置</div>
            </div>
          </div>

          <!-- 销售简报、数据汇总、商机阶段 -->
          <DataAnalysis></DataAnalysis>

          <!-- 常用联系人 -->
          <div class="mt-3">
            <div class="text-size-large text-[#000] pl16">常用联系人</div>
            <div class="p16 pt-0 pb-0">
              <template v-if="topContactsList && topContactsList.length > 0">
                <template v-for="item in topContactsList">
                  <div class="flex flex-row items-center rounded-md p-4 bg-white mb-5" @click="toContactDetails(item)">
                    <div class="contactImage">
                      <img class="w-full h-full" src="/src/assets/image/topContacts.png">
                    </div>
                    <div class="flex-1">{{ item.name }}</div>
                    <div class="rightArrow">
                      <van-icon name="arrow" />
                    </div>
                  </div>
                </template>
              </template>
              <template v-else>
                <van-empty description="暂无常用联系人" />
              </template>
            </div>
          </div>
        </div>
        
        <!-- 弹出层 -->
        <van-popup v-model:show="showBottom" position="bottom" :overlay-style="{ backgroundColor: 'rgba(0, 0, 0, 0.4)' }">
          <div class="bg-[#f6f6fa]">
            <div class="w-full text-center bg-white block-div" @click="quickListShow = true">快捷新建设置</div>
            <div class="w-full text-center bg-white block-div biankuang" @click="modulesListShow = true">常用功能设置</div>
            <div class="w-full text-center mt-4 text-[red] bg-white block-div" @click="showBottom = false">取消</div>
          </div>
        </van-popup>
        
        <!-- 快捷入口设置 -->
        <van-popup v-model:show="quickListShow" position="bottom" :style="{ height: '100%' }" closeable>
          <QuickEntrance :allModulesList="allModulesList" :selectModule="addQuickList" @save-value="refreshData" />
        </van-popup>

        <!-- 常用功能设置 -->
        <van-popup v-model:show="modulesListShow" position="bottom" :style="{ height: '100%' }" closeable>
          <CommonFunctions :allModulesList="allModulesList" :selectModule="addCommonlyUsedList" @save-value="refreshData" />
        </van-popup>
      </div>
    </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 Footer from "@components/page/footer.vue";
import requests from "@common/requests"
import { GET_FREQUENTLY_USED_CONTACTS, GET_FAST_ACCESS_LIST, GET_ALL_ROUTING_PARAMETERS, COMMON_FUNCTIONS } from "@hooks/useApi";
import useToast from "@hooks/useToast"
import { routingInfos, getRouterImg } from "@utility/generalVariables.js";
import useRouterStore from "@store/useRouterStore.js";

// 相关页面
import DataAnalysis from './component/dataAnalysis.vue';
import QuickEntrance from './component/quickEntrance.vue'
import CommonFunctions from './component/commonFunctions.vue'

const { toastText, toastSuccess, toastFail, toastLoading } = useToast()
const router = useRouterStore()
const useInfo = useInfoStore()

const showBottom = ref(false)
const quickListShow = ref(false)
const modulesListShow = ref(false)
const topContactsList = ref([])
const allModulesList = [...(useInfo?.modularList || []).filter(item => item.path !== '/biReport'), { id: -1, path: '/visitor', name: '访客计划' }]
const addQuickList = ref([])
const addCommonlyUsedList = ref([])

function getAllData() {
  getFrequentlyUsedContacts()
  getQuickList()
  getCommonUseList()
}

// 获取当前公司的常用功能列表
function getCommonUseList() {
  requests.post(COMMON_FUNCTIONS, {}).then((res) => {
    addCommonlyUsedList.value = res.data.map(item => { return { ...item, path: item.router } })
  })
}

// 获取快捷新建列表
function getQuickList() {
  requests.post(GET_FAST_ACCESS_LIST, {}).then((res) => {
    addQuickList.value = res.data.map(item => { return { ...item, path: item.router } })
  })
}

function getFrequentlyUsedContacts() {
  requests.post(GET_FREQUENTLY_USED_CONTACTS, {}).then((res) => {
    topContactsList.value = res.data
  })
}

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

function jumpList(item) {
  if(item.path == '/visitor') {
    router.navigateTo({
      pathName: 'visitor',
      success: () => {}
    })
    return
  }
  const jumpTo = routingInfos[item.path.replace('/', '')]
  router.navigateTo({
    pathName: 'moduleList',
    success: () => {
      router.emit('moduleListDetailParameter', {
        row: JSON.stringify(jumpTo)
      })
    }
  })
}

function refreshData() {
  getQuickList()
  getCommonUseList()
  showBottom.value = false
  quickListShow.value = false
  modulesListShow.value = false
}

function obtainEnterpriseWeChatParameters(data = {}) {
  console.log(data, '<=== 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: () => {
    getAllData()
  },
  init: () => {
    const currentEnvironment = navigator.userAgent.toLowerCase();
    const isCorpWX = currentEnvironment.indexOf("wxwork") > 0 ? true : false
    if (isCorpWX) {
      obtainEnterpriseWeChatParameters(useInfo.userInfo)
    }
  }
});


</script>

<style lang="scss" scoped>
:deep(.van-tabs__content) {
  flex: 1;
  overflow-y: auto;
}

:deep(.van-tabs__wrap) {
  background-color: $themeColor;
}

.home-theBack {
  width: 100%;
  height: 147px;
  background: linear-gradient(to top right, rgba($color: $themeColor, $alpha: 0.8), $themeColor, rgba($color: $themeColor, $alpha: 0.8));
  position: absolute;
  top: 0;
}

.homeheaderleft {
  font-size: 20px;
  font-weight: bold;
  display: flex;
  align-items: center;

  img {
    width: 30px;
  }

  div {
    margin-left: 10px;
  }
}

.home-theContent {
  display: flex;
  height: 100%;
  flex-direction: column;


  .home-theContent-title {
    padding: 25px;
    // background-color: $themeColor;
    // background: linear-gradient(to top right, #4985e0, $themeColor, #1965db);
    display: flex;

    .item {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 25%;

      &::after {
        content: '';
        width: 1px;
        height: 30px;
        background-color: rgba($color: #fff, $alpha: 0.5);
        position: absolute;
        left: 0px;
        top: 0%;
      }

      &:first-child::after {
        width: 0;
      }

      .item-img {
        width: 24px;
        height: 24px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .item-text {
        color: #fff;
        font-size: 14px;
        margin-top: 8px;
      }
    }
  }

  .rollingLayout {
    flex: 1;
    overflow-y: auto;
    margin: 20px 0;
    padding: 0 20px;
    border-radius: 10px;

    .layoutOfEachModule {
      display: flex;
      flex-wrap: wrap;

      .item {
        width: 20%;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-bottom: 20px;

        .item-img {
          width: 36px;
          height: 36px;

          img {
            width: 100%;
            height: 100%;
          }
        }

        .item-text {
          color: #474A56;
          font-size: 14px;
          margin-top: 8px;
        }
      }
    }
  }
}

.biankuang {
  border-top: 1px solid #eceeef;
}

.block-div {
  padding: 14px 0;
}
</style>
