<template>
  <div class="personal-container" :class="{ 'personal-mobile': mobile }">
    <div class="personal-main">
      <!-- 个人信息框 -->
      <div class="personal-info-container">
        <div class="personal-user">
          <div class="personal-user-avatar">
            <img
              class="personal-user-avatar-img"
              :src="personalUserInfo.icon"
            />
            <a
              href="/type/vip/developer"
              target="view_window"
              class="personal-user-tag"
              v-if="personalUserInfo.person_vip_status == 1"
            ></a>
          </div>
          <div class="personal-user-info">
            <div class="personal-user-name">
              <span class="name-cotent">
                <span>{{ personalUserInfo.nickname }}</span>
                <span v-if="personalUserInfo.direction_name != ''"
                  >（{{ personalUserInfo.direction_name }}）</span
                >
              </span>
              <LevelTag :level="personalUserInfo.fw_freework_level"></LevelTag>
              <span style="margin-left:5px;"></span>
              <t-level-tag
                :isLink="true"
                :level="personalUserInfo.freework_level"
              />
            </div>
            <div class="personal-user-text">
              {{ personalUserInfo.lasttime }} ·
              {{ personalUserInfo.dynamic_view_num }}浏览
            </div>
            <div class="personal-user-text" v-if="registerTime">
              {{ registerTime }}加入
            </div>
          </div>
        </div>
        <div class="personal-user-follow">
          <p class="personal-report">
            <a
              :href="baseUrl + '/otherpage/report/' + personalUserInfo.uid"
              target="view_window"
              >举报</a
            >
          </p>
          <div class="personal-share-area">
            <span
              v-if="personalUserInfo.github_name"
              @click="
                linkToThirdParty(personalUserInfo.github_name, 'github_name')
              "
              class="personal-share-btn github"
            ></span>
            <span
              v-if="personalUserInfo.gitee_name"
              @click="
                linkToThirdParty(personalUserInfo.gitee_name, 'gitee_name')
              "
              class="personal-share-btn gitee"
            ></span>
            <span
              v-if="personalUserInfo.csdn_name"
              @click="linkToThirdParty(personalUserInfo.csdn_name, 'csdn_name')"
              class="personal-share-btn csdn"
            ></span>

            <span
              v-if="personalUserInfo.juejin_name"
              @click="
                linkToThirdParty(personalUserInfo.juejin_name, 'juejin_name')
              "
              class="personal-share-btn juejin"
            ></span>
            <span
              v-if="personalUserInfo.zhihu_name"
              class="personal-share-btn zhihu"
            ></span>
          </div>
          <div
            class="personal-follow-btn"
            @click="toggleFollow"
            v-if="isShowFollow"
          >
            {{ isFollowing ? "已关注" : "关注" }}
          </div>
        </div>
      </div>

      <!-- 内容tab -->
      <div class="personal-content-container">
        <div class="personal-content-tab">
          <!-- tab框 -->
          <div
            class="personal-tab-item"
            :class="{ cur: tabSelected == 1 }"
            @click="tabSelected = 1"
          >
            动态 {{ dynamicCount }}
          </div>
          <div
            class="personal-tab-item"
            :class="{ cur: tabSelected == 2 }"
            @click="tabSelected = 2"
          >
            文章 {{ articleCount }}
          </div>
          <div
            class="personal-tab-item"
            :class="{ cur: tabSelected == 3 }"
            @click="tabSelected = 3"
          >
            视频课程 {{ courseCount }}
          </div>
        </div>
        <div class="personal-content-main">
          <template v-if="tabSelected == 1">
            <DynamicItem
              :info="item"
              :init="init"
              v-for="item in list"
              :key="item.dynamicId"
            ></DynamicItem>
          </template>

          <template v-if="tabSelected == 2">
            <ArticleItem
              :info="item"
              v-for="item in list"
              :key="item.hash_id"
            ></ArticleItem>
          </template>
          <template v-if="tabSelected == 3">
            <CourseItem
              :info="item"
              v-for="item in list"
              :key="item.id"
            ></CourseItem>
          </template>

          <Empty v-if="list.length == 0 && !pageLoading">
            <div v-if="isSelf" class="auto-bind-wechat">
              <!-- <span @click="callBindWeChat">绑定社交账号</span>，自动抓取更新 -->

               已绑定XXX账号<span @click="unbindWeChat">解绑</span>
            </div>
          </Empty>

          <div class="loading" v-if="pageLoading">加载中</div>

          <!-- 列表内容 -->
        </div>
      </div>
    </div>
    <div class="personal-side">
      <a
        class="personal-page-link"
        :href="'https://www.proginn.com/wo/' + personUid"
        target="view_window"
      >
        <span>Ta的开发工作主页</span>
        <span class="arrow"></span>
      </a>

      <div class="personal-follow-info">
        <div class="personal-follow-item">
          <span class="personal-follow-label">关注了</span>
          <span class="personal-follow-count">{{
            personalUserInfo.my_followers
          }}</span>
        </div>
        <div class="personal-follow-item">
          <span class="personal-follow-label">关注者</span>
          <span class="personal-follow-count">{{
            personalUserInfo.followers_my
          }}</span>
        </div>
      </div>

      <div class="personal-ad-container">
        <a
          class="ad-item"
          v-for="(item, index) in adList"
          :key="index"
          target="view_window"
          :style="{ backgroundImage: 'url(' + item.image + ')' }"
        >
        </a>
      </div>
    </div>
    <BindWeChatArticle ref="bindWeChat"></BindWeChatArticle>
    <UnBindWeChatArticle ref="unBindWeChat"></UnBindWeChatArticle>
  </div>
