<template>
  <view class="container">
    <!--用户信息-->
    <view class="header main-between cross-center">
      <view class="user-box main-left cross-center">
        <view class="head-img">
          <!--   #ifdef  MP-KUAISHOU | MP-TOUTIAO   -->
          <image :src="userInfo.avatar?userInfo.avatar:'/static/image/default-head-img.png'" />
          <!--   #endif  -->
          <!--   #ifdef  MP-WEIXIN   -->
          <button class="avatar cross-center" @click="handleGetWechatUserInfo">
            <image :src="userInfo.avatar?userInfo.avatar:'/static/image/default-head-img.png'" />
          </button>
          <!--   #endif  -->
        </view>
        <view class="base">
          <!--   #ifdef  MP-KUAISHOU | MP-TOUTIAO   -->
          <view v-if="!userInfo.nickname" class="nickname cross-center" @click="handleGetUserInfo">未授权登陆</view>
          <!--   #endif  -->
          <!--   #ifdef  MP-WEIXIN   -->
          <view v-if="!userInfo.nickname" class="nickname cross-center" @click="handleGetWechatUserInfo">未授权登陆</view>
          <!--   #endif  -->
          <view v-if="userInfo.nickname" class="nickname cross-center">{{ userInfo.nickname }}</view>
          <view v-if="userInfo.info.is_vip" class="vip cross-center">
            VIP到期时间: {{ userInfo.info.end_at }}
          </view>
        </view>
      </view>
      <!--   #ifdef  MP-KUAISHOU | MP-TOUTIAO   -->
      <button open-type="getUserInfo" class="refresh" @click="handleGetUserInfo">刷新</button>
      <!--   #endif  -->
      <!--   #ifdef  MP-WEIXIN   -->
      <button open-type="getUserInfo" class="refresh" @click="handleGetWechatUserInfo">刷新</button>
      <!--   #endif  -->
    </view>
    <!--充值-->
    <view class="recharge main-between cross-center">
      <view class="static-box main-left cross-center">
        <view class="icon">
          <image src="/static/image/gold-bag.png" mode="aspectFill" />
        </view>
        <view class="overage">{{ userInfo.info.integral }}金币</view>
      </view>
      <view class="recharge-btn" @click="recharge.show = true">充值</view>
    </view>
    <!--历史-->
    <view class="history" @click="$u.route('/pages/my/history')">
      <view class="header main-between cross-center">
        <text>历史观看记录</text>
        <u-icon name="arrow-right" :color="$colors.infoColor" bold />
      </view>
      <view class="content dir-left-nowrap cross-center">
        <view
          v-for="(item,index) in history"
          :key="index"
          class="episode"
        >
          <view class="cover-image">
            <image :src="item.detail.episode.cover_img" mode="aspectFill" />
          </view>
        </view>
      </view>
    </view>
    <!--菜单-->
    <view class="menu-group">
      <template v-for="(menu,index) in menus">
        <button
          v-if="menu.href !== '/pages/share/index' || (menu.href === '/pages/share/index' && userInfo.is_share !== '0')"
          :key="index"
          class="menu-item main-between cross-center"
          :open-type="menu.type ? menu.type : ''"
          @bindcontact="handleMenu"
          @click="handleMenu(menu)"
        >
          <view class="left-box dir-left-nowrap cross-center">
            <view class="icon">
              <image :src="menu.icon" />
            </view>
            <text>{{ menu.name }}</text>
          </view>
          <u-icon name="arrow-right" :color="$colors.infoColor" bold />
        </button>
      </template>
    </view>
    <!--tab bar-->
    <tab-bar />
    <!--充值-->
    <recharge :show.sync="recharge.show" />
    <!--   #ifdef  MP-WEIXIN   -->
    <u-modal
      :show="modal.show"
      :title="modal.title"
      :show-confirm-button="false"
    >
      <view class="slot-content dir-top-wrap cross-center">
        <button open-type="chooseAvatar" class="avatar cross-center" @chooseavatar="handleChooseAvatar">
          <image :src="modal.avatar?modal.avatar:'/static/image/default-head-img.png'" />
        </button>
        <input
          class="nickname cross-center"
          type="nickname"
          :value="modal.nickname"
          placeholder="填写昵称"
          @change="handleChangeNickname"
        >

        <button class="confirm" @click="handleConfirmWechatUserInfo">提交</button>
      </view>
    </u-modal>
    <!--   #endif  -->
  </view>
</template>

