<script setup>
import { useStore } from "vuex";
import { computed, ref, watch } from "vue";
import Notice from '@/components/Notice.vue'
import MyCollect from '@/components/MyCollect.vue'
import moment from "moment";
import { apiGetPermissionList } from "@/api/common.js";
import { ElMessageBox, ElMessage } from "element-plus";
import { apiLastApplyRecord ,apiApplyPermission} from "@/api/user";
import { useRouter } from "vue-router";

const router = useRouter();
const store = useStore();
store.dispatch("getUserInfo"); //获取个人信息
const userInfo = computed(() => store.state.userInfo);
const lastTime = computed(() => {
  let timeArr = [];
  store.state.userInfo.permission_list &&
    store.state.userInfo.permission_list.forEach((item) => {
      item.permission_list.forEach((item2) => {
        timeArr.push(new Date(item2.end_date));
      });
    });

  let maxTime = Math.max(...timeArr);
  if (timeArr.length === 0) {
    return "";
  } else {
    return moment(maxTime).format("YYYY.MM.DD");
  }
});

let permissionList = ref([]);
const getPermissionList = async () => {
  const res = await apiGetPermissionList();
  if (res.code === 200) {
    permissionList.value = res.data;
  }
};
getPermissionList();

let permission_list_str = computed(() => {
  let hasArr = [];
  store.state.userInfo.permission_list &&
    store.state.userInfo.permission_list.forEach((item) => {
      item.permission_list.forEach((item2) => {
        hasArr.push(item2.name);
      });
    });
  let arr = permissionList.value.filter((item) => {
    if (hasArr.find((e) => e === item.permission_name)) return item;
  });
  let arr2 = arr.map((item) => item.name);

  return arr2.join("/");
});

//我的中点击去申请权限
const handleGoApplyPermission = async () => {
  if(store.state.userInfo.is_bind===0){
        ElMessageBox({
            title:`温馨提示`,
            message:'为了优化您的用户体验，<br>请登录后查看更多信息！',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonText:'去登录',
            confirmButtonClass:'self-elmessage-confirm-btn',
            showCancelButton:true,
            cancelButtonText:'取消',
            cancelButtonClass:'self-elmessage-cancel-btn'
        }).then(res=>{
            wx.miniProgram.reLaunch({url:'/pages/login'})
        }).catch(()=>{})
        return
  }
  const res = await apiLastApplyRecord();
  if (res.code === 200) {
    if (res.data) {
      const htmlStr = `<p style="text-align:center;">您已提交过申请，请耐心等待</p>`;
      ElMessageBox({
        title: "申请提醒",
        message: htmlStr,
        center: true,
        dangerouslyUseHTMLString: true,
        confirmButtonText: "知道了",
        confirmButtonClass: "self-elmessage-confirm-btn",
      });
    } else {
      // 流失客户主动申请一次
      if (userInfo.value.status == "流失"||userInfo.value.status == "关闭") {
        apiApplyPermission({
          company_name: userInfo.value.company_name,
          real_name: userInfo.value.real_name,
          source: 1,
          from_page: "我的",
        }).then((res) => {
          const htmlStr = `<p>申请已提交</p><p>请等待销售人员与您联系</p>`;
          ElMessageBox({
            title: "申请提醒",
            message: htmlStr,
            center: true,
            dangerouslyUseHTMLString: true,
            confirmButtonText: "知道了",
            confirmButtonClass: "self-elmessage-confirm-btn",
          });
        });
        return;
      }
      router.push({
        path: "/apply/permission",
        query: {
          source: 1,
          fromPage: "我的",
        },
      });
    }
  }
};

//我的中点击联系销售
const handleContact = async () => {
  const res = await apiApplyPermission({
    company_name: userInfo.value.company_name,
    real_name: userInfo.value.real_name,
    source: 1,
    from_page: "我的",
  });
  if (res.code === 200) {
    console.log("主动申请成功");
  }
  const htmlStr = `<p>请联系对口销售${userInfo.value.seal_name}：${userInfo.value.seal_mobile}</p>`;
  ElMessageBox({
    title: "申请提醒",
    message: htmlStr,
    center: true,
    dangerouslyUseHTMLString: true,
    confirmButtonText: "知道了",
    confirmButtonClass: "self-elmessage-confirm-btn",
  });
};