</template>

<script>
import { mapState } from "vuex";
import qs from "qs";
import DynamicItem from "./component/dynamic-item.vue";
import ArticleItem from "./component/article-item.vue";
import CourseItem from "./component/course-item.vue";

import Empty from "@/components/empty.vue";

import LevelTag from "@/components/level-tag.vue";
import PersonalSeoData from "./personalData";
import moment from "moment";
import TLevelTag from "@/components/t-level-tag.vue";
import BindWeChatArticle from "@/components/bind_wechat_article";
import UnBindWeChatArticle from "@/components/unbind_wechat_article";

export default {
  name: "PersonalIndex",
  layout: "header-fix",
  components: {
    LevelTag,
    DynamicItem,
    ArticleItem,
    CourseItem,
    Empty,
    TLevelTag,
    BindWeChatArticle,
    UnBindWeChatArticle
  },
  data() {
    return {
      baseUrl: "",
      mobile: false,
      // firstLoad: true,
      isWeixinApp: true,
      tabSelected: 1,
      tabs: [
        {
          id: 1,
          label: "动态",
          count: 10
        },
        {
          id: 2,
          label: "文章",
          count: 10
        },
        {
          id: 3,
          label: "视频课程",
          count: 10
        }
      ],

      list: [],
      page: 0,
      pageSize: 10,

      isMore: true,
      pageLoading: false,

      user: {},
      personUid: "",
      init: 0
    };
  },
  watch: {
    tabSelected: function() {
      this.resetTab();
    }
  },
  head() {
    const {
      title = this.personalUserInfo.nickname + "个人主页-技术圈",
      keyword = this.personalUserInfo.nickname + "个人主页",
      description = "技术圈提供" +
        this.personalUserInfo.nickname +
        "个人主页，方便对" +
        this.personalUserInfo.nickname +
        "感兴趣的人收藏和关注，并及时了解" +
        this.personalUserInfo.nickname +
        "的动态，包括最新文章、最新视频！",
      h1 = "",
      canonical = "",
      metaLocation
    } = this.head || {};
    let obj = {
      title: title,
      meta: [
        {
          name: "keywords",
          content: keyword
        },
        {
          name: "description",
          content: description
        },
        {
          name: "h1",
          content: h1
        }
      ],
      link: [
        {
          rel: "canonical",
          href: canonical
        }
      ]
    };
    if (metaLocation) {
      obj.meta.push({
        name: "location",
        content: metaLocation
      });
    }
    return obj;
  },
  computed: {
    ...mapState(["deviceType"]),
    isSelf() {
      let myuid = 681042 || this.userinfouid;
      let pageuid = this.$route.params.uid;
      if (myuid && myuid == pageuid) {
        return true;
      }
      return false;
    },
    showWxHeader() {
      return (
        !this.deviceType.app &&
        !this.isWeixinApp &&
        (this.deviceType.android || this.deviceType.ios)
      );
    },
    mainMarginTop() {
      if (this.mobile && this.showWxHeader) {
        return "64px !important";
      } else if (this.mobile) {
        return "0px !important";
      } else {
        return "20px !important";
      }
    },
    registerTime() {
      if (this.personalUserInfo.logintime) {
        let time = moment(this.personalUserInfo.logintime * 1000).format(
          "YYYY年MM月"
        );
        return time;
      } else {
        return 0;
      }
    },
    isShowFollow() {
      let isLogin = this.userinfo.uid;
      let isMine = this.userinfo.uid == this.personUid ? true : false;
      if (!isLogin) return true;
      return isMine ? false : true;
    }
  },

  mounted() {
    console.log(111, this.$route.params);
    this.personUid = this.$route.params.uid;
    this.baseUrl = this.$store.state.domainConfig.siteUrl;
    this.isWeixinApp = navigator.userAgent.indexOf("miniProgram") > -1;
    this.init = 1;
    this.$nextTick(() => {
      this.listenToEnd();
    });
    this.fetchData();
  },
  async asyncData({ ...params }) {
    let dealDataObj = new PersonalSeoData(params);
    let ans = await dealDataObj.dealData();

    return {
      ...ans
    };
  },
  destroy: function() {
    window.onscroll = null;
  },
  methods: {
    resetTab() {
      this.list = [];
      this.page = 0;
      this.isMore = true;
      this.pageSize = 10;
      this.pageLoading = false;

      this.fetchData();
    },
    async fetchData() {
      if (this.pageLoading || !this.isMore) return;
      this.pageLoading = true;

      let page = this.page + 1;

      let tabSelected = this.tabSelected;
      let uid = this.personUid;
      let res;
      let list = [];
      if (tabSelected == 1) {
        res = await this.$axios.post("/uapi/dynamic/get_dynamic_list_my", {
          to_uid: uid,
          page: page,
          pagesize: this.pageSize
        });
        list = res.data.data.list;
      } else if (tabSelected == 2) {
        res = await this.$axios.post("/uapi/news/index/list", {
          uid: uid,
          page: page,
          pagesize: this.pageSize
        });
        list = res.data.data.list;
      } else if (tabSelected == 3) {
        res = await this.$axios.post("/uapi/goods/video/list", {
          to_uid: uid,
          page: 1,
          pagesize: 1
        });
        list = res.data.data.list;
      }

      if (Number(res.data.status) === 1) {
        setTimeout(() => {
          this.pageLoading = false;
        }, 100);
        this.page = page;
        this.list.push(...list);
        this.isMore = list.length < this.pageSize ? false : true;
      } else if (Number(res.status) === 40001) {
        this.isExist = false;
      }
    },
    listenToEnd() {
      let that = this;
      window.onscroll = function() {
        var scrollTop =
          document.documentElement.scrollTop || document.body.scrollTop;
        var windowHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
        var scrollHeight =
          document.documentElement.scrollHeight || document.body.scrollHeight;

        if (scrollHeight - scrollTop - windowHeight < 400) {
          that.fetchData();
        }
      };
    },
    linkToThirdParty(content, type) {
      let link = "";
      switch (type) {
        case "github_name":
          link = `https://github.com/${content}`;
          break;
        case "gitee_name":
          link = `https://gitee.com/${content}`;
          break;
        case "csdn_name":
          link = `https://blog.csdn.net/${content}`;
          break;
        case "wechat_name":
          // link = `https://blog.csdn.net/${content}`;
          break;
        case "juejin_name":
          link = "";
          break;
      }

      link && window.open(link, "view_window");
    },
    toggleFollow() {
      if (this.isFollowing) {
        this.unFollow();
      } else {
        this.follow();
      }
    },
    async follow() {
      if (this.pageLoading) return;
      this.pageLoading = true;
      let res = await this.$axios.$post("/uapi/dynamic/add_followers", {
        to_uid: this.personUid
      });
      this.pageLoading = false;
      if (Number(res.status) === 1) {
        this.isFollowing = true;
        this.personalUserInfo.followers_my++;
      }
    },
    async unFollow() {
      if (this.pageLoading) return;
      this.pageLoading = true;
      let res = await this.$axios.$post("/uapi/dynamic/del_followers", {
        to_uid: this.personUid
      });
      this.pageLoading = false;
      if (Number(res.status) === 1) {
        this.isFollowing = false;
        this.personalUserInfo.followers_my--;
      }
    },
    callBindWeChat() {
      this.$refs["bindWeChat"].show({
        name: this.userinfo.nickname,
        uid: this.userinfo.uid,
        avatar: this.userinfo.icon_url
      });
    },
    unbindWeChat(){
      this.$refs['unBindWeChat'].show()
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/css/frontend/personal.scss";

.auto-bind-wechat {
  text-align: center;
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #0b121a;
  margin-top: 16px;
  span {
    color: #308eff;
    cursor: pointer;
  }
}
</style>
