<template>
  <view>
    <zj-page-layout
      :isScroll="true"
      :isWxCustomPage="true"
      :isLoading="isLoading"
      :refresherTriggered="refresherTriggered"
      @refresherrefresh="refresherrefresh"
    >
      <!-- <template slot="header">
        <view class="header-container" :style="cuStyle">我的</view>
      </template> -->
      <view class="a-container">
        <view class="top-container">
          <view class="user" v-if="isLogin">
            <view class="left" @tap="navToPage('/packageMine/pages/userinfo')">
              <block v-if="userInfo.avatar">
                <image :src="userInfo.avatar" mode="aspectFill" v-if="userInfo.avatar.indexOf('http') >= 0"></image>
                <image :src="imageUrl + userInfo.avatar" mode="aspectFill" v-else></image>
              </block>

              <view class="main">
                <view class="name">{{ userInfo.nickName }}</view>
                <view class="text">点击修改个人资料<text class="iconfont icon-jinru"></text></view>
              </view>
            </view>
            <view class="right">
              <view class="it" v-if="(isServiceUser || isWorkerUser) && qrcode2" @tap="openCode">
                <text class="iconfont icon-erweima"></text>
              </view>
              <view class="it" @tap="navToPage('/packageMine/pages/notice/list')">
                <u-icon name="chat" size="30"></u-icon>
                <u-badge max="99" :value="noticeNum || 0" absolute :offset="[-2, -2]"></u-badge>
              </view>
            </view>
          </view>
          <view class="user" @tap="navToPage('/pages/login/indexs')" v-else>
            <view class="left">
              <image :src="configInfo.minLogo3" mode="aspectFill"></image>
              <view class="main">
                <view class="name">请先登录</view>
              </view>
            </view>
          </view>

          <!-- <view class="stats">
            <view
              class="item"
              v-for="(item, index) in statsList.filter(o => o.show)"
              :key="index"
              @tap="navToPage(item.link)"
            >
              <view class="value">{{ item.num }}</view>
              <view class="label">{{ item.name }}</view>
            </view>
          </view> -->
        </view>

        <view class="all-container">
          <!-- <view class="profit-container card" v-if="isLogin && (isServiceUser || isWorkerUser)">
            <view class="home-title">
              <view class="left">分销收益</view>
              <view class="right" @tap="navToPage('/packageMine/pages/profit/list', 1)">
                <text class="text">明细</text>
                <text class="iconfont icon-jinru"></text>
              </view>
            </view>
            <view class="list">
              <view
                class="item"
                v-for="(item, index) in shareProfitList"
                :key="index"
                @tap="navToPage('/packageMine/pages/profit/list', 1)"
              >
                <view class="num">{{ item.num | priceFilter }}</view>
                <view class="title">{{ item.title }}</view>
              </view>
            </view>
          </view> -->

          <view class="profit-container card" v-if="isLogin && isWorkerUser">
            <view class="home-title">
              <view class="left">销售收益</view>
              <view class="right" @tap="navToPage('/packageMine/pages/salesProfit/index', 1)">
                <text class="text">明细</text>
                <text class="iconfont icon-jinru"></text>
              </view>
            </view>
            <view class="list">
              <view
                class="item"
                v-for="(item, index) in salesProfitList"
                :key="index"
                @tap="navToPage('/packageMine/pages/salesProfit/index', 1)"
              >
                <view class="num">{{ item.num | priceFilter }}</view>
                <view class="title">{{ item.title }}</view>
              </view>
            </view>
          </view>

          <!-- <view class="order-container card">
            <view class="home-title">
              <view class="left">我的订单</view>
              <view class="right" @tap="navToPage('/packageMine/pages/order/list?tab=', 1)">
                <text class="text">全部订单</text>
                <text class="iconfont icon-jinru"></text>
              </view>
            </view>
            <view class="list">
              <view
                class="item"
                v-for="(item, index) in orderList"
                :key="index"
                @tap="navToPage(`/packageMine/pages/order/list?tab=${item.key}`, 1)"
              >
                <view class="icon">
                  <text class="iconfont" :class="item.icon"></text>
                  <u-badge max="99" :value="item.num" :absolute="true" :offset="[-4, -4]"></u-badge>
                </view>
                <view class="title">{{ item.title }}</view>
              </view>
            </view>
          </view> -->

          <view class="menu-container card">
            <view class="home-title">
              <view class="left">更多服务</view>
            </view>
            <view class="list">
              <block v-for="(item, index) in menuList.filter(o => o.show)" :key="index">
                <button
                  v-if="item.fn == 'phone'"
                  open-type="getPhoneNumber"
                  @getphonenumber="getPhoneNumber"
                  class="item"
                >
                  <view class="icon"><text class="iconfont" :class="item.icon"></text></view>
                  <view class="title">{{ item.name }}</view>
                  <view class="right"><text class="iconfont icon-jinru"></text></view>
                </button>
                <button v-else-if="item.fn == 'contact'" open-type="contact" class="item">
                  <view class="icon"><text class="iconfont" :class="item.icon"></text></view>
                  <view class="title">{{ item.name }}</view>
                  <view class="right"><text class="iconfont icon-jinru"></text></view>
                </button>
                <view
                  v-else-if="item.icon == 'coupon'"
                  class="item"
                  @tap="item.link ? navToPage(item.link, 1) : actionFn(item.fn)"
                >
                  <view class="icon"><u-icon size="20" :name="item.icon"></u-icon></view>
                  <view class="title">{{ item.name }}</view>
                  <view class="right"><text class="iconfont icon-jinru"></text></view>
                </view>
                <view v-else class="item" @tap="item.link ? navToPage(item.link, 1) : actionFn(item.fn)">
                  <view class="icon"><text class="iconfont" :class="item.icon"></text></view>
                  <view class="title">{{ item.name }}</view>
                  <view class="right"><text class="iconfont icon-jinru"></text></view>
                </view>
              </block>
            </view>
          </view>
          <!-- <no-data v-if="!isLogin" :showText="'请先登录'" @tap="navToPage('/pages/login/indexs')"></no-data> -->

          <!-- <view class="logout" @tap="toLogout()" v-if="isLogin">退出登录</view> -->
        </view>
      </view>
    </zj-page-layout>
  </view>