// 全局返回按钮
const goBack=()=>{
  if(window.history.state.back){
    console.log('返回上一页');
    router.go(-1)
  }else{
    console.log('返回首页');
    router.push({path:'/report/index'})
  }
}

// 点击面包屑
const handleClickBreadCrumb=(item,index)=>{
  const _index=index-(store.state.breadCrumbList.length-1)
  router.go(_index)
}

// 跳转设置个人信息
const handleSetUserInfo=()=>{
  if(store.state.userInfo.is_bind===0){
        ElMessageBox({
            title:`温馨提示`,
            message:'为了优化您的用户体验，<br>请登录后查看更多信息！',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonText:'去登录',
            confirmButtonClass:'self-elmessage-confirm-btn',
            showCancelButton:true,
            cancelButtonText:'取消',
            cancelButtonClass:'self-elmessage-cancel-btn'
        }).then(res=>{
            wx.miniProgram.reLaunch({url:'/pages/login'})
        }).catch(()=>{})
        return
  }
  router.push('/user/setinfo')
}

// 我的收藏
let showCollect=ref(false)
// 是否在小程序环境中 区分网页版和PC小程序
const isInMini=ref(false)

wx.miniProgram.getEnv(res=>{
  isInMini.value=res.miniprogram
})

const goYBPCEN=()=>{
    let href = import.meta.env.VITE_EN_YB_PC
    window.open(href,'_blank');
}

</script>