<script>
import TabBar from '../../components/TabBar/index'
import { mapState } from 'vuex'
import Recharge from '../../components/Recharge/index'
export default {
  name: 'My',
  components: { Recharge, TabBar },
  data() {
    return {
      history: [],
      menus: [
        { icon: '/static/image/my-page/order.png', name: '消费记录', href: '/pages/my/consume' },
        { icon: '/static/image/my-page/recharge.png', name: '充值记录', href: '/pages/my/recharge' },
        { icon: '/static/image/my-page/contact.png', name: '联系客服', type: 'contact' },
        { icon: '/static/image/my-page/share.png', name: '分享中心', href: '/pages/share/index' },
        { icon: '/static/image/my-page/protocol.png', name: '用户协议', href: '/pages/my/protocol' }
      ],
      recharge: {
        show: false
      },
      code: null,
      config: {},
      modal: {
        show: false,
        title: '用户信息获取',
        nickname: '',
        avatar: ''
      },
      btnLock: false
    }
  },
  computed: {
    ...mapState({
      userInfo: seate => seate.user.info
    })
  },
  methods: {
    getHistory() {
      this.$api.user.episode.record({ limit: 3 }).then(res => {
        this.history = res.data
      })
    },
    handleMenu(menu) {
      // #ifdef MP-KUAISHOU
      if (menu.type === 'contact') {
        ks.makePhoneCall({
          phoneNumber: this.config.contact,
          success(res) {
            console.log('-->success', res)
          },
          fail(err) {
            console.log('-->error', err)
          }
        })
      }
      // #endif
      if (menu.href) {
        this.$u.route(menu.href)
      }
    },
    // 微信获取头像
    handleGetWechatUserInfo() {
      this.modal.show = true
      this.modal.nickname = this.userInfo.nickname
      this.modal.avatar = this.userInfo.avatar
    },
    // 微信获取头像
    handleChooseAvatar({ detail }) {
      const _this = this
      uni.getFileSystemManager().readFile({
        filePath: detail.avatarUrl, // 选择图片返回的相对路径
        encoding: 'base64', // 编码格式
        success: res => { // 成功的回调
          uni.uploadFile({
            url: _this.$setting.BASE_URL + '/avatar/upload',
            // filePath: 'data:image/png;base64,' + res.data,
            filePath: detail.avatarUrl,
            name: 'file',
            success({ data }) {
              const res = JSON.parse(data)
              const { url } = res.data
              _this.modal.avatar = url
              console.log('-->data', _this.modal.avatar)
            }
          })
          // this.modal.avatar = detail.avatarUrl
          // console.log('data:image/png;base64,' + res.data)
        }
      })
    },
    handleChangeNickname(res) {
      this.modal.nickname = res.detail.value
    },
    // 微信获取头像
    handleConfirmWechatUserInfo() {
      console.log('-->data', this.modal)
      if (!this.modal.avatar) {
        this.$u.toast('请上传头像')
        return
      }
      if (!this.modal.nickname) {
        this.$u.toast('请填写昵称')
        return
      }
      this.$loading('数据提交中...')
      this.$api.user.update({ avatar: this.modal.avatar, nickname: this.modal.nickname }).then(res => {
        this.code = null
        this.$hideLoading()
        this.$store.dispatch('user/info', res.data)
        this.modal.show = false
      }).catch(() => {
        this.$hideLoading()
      })
    },
    handleGetUserInfo(res) {
      if (this.btnLock) return
      this.btnLock = true
      // #ifdef  MP-KUAISHOU
      this.$loading('数据刷新中...')
      uni.authorize({
        scope: 'scope.userInfo',
        success: () => {
          uni.getUserInfo({
            withCredentials: true,
            success: res => {
              this.getCode().then(code => {
                const params = {
                  encryptedData: res.encryptedData,
                  iv: res.iv,
                  signature: res.signature,
                  code: code
                }
                this.$api.user.update(params).then(res => {
                  this.btnLock = false
                  this.code = null
                  this.$hideLoading()
                  this.$store.dispatch('user/info', res.data)
                }).catch(() => {
                  this.code = null
                  this.btnLock = false
                  this.$hideLoading()
                })
              })
            },
            fail: () => {
              this.btnLock = false
            }
          })
        },
        fail: () => {
          this.btnLock = false
        }
      })
      // #endif
      // #ifdef  MP-TOUTIAO
      uni.getUserProfile({
        success: res => {
          this.getCode().then(code => {
            const params = {
              encryptedData: res.encryptedData,
              iv: res.iv,
              signature: res.signature,
              code: code
            }
            this.$loading('数据刷新中...')
            this.$api.user.update(params).then(res => {
              this.btnLock = false
              this.code = null
              this.$hideLoading()
              this.$store.dispatch('user/info', res.data)
            }).catch(() => {
              this.code = null
              this.btnLock = false
              this.$hideLoading()
            })
          })
        },
        fail: () => {
          this.btnLock = false
        }
      })
      // #endif
    },
    getCode() {
      return new Promise((resolve, reject) => {
        if (this.code) {
          return resolve(this.code)
        }
        uni.login({
          provider: uni.$u.platform,
          success: loginRes => {
            this.code = loginRes.code
            // 四分钟失效
            setTimeout(() => {
              this.code = null
            }, 1000 * 4 * 60)
            resolve(this.code)
          },
          fail: () => {
            this.btnLock = false
            reject()
          }
        })
      })
    },
    getConfig() {
      this.$api.setting.config().then(res => {
        this.config = res.data
      })
    }
  },
  onShow() {
    this.getHistory()
    this.getConfig()
  }
}
</script>