</template>

<script>
import { getNoticeNum, getOrderNum, selectionChange } from '@/common/utils/util.js'
import { getStorage } from '@/common/utils/storage.js'
export default {
  data() {
    return {
      isLoading: true,
      refresherTriggered: false, // 下拉刷新状态
      imageUrl: this.$imageUrl,
      configInfo: {},
      userInfo: {}, // 信息详情
      shareProfitList: [
        { title: '今日分销收益', num: 0 },
        { title: '累计分销收益', num: 0 }
      ],
      salesProfitList: [
        { title: '已结算金额', num: 0 },
        { title: '待结算金额', num: 0 }
      ],
      orderList: [
        { title: '待付款', icon: 'icon-daifukuan', key: 'NOPAY', num: 0 },
        { title: '进行中', icon: 'icon-daifuwu', key: 'YFH', num: 0 },
        { title: '待评价', icon: 'icon-daipingjia1', key: 'OVER', num: 0 },
        { title: '售后/退款', icon: 'icon-shouhou', key: 'REFUND', num: 0 }
      ],
      statsList: [],
      menuList: [],
      noticeNum: 0,
      qrcode2: ''
    }
  },
  computed: {
    mobile() {
      return this?.userInfo?.mobile
    },
    cuStyle() {
      return `height: ${this.CustomBar - this.StatusBar}px; padding-top: ${this.StatusBar}px;`
    },
    isLogin() {
      return this.$store.state.user.token ? true : false
    },
    isWorkerUser() {
      // 是否师傅
      // return true;
      return this.userInfo && this.userInfo.type === 'WORKER'
    },
    isServiceUser() {
      // 是否业务员
      // return true;
      return this.userInfo && this.userInfo.type === 'SERVICE'
    },
    isHeadUser() {
      // 是否团长
      // return false;
      return this.userInfo && this.userInfo.promotionGroupLeader
    }
  },

  async onShow() {
    selectionChange()

    this.configInfo = await this.$getConfigInfo()

    // if(this.isLogin) {
    this.userInfo = await this.$getUserInfo()
    await this.getCouponList()
    this.initList()
    await this.getCount()
    await this.getShareProfitCount()
    await this.getSalesProfitCount()
    await this.getStats()
    this.getweixinpeizhi()
    // }

    this.noticeNum = await getNoticeNum()
    getOrderNum()

    this.isLoading = false
  },

  methods: {
    // 触发下拉刷新
    async refresherrefresh(e) {
      this.refresherTriggered = true

      this.configInfo = await this.$getConfigInfo()
      // if(this.isLogin) {
      this.userInfo = await this.$getUserInfo()
      await this.getCouponList()
      this.initList()
      await this.getCount()
      await this.getShareProfitCount()
      await this.getSalesProfitCount()
      await this.getStats()
      // }

      this.noticeNum = await getNoticeNum()

      this.isLoading = false
      this.refresherTriggered = false
    },

    initList() {
      this.statsList = [
        {
          name: '优惠券',
          num: 0,
          link: '/packageMine/pages/coupon/list',
          show: true
        },
        {
          name: '收藏',
          num: 0,
          link: '/packageMine/pages/collection',
          show: true
        },
        {
          name: '收益',
          num: 0,
          link: '/packageMine/pages/profit/list',
          show: this.isServiceUser || this.isWorkerUser || this.isHeadUser
        }
      ]
      this.menuList = [
        // {
        //   name: '我的租赁',
        //   icon: 'coupon',
        //   link: '/packageWorkorder/pages/tenancyOrderList',
        //   show: this.userInfo.isShowLease
        // },
        {
          name: '绑定手机号',
          icon: 'icon-kefu',
          link: '/packageMine/pages/phone',
          show: !this.userInfo.mobile
        },
        // {
        //   name: '商城二维码',
        //   icon: 'icon-erweima',
        //   link: '/packageMine/pages/mallCode',
        //   show: this.isServiceUser || this.isWorkerUser
        // },
        // // {
        // //   name: '关注公众号',
        // //   icon: 'icon-gongzhonghao',
        // //   fn: 'toWxLink',
        // //   show: true
        // // },
        // {
        //   name: '地址管理',
        //   icon: 'icon-shouhuodizhi',
        //   link: '/packageMine/pages/address/list',
        //   show: true
        // },
        // {
        //   name: '销售排行榜',
        //   icon: 'icon-paihangbang',
        //   link: '/packageMine/pages/ranking/list',
        //   show: this.isServiceUser || this.isWorkerUser
        // },
        // // {
        // //   name: '在线客服',
        // //   icon: 'icon-kefu',
        // //   fn: 'contact',
        // //   show: true
        // // },
        {
          name: '师傅入驻',
          icon: 'icon-kehu',
          link: '/packageMine/pages/myWebsit',
          show: true
        },
        // {
        //   name: '成为分销员',
        //   icon: 'icon-kehu',
        //   link: '/packageMine/pages/distributorEnter',
        //   show: !this.isWorkerUser && !this.isServiceUser
        // },
        {
          name: '我的安维费',
          icon: 'icon-kehu',
          link: '/packageMine/pages/wodeanwei',
          show: this.isWorkerUser
        },
        {
          name: '中心文件',
          icon: 'icon-kehu',
          link: '/packageMine/pages/coreLssuedFile/index',
          show: this.isWorkerUser
        },
        {
          name: '师傅组别',
          icon: 'icon-kehu',
          link: '/packageMine/pages/masterGroup/index',
          show: this.isWorkerUser
        },
        {
          name: '师傅签名确认书',
          icon: 'icon-kehu',
          link: '/pages/signatureConfirmation',
          show: this.isWorkerUser
        },
        {
          name: '我的保单',
          icon: 'icon-kehu',
          link: '/packageEnter/pages/insurance/myInsurance/index',
          show: true
        },
        {
          name: '修改手机号',
          icon: 'icon-kehu',
          link: '/packageMine/pages/phoneUpdate',
          show: this.mobile
        }
      ]
    },

    actionFn(fn) {
      if (!fn) return false
      this[fn]()
    },

    // 授权手机号
    getPhoneNumber(e) {
      if (!e.detail.iv) {
        return this.$toast('获取手机号失败')
      }
      uni.login({
        provider: 'weixin',
        success: loginRes => {
          this.$api
            .post('/user/auth', {
              code: loginRes.code,
              phoneCode: e.detail.code
            })
            .then(async res => {
              this.$store.commit('user/set_token', res.data.token)
              this.$store.commit('user/set_openId', res.data.openId)
              this.$store.commit('user/set_name', res.data.nickName)
              this.$store.commit('user/set_avatar', res.data.avatar)
              this.$store.commit('user/set_userId', res.data.userId)
              this.$store.commit('user/set_mobile', res.data.mobile)
              this.$successToast('授权成功')
            })
        }
      })
    },

    // 获取订单数量
    async getCount() {
      return new Promise((resolve, reject) => {
        this.$api
          .get('/order/count', {
            userId: this.$store.state.user.userId
          })
          .then(res => {
            const data = res.data || {}
            this.orderList[0].num = data.noPay
            this.orderList[1].num = data.yfh
            this.orderList[2].num = data.ywc
            this.orderList[3].num = data.sh
            resolve(data)
          })
          .catch(res => {
            resolve(1)
          })
      })
    },

    // 获取统计数量
    async getStats() {
      return new Promise((resolve, reject) => {
        this.$api
          .get('/user/my/count', {
            userId: this.$store.state.user.userId
          })
          .then(res => {
            const data = res.data || {}
            this.statsList[0].num = data.coupon || 0
            this.statsList[1].num = data.collect || 0
            this.statsList[2].num = data.amount || 0
            resolve(data)
          })
          .catch(res => {
            resolve(1)
          })
      })
    },

    // 获取收益统计
    async getShareProfitCount() {
      return new Promise((resolve, reject) => {
        this.$api
          .get('/user/profit', {
            userId: this.$store.state.user.userId
          })
          .then(res => {
            const data = res.data || {}
            this.shareProfitList[0].num = data.today
            this.shareProfitList[1].num = data.totalAmount
            resolve(data)
          })
          .catch(res => {
            resolve(1)
          })
      })
    },

    // 获取销售收益统计
    async getSalesProfitCount() {
      return new Promise((resolve, reject) => {
        this.$api
          .post('/withdrawal/amount/count')
          .then(res => {
            const data = res.data || {}
            this.salesProfitList[0].num = data.yjs
            this.salesProfitList[1].num = data.djs
            resolve(data)
          })
          .catch(res => {
            resolve(1)
          })
      })
    },

    // 获取可领优惠券列表
    async getCouponList() {
      return new Promise((resolve, reject) => {
        this.$api
          .get('/coupon/list/all', {
            userId: this.$store.state.user.userId
          })
          .finally(res => {
            resolve(1)
          })
      })
    },

    getweixinpeizhi() {
      this.$api.get('/common/wechat/detail').then(res => {
        this.qrcode2 = res.data.qrcode2
      })
    },

    openCode() {
      this.$api
        .post('/common/get/mp/qrcode', {
          companyWechatId: getStorage('user').companyWechatId || '',
          userId: this.$store.state.user.userId
        })
        .then(res => {
          uni.previewImage({
            current: res.data.ticket
              ? `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${res.data.ticket}`
              : this.qrcode2,
            urls: [
              res.data.ticket ? `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${res.data.ticket}` : this.qrcode2
            ]
          })
        })
    },

    // 跳转微信公众号链接
    toWxLink() {
      let link = this.configInfo.pubOfficeAddr
      if (!link) return false
      this.navToPage('/pages/index/webview?link=' + link)
    },

    navToPage(url) {
      this.$navToPage({
        url
      })
    },

    toLogout() {
      this.$modal({
        content: '确定退出登录？'
      })
        .then(() => {
          this.$store.dispatch('user/resetToken')
          console.log(this.configInfo)
          // this.crossPage.$emit('loginout', '', 'H5');
          this.shareProfitList.forEach(item => {
            item.num = 0
          })
          this.orderList.forEach(item => {
            item.num = 0
          })
          this.statsList.forEach(item => {
            item.num = 0
          })
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped lang="scss">
.a-container {
  padding-bottom: 30rpx;
}

.header-container {
  background: linear-gradient(262deg, #daf8fa 0%, #d3e6fc 84%, #d2e2fc 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
}

.top-container {
  background: linear-gradient(262deg, #daf8fa 0%, #d3e6fc 84%, #d2e2fc 100%);
  padding: 20rpx 20rpx 80rpx;

  .user {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 10rpx;

    .left {
      display: flex;
      align-items: center;

      image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }

      .main {
        display: flex;
        flex-direction: column;

        .name {
          font-size: 32rpx;
          line-height: 36rpx;
          font-weight: 500;
        }

        .text {
          font-size: 24rpx;
          color: #0b2853;
          line-height: 30rpx;
          margin-top: 12rpx;
          opacity: 0.5;

          .iconfont {
            font-size: 20rpx;
            margin-left: 8rpx;
          }
        }
      }
    }

    .right {
      display: flex;
      align-items: center;

      .it {
        margin-left: 40rpx;
        position: relative;

        &:first-child {
          margin-left: 0;
        }

        .iconfont {
          display: block;
          font-size: 44rpx;
        }
      }
    }
  }

  .stats {
    display: flex;
    align-items: center;
    margin-top: 20rpx;

    .item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .value {
        font-weight: 600;
        font-size: 36rpx;
      }

      .label {
        margin-top: 8rpx;
        font-size: 22rpx;
        color: #0b2853;
        opacity: 0.5;
      }
    }
  }
}

.all-container {
  padding: 1rpx 20rpx 20rpx;
  margin-top: -80rpx;
}

.home-title {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .left {
    font-size: 34rpx;
    color: $main-font;
    font-weight: bold;
  }

  .right {
    display: flex;
    align-items: center;

    .text {
      font-size: 28rpx;
      color: $sec-font;
    }

    .iconfont {
      font-size: 24rpx;
      color: $sec-font;
      margin-left: 8rpx;
    }
  }
}

.card {
  @include zj-card;
  background: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
  padding: 30rpx;
  margin-top: 20rpx;
}

.profit-container {
  .list {
    display: flex;
    margin-top: 30rpx;

    .item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .num {
        font-size: 36rpx;
        font-weight: 500;
      }

      .title {
        font-size: 24rpx;
        margin-top: 8rpx;
      }
    }
  }
}

.order-container {
  .list {
    display: flex;
    margin-top: 30rpx;

    .item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .icon {
        position: relative;

        .iconfont {
          font-size: 52rpx;
        }
      }

      .title {
        font-size: 26rpx;
        margin-top: 10rpx;
      }
    }
  }
}

.menu-container {
  .list {
    margin-top: 20rpx;

    .item {
      padding: 0;
      background: none;
      text-align: left;
      display: flex;
      align-items: center;
      height: 100rpx;
      border-bottom: 1px solid #f5f5f5;
      color: #333333;

      &:last-child {
        border: none;
      }

      &::after {
        border: none;
      }

      .icon {
        margin-right: 20rpx;

        .iconfont {
          color: $reg-font;
          font-size: 40rpx;
        }
      }

      .title {
        flex: 1;
        font-size: 30rpx;
      }

      .right {
        .iconfont {
          font-size: 28rpx;
          color: $sec-font;
        }
      }
    }
  }
}

.logout {
  @include zj-card;
  background: #ffffff;
  border-radius: 20rpx;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  margin-top: 30rpx;
  font-size: 32rpx;
  font-weight: 400;
  color: $theme-color;
}
</style>