<template>
  <div class="clear-float head-wrap">
    <div class="flex-col-center logo-box" style="cursor: pointer;" @click="router.push('/report/index')">
      <img src="@/assets/logo.png" alt="logo" class="logo" />
      <span>弘则研报</span>
    </div>
    <div class="flex-col-center userinfo-wrap">
      <img src="@/assets/icon-yben.png" class="yben-icon" @click="goYBPCEN" v-if="!isInMini"/>
      <!-- 我的收藏 -->
      <el-popover trigger="click" @show="showCollect=true" @hide="showCollect=false" :width="460" popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;">
        <template #reference>
          <img v-if="userInfo" style="width:26px;height:25px;margin-right:21px;position: relative;top:-2px" src="@/assets/icon-start.png" alt="">
        </template>
        <template #default>
          <MyCollect :show="showCollect"/>
        </template>
      </el-popover>
      <!-- 消息 -->
      <el-popover trigger="click" :width="439" popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;">
        <template #reference>
          <el-badge v-if="userInfo" :value="$store.state.userInfo.un_read" :hidden="$store.state.userInfo.un_read==0">
            <img style="width:28px;height:28px" src="@/assets/icon-notice.png" alt="">
          </el-badge>
        </template>
        <template #default>
          <Notice/>
        </template>
      </el-popover>
      <!-- 扫码 -->
      <el-popover :width="400" popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;">
        <template #reference>
          <img class="icon-scan" src="@/assets/icon-scan.png" alt="" />
        </template>
        <template #default>
          <div class="flex" style="justify-content: space-between">
            <div style="flex: 1; text-align: center">
              <img style="width: 121px" src="@/assets/xcx-img.png" alt="" />
              <p>手机扫码<br />体验更多小程序功能</p>
            </div>
            <div style="flex: 1; text-align: center">
              <img style="width: 121px" src="@/assets/gzh-img.png" alt="" />
              <p>关注弘则研报公众号<br />及时获取活动和报告通知</p>
            </div>
          </div>
        </template>
      </el-popover>
      <!-- 个人信息 -->
      <el-popover :width="400" popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;">
        <template #reference>
          <el-avatar shape="square" :size="40" v-if="userInfo" :src="$store.state.userInfo.head_img_url||$store.state.globalImgUrls.defaultAvatar"></el-avatar>
        </template>
        <template #default>
          <div class="userinfo-box" v-if="userInfo">
            <div class="top" @click="handleSetUserInfo">
              <el-avatar shape="square" :size="50" :src="$store.state.userInfo.head_img_url||$store.state.globalImgUrls.defaultAvatar"></el-avatar>
              <p style="font-size: 20px">{{ userInfo.real_name || "--" }}</p>
              <p style="margin:12px 0">
                <span>昵称：</span>
                <span v-if="userInfo.nick_name">{{userInfo.nick_name}}</span>
                <span v-else style="background:#FFFBF5;color:#F3A52F;padding:2px 24px">设置专属昵称</span>
              </p>
              <p>{{ userInfo.mobile || userInfo.email }}</p>
            </div>
            <div class="flex info-item">
              <div class="label">公司</div>
              <div class="con">{{ userInfo.company_name || "--" }}</div>
            </div>
            <div class="flex info-item">
              <div class="label">品种权限</div>
              <div class="con" v-if="userInfo.status == '冻结' || (userInfo.status == '试用' && userInfo.is_suspend == 1)">
                <span>暂无权限</span>
                <span class="btn" @click="handleContact">联系销售</span>
              </div>
              <div class="con" v-else-if="userInfo.permission_list.length == 0">
                <span>暂无权限</span>
                <span class="btn" @click="handleGoApplyPermission">立即申请</span>
              </div>
              <div class="con" v-else>{{ permission_list_str }}</div>
            </div>
            <div class="flex info-item" v-if="userInfo.status!='试用'">
              <div class="label">服务截至日期</div>
              <div class="con">{{ lastTime }}</div>
            </div>
          </div>
        </template>
      </el-popover>
    </div>

    <!-- 头部版心 -->
    <div class="head-main">
      <!-- 面包屑 -->
      <div class="flex-col-center left-breadcrumb-box">
        <img @click="goBack" class="back-icon" src="@/assets/icon-back.png" alt="" v-if="$route.meta.hasBack">
        <span class="breadcrumb-item" v-for="(item,index) in $store.state.breadCrumbList" :key="item.path" @click="handleClickBreadCrumb(item,index)">{{item.name}}</span>
      </div>
      <!-- 图库模块搜索与筛选 -->
      <div id="chart-in-head"></div>
      <!-- 研报首页搜索 -->
      <div id="reportIndex-in-head"></div>
      <!-- 报告列表搜索与筛选 -->
      <div id="reportlist-in-head"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.head-wrap {
  width: 100%;
  height: 100%;
  .logo-box {
    float: left;
    width: 140px;
    height: 100%;
    border-right: 1px solid #f2f2f2;
    .logo {
      width: 32px;
      height: 32px;
      margin-right: 10px;
    }
    span {
      font-size: 18px;
      font-weight: bold;
    }
  }
  .userinfo-wrap {
    margin-left: 40px;
    float: right;
    // width: 120px;
    height: 100%;
    .yben-icon{
      height: 26px;
      margin-right: 21px;
      cursor: pointer;
    }
    .icon-scan {
      width: 26px;
      height: 26px;
      flex-shrink: 0;
      position: relative;
      margin-right: 20px;
      margin-left: 20px;
    }
    :deep(.el-badge__content--danger){
      background-color: #D62020;
    }
  }
  .head-main{
    width: calc(100% - 280px);
    height: 100%;
    margin-left: auto;
    margin-right: auto;
    .left-breadcrumb-box{
      float: left;
      margin-left: 20px;
      height: 100%;
      .back-icon{
        width: 30px;
        height: 30px;
        margin-right: 20px;
        cursor: pointer;
      }
      .breadcrumb-item{
        font-size: 14px;
        cursor: pointer;
        &::after{
          content: '/';
          display: inline-block;
          margin: 0 5px;
        }
        &:last-child::after{
          content: '';
        }
        &:last-child{
          color: #F3A52F;
        }
      }
    }
    #chart-in-head{
      float: right;
      height: 100%;
    }
    #reportIndex-in-head{
      float: right;
      height: 100%;
    }
    #reportlist-in-head{
      float: right;
      height: 100%;
    }
    
  }
}
.userinfo-box {
  .top {
    text-align: center;
    margin-bottom: 31px;
    color:#333;
    p {
      margin: 0;
    }
  }
  .info-item {
    padding: 20px 26px 20px 20px;
    border-top: 1px solid #ebebeb;
    position: relative;
    .label {
      width: 90px;
      margin-right: 19px;
      flex-shrink: 0;
    }
    .con {
      .btn {
        width: 97px;
        height: 30px;
        border-radius: 8px;
        border: 1px solid #F3A52F;
        font-size: 16px;
        color: #F3A52F;
        display: inline-block;
        text-align: center;
        line-height: 30px;
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
      }
    }
  }
}
</style>