<style lang="scss" scoped>
  .container {
    padding: 20px 20rpx 180rpx;
    font-size: 30rpx;
    >.header{
      .user-box{
        .head-img{
          .avatar{
            background: transparent;
          }
          image{
            width: 100rpx;
            height: 100rpx;
            border-radius: 50%;
          }
        }
        .base{
          margin-left: 30rpx;
          .nickname{
            color: $primary-color;
            font-size: 32rpx;
          }
          .vip{
            font-size: 22rpx;
            color: #fff;
            margin-top: 6rpx;
          }
        }
      }
      .refresh{
        background: $primary-color;
        color: #fff;
        border-radius: 30rpx;
        padding: 10rpx 0;
        width: 140rpx;
        text-align: center;
        letter-spacing: .1rem;
        line-height: initial;
      }
    }
    .recharge{
      background: url("/static/image/my-recharge-bg.png") no-repeat center;
      background-size: 100%;
      height: 200rpx;
      margin-top: 20rpx;
      margin-bottom: 10rpx;
      .static-box{
        margin-left: 30rpx;
        .icon{
          border-radius: 20rpx;
          image{
            width: 100rpx;
            height: 100rpx;
          }
        }
        .overage{
          font-weight: 800;
          margin-left: 20rpx;
          font-size: 32rpx;
        }
      }
      .recharge-btn{
        border: 1rpx solid #fff;
        padding: 10rpx 0 ;
        text-align: center;
        width: 140rpx;
        margin-right: 20rpx;
        border-radius: 30rpx;
        color: #ffffff;
      }
    }
    .history{
      background: $bg-op-color;
      height: 300rpx;
      border-radius: 15rpx;
      padding: 20rpx 30rpx;
      margin-bottom: 40rpx;
      >.header{
        text{
          color: $info-color;
          font-weight: 600;
        }
      }
      .content{
        margin-top: 20rpx;
        .episode{
          width: calc(100%/4);
          margin-left: 20rpx;
          &:first-child{
            margin-left: 0;
          }
          .cover-image{
            image{
              width: 100%;
              height: 200rpx;
              border-radius: 16rpx;
            }
          }
        }
      }
    }
    .menu-group{
      .menu-item{
        padding: 20rpx 0;
        background: transparent;
        border: none;
        text-align: unset;
        width: 100%;
        line-height: initial;
        font-size: initial;
        justify-content: space-between;
        &:after{
          content: unset;
        }
        .left-box{
          flex: 1;
          .icon{
            transform: translateY(4rpx);
            image{
              width: 55rpx;
              height: 55rpx;
            }
          }
          text{
            color: #fff;
            margin-left: 10rpx;
          }
        }
      }
    }
    /* 微信获取用户信息 弹窗*/
    .slot-content{
      width: 100%;
      .avatar{
        background: transparent;
        &:after{
          content: unset;
        }
        image{
          width: 140rpx;
          height: 140rpx;
          border-radius: 50%;
        }
      }
      .nickname{
        width: 100%;
        margin: 30rpx 0 50rpx;
        border: 1rpx solid #ccc;
        padding: 0 20rpx;
        height: 76rpx;
        line-height: 76rpx;
        border-radius: 10rpx;
      }
      .confirm{
        background: $primary-color;
        color: #fff;
        border-radius: 30rpx;
        padding: 12rpx 0;
        width: 100%;
        text-align: center;
        letter-spacing: .1rem;
        line-height: initial;
      }
    }
  }
</style>
