<template>
  <!-- auto设为false，在请求完用户信息后手动刷新 -->
  <z-paging
    ref="paging"
    v-model="likeProdData"
    :auto="false"
    :refresher-enabled="false"
    :default-page-size="10"
    :safe-area-inset-bottom="false"
    :auto-scroll-to-top-when-reload="false"
    :auto-clean-list-when-reload="false"
    :paging-style="{'top': '0','background': '#f2f3f7','bottom': 'var(--window-bottom)'}"
    @query="onGetLikeProdList"
  >
    <view class="Mall4j page-my">
      <!-- 用户资料 -->
      <view class="user-box">
        <view
          class="img"
          @tap="onRouteToUrl('user-settings')"
        >
          <image
            v-if="userDetails.pic && isUserPic"
            :src="util.addDomain(userDetails.pic)"
            @error="imgError"
          />
          <image
            v-else
            src="/static/images/head-sculpture.png"
          />
        </view>
        <view
          v-if="isNotLogged"
          class="text-box"
          @tap="onToLogin"
        >
          <view class="name">
            立即登录
          </view>
        </view>
        <view
          v-if="!isNotLogged"
          class="text-box"
          @tap="onRouteToUrl('user-settings')"
        >
          <view class="name">
            {{ userDetails.nickName }}
          </view>
          <view class="level">
            <view :class="['level-style', userDetails.levelType === 1 ? 'vip' : '']">
              {{ userDetails.levelType === 1 ? 'VIP' : '普通' }}
            </view>
            <view :class="'level-name '+ (userDetails.levelType === 1 ? 'vip' : '')">
              {{ userDetails.levelType === 1 ? userDetails.vipLevelName : userDetails.levelName }}
            </view>
          </view>
        </view>
        <view
          v-if="!isNotLogged"
          class="sign-in"
        >
          <image
            src="/static/images/codes.png"
            @tap="onSacnCode"
          />
          <image
            src="/static/images/sign-in.png"
            @tap="onSubPackageRoute('sign-in')"
          />
        </view>
      </view>

      <!-- 用户资产 -->
      <view class="user-assets">
        <view class="item">
          <view
            v-if="isNotLogged"
            class="number"
            @tap="onSubPackageRoute('my-balance')"
          >
            -
          </view>
          <view
            v-else
            class="number visible"
            @tap="onSubPackageRoute('my-balance')"
          >
            <text> {{ formatBalance }}</text>
          </view>
          <view class="text">
            余额
          </view>
        </view>
        <view
          class="item"
          @tap="onSubPackageRoute('my-integral')"
        >
          <view
            v-if="isNotLogged"
            class="number"
          >
            -
          </view>
          <view
            v-else
            class="number visible"
          >
            {{ formatScore || 0 }}
          </view>
          <view class="text">
            积分
          </view>
        </view>
        <view
          class="item"
          @tap="onSubPackageRoute('my-coupons')"
        >
          <view
            v-if="isNotLogged"
            class="number"
          >
            -
          </view>
          <view
            v-else
            class="number"
          >
            {{ userInfo.couponNum || 0 }}
          </view>
          <view class="text">
            优惠券
          </view>
        </view>
        <view
          class="item"
          @tap="onRouteToUrl('message-platform')"
        >
          <view
            v-if="isNotLogged"
            class="number"
          >
            -
          </view>
          <view
            v-else
            class="number"
          >
            {{ unreadSystemMessagesNum }}
          </view>
          <view class="text">
            消息
          </view>
        </view>
      </view>

      <!-- 开通会员 -->
      <view
        class="open-vip"
        @tap="onSubPackageRoute('member')"
      >
        <view class="bg">
          <image src="/static/images/vip-bg.png" />
        </view>
        <view class="text-box">
          <view class="tit">
            <view class="img">
              <image src="/static/images/vip.png" />
            </view>
            <view
              v-if="userDetails.levelType === 0 || isNotLogged"
              class="text"
            >
              开通会员尊享特权
            </view>
            <view
              v-else
              class="text"
            >
              您已开通会员
            </view>
          </view>
          <view
            v-if="userDetails.levelType === 0 || isNotLogged"
            class="des"
          >
            尊享{{ rightsNum }}项专属特权
          </view>
          <view
            v-else
            class="des"
          >
            会员还有{{ ExpiredDays }}天到期
          </view>
        </view>
        <view
          v-if="userDetails.levelType === 0 || isNotLogged"
          class="btn"
        >
          立即开通
        </view>
        <view
          v-else
          class="btn"
        >
          立即续费
        </view>
      </view>

      <!-- 我的订单 -->
      <view class="my-con my-orders">
        <view
          class="tit"
          @tap="onToMyOder(orderStatusConstant.ALL)"
        >
          <view class="text">
            我的订单
          </view>
          <view class="more text-arrow">
            全部
          </view>
        </view>
        <view class="con-box">
          <view
            class="item"
            @tap="onToMyOder(orderStatusConstant.UNPAY)"
          >
            <view class="img">
              <image src="/static/images/my-paid.png" />
              <view
                v-if="orderCountInfo.unPay"
                class="mark"
              >
                {{ orderCountInfo.unPay }}
              </view>
            </view>
            <view class="text">
              待付款
            </view>
          </view>
          <view
            class="item"
            @tap="onToMyOder(orderStatusConstant.PAYED)"
          >
            <view class="img">
              <image src="/static/images/my-delivered.png" />
              <view
                v-if="orderCountInfo.payed"
                class="mark"
              >
                {{ orderCountInfo.payed }}
              </view>
            </view>
            <view class="text">
              待发货
            </view>
          </view>
          <view
            class="item w70"
            @tap="onToMyOder(orderStatusConstant.CONSIGNMENT)"
          >
            <view class="img">
              <image src="/static/images/my-receiving.png" />
              <view
                v-if="orderCountInfo.consignment"
                class="mark"
              >
                {{ orderCountInfo.consignment }}
              </view>
            </view>
            <view class="text">
              待收货
            </view>
          </view>
          <view
            class="item"
            @tap="onToMyOder(-1)"
          >
            <view class="img">
              <image src="/static/images/my-refund.png" />
              <view
                v-if="orderCountInfo.refund"
                class="mark"
              >
                {{ orderCountInfo.refund }}
              </view>
            </view>
            <view class="text">
              退款/退货
            </view>
          </view>
        </view>
      </view>

      <!-- 分销中心&积分商城 -->
      <view class="distribution-points-wrap">
        <view
          class="distribution-item"
          @tap="onToDistCenter"
        >
          <view class="txt-left">
            <text>分销中心</text>
            <text>分享转化获佣金</text>
          </view>
          <image
            class="img-right"
            src="/static/images/distribution-center.png"
          />
        </view>
        <view
          class="points-item"
          @tap="onSubPackageRoute('my-integral')"
        >
          <view class="txt-left">
            <text>积分商城</text>
            <text>攒积分兑好礼</text>
          </view>
          <image
            class="img-right"
            src="/static/images/integral-mall.png"
          />
        </view>
      </view>
      <!-- end 分销中心 & 积分商店 -->

      <!-- 我的工具 -->
      <view class="my-con my-tools">
        <view class="tit">
          <view class="text">
            我的工具
          </view>
        </view>
        <view class="con-box">
          <view
            class="item"
            @tap="onSubPackageRoute('member')"
          >
            <view class="img">
              <image src="/static/images/my-member.png" />
            </view>
            <view class="text">
              会员中心
            </view>
          </view>
          <view
            class="item"
            @tap="onSubPackageRoute('coupon-center')"
          >
            <view class="img">
              <image src="/static/images/my-coupon.png" />
            </view>
            <view class="text">
              领券中心
            </view>
          </view>
          <view
            class="item"
            @tap="onSubPackageRoute('my-collection')"
          >
            <view class="img">
              <image src="/static/images/my-collection.png" />
            </view>
            <view class="text">
              我的收藏
            </view>
          </view>
          <view
            class="item"
            @tap="onRouteToUrl('address-list')"
          >
            <view class="img">
              <image src="/static/images/my-address.png" />
            </view>
            <view class="text">
              地址管理
            </view>
          </view>
          <view
            class="item"
            @tap="onSubPackageRoute('history')"
          >
            <view class="img">
              <image src="/static/images/my-history.png" />
            </view>
            <view class="text">
              我的足迹
            </view>
          </view>
          <view
            class="item"
            @tap="onRouteToUrl('my-chat')"
          >
            <view class="img">
              <image src="/static/images/touch-platform.png" />
            </view>
            <view class="text">
              平台客服
            </view>
          </view>
          <view
            class="item"
            @tap="onMerchantEntry"
          >
            <view class="img">
              <image src="/static/images/icon_tenants.png" />
            </view>
            <view class="text">
              商家入驻
            </view>
          </view>
          <view
            class="item"
            @tap="onRouteToUrl('user-settings')"
          >
            <view class="img">
              <image src="/static/images/my-set.png" />
            </view>
            <view class="text">
              系统设置
            </view>
          </view>
        </view>
      </view>

      <!-- 猜你喜欢 -->
      <view
        v-if="likeProdData && likeProdData.length > 0"
        class="guess-like"
      >
        <view class="tit">
          <view class="bg">
            <image src="/static/images/tit-bg.png" />
          </view>
          <view class="text">
            你可能还喜欢
          </view>
          <view class="bg">
            <image src="/static/images/tit-bg.png" />
          </view>
        </view>
        <view class="prods">
          <view
            v-for="(prodItem, prodIndex) in likeProdData"
            :key="prodIndex"
            class="item"
            @tap="onToProdDetail(prodItem.spuId)"
          >
            <view class="img">
              <image
                v-if="prodItem.mainImgUrl"
                mode="aspectFit"
                :src="util.addDomain(prodItem.mainImgUrl)"
                @error="onHandlePicError(prodIndex)"
              />
              <image
                v-else
                mode="aspectFit"
                src="/static/images/def.png"
              />
            </view>
            <view class="text-box">
              <view class="name">
                {{ prodItem.spuName }}
              </view>
              <view class="sku">
                {{ prodItem.sellingPoint || '' }}
              </view>
              <view class="price-box">
                <view class="price">
                  <view class="symbol">
                    ￥
                  </view>
                  <view class="big">
                    {{ wxs.parsePrice(prodItem.priceFee)[0] }}
                  </view>
                  <view class="symbol">
                    .{{ wxs.parsePrice(prodItem.priceFee)[1] }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </z-paging>
</template>

<script setup>
import util from '@/utils/util.js'
import { getCartCount } from '@/utils/cart-count'
import { OrderStatus } from '@/utils/constant'
import moment from 'moment'
import Wechat from '@/utils/wechat.js'

const wxs = number()
const orderStatusConstant = OrderStatus
const userDetails = ref({}) // 用户详细信息
const userInfo = ref({})
const orderCountInfo = ref({})
const isNotLogged = ref(true) // 未登录
const refreshFlag = ref('')
onShow(() => {
  // 排除 tempToken 影响，真实登陆后再请求数据
  if (uni.getStorageSync('cloudToken')) {
    refreshFlag.value = 1
    // 查询用户信息
    onQueryUserInfo()
    // 加载订单数据
    onLoadOrderCountFun()
    // 获取用户详细信息
    onGetUserDetails()
    // 用户未读系统消息数量
    onGetNumOfUnreadSystemMessage()
    // 查询分销是否开启
    onGetDistInfo()
  } else {
    refreshFlag.value = 0
    userDetails.value = {}
    userInfo.value = {}
    orderCountInfo.value = {}
  }
  getCartCount()
  isNotLogged.value = Boolean(!uni.getStorageSync('cloudToken'))
  onGetPaidMemberList()
})

/**
 * 用户点击右上角分享(勿删)
 */
onShareAppMessage(() => {})

watch(() => refreshFlag.value, () => {
  nextTick(() => {
    paging.value.reload()
  })
})

const ExpiredDays = computed(() => {
  return moment(userDetails.value.vipEndTime).diff(moment(), 'days')
})

const formatScore = computed(() => {
  let val = userInfo.value.score
  if (val) {
    val = val.toString()
    const lang = uni.getStorageSync('cloudLang').indexOf('zh') !== -1 ? 'zh' : 'en'
    if (val.length >= 5 && lang === 'zh') {
      if (val >= 10 ** 10) {
        return 99999 + 'w+'
      }
      return val.slice(0, -4) + 'w+'
    } else if (val.length >= 4 && lang === 'en') {
      if (val >= 10 ** 9) {
        return 99999 + 'k+'
      }
      return val.slice(0, -3) + 'k+'
    }
  }
  return val
})

const paySettlementType = uni.getStorageSync('cloudPaySettlementType') // 1:通联支付
const formatBalance = computed(() => {
  let val = paySettlementType === 1 ? userInfo.value.allinpayActualBalance : userInfo.value.actualBalance
  if (val) {
    val = val.toString()
    const lang = uni.getStorageSync('cloudLang').indexOf('zh') !== -1 ? 'zh' : 'en'
    if (val.length >= 7 && lang === 'zh') {
      if (val >= 10 ** 10) {
        return 99999 + 'w+'
      }
      return val.slice(0, -6) + 'w+'
    } else if (val.length >= 6 && lang === 'en') {
      if (val >= 10 ** 9) {
        return 99999 + 'k+'
      }
      return val.slice(0, -5) + 'k+'
    }
  }
  if (!val) {
    return 0
  }
  val = (val / 100).toFixed(2).split('.')
  return val[0] + '.' + val[1]
})

const isShowMember = ref(true)
const rightsNum = ref(0)
let minMemberPriceInfo = ''
/**
 * 获取付费会员列表
 */
const onGetPaidMemberList = () => {
  const params = {
    url: '/mall4cloud_user/user_level/ua/list_level_by_type',
    method: 'GET',
    data: {
      levelType: 1
    }
  }
  http.request(params).then((data) => {
    if (!data.length) {
      isShowMember.value = false
      return
    }
    rightsNum.value = data[0].userRightsList.length
    data[0].userLevelTerms.forEach((termItem) => {
      if (termItem.termType === 0) {
        minMemberPriceInfo = termItem
      }
    })
    minMemberPriceInfo.needAmount = (minMemberPriceInfo.needAmount / 100).toFixed(2)
  })
}

/**
 * 获取用户详细信息
 */
const onGetUserDetails = () => {
  if (!uni.getStorageSync('cloudToken')) {
    return
  }
  const params = {
    url: '/mall4cloud_user/user/ma/user_detail_info',
    method: 'GET',
    data: {}
  }
  http.request(params).then((res) => {
    if (res.pic) {
      res.pic = util.checkFileUrl(res.pic)
    }
    userDetails.value = res
    uni.setStorageSync('cloudUserDetails', res)
  })
}

// 获取猜你喜欢商品列表
const paging = ref(null)
const onGetLikeProdList = (pageNum, pageSize) => {
  const categoryId = uni.getStorageSync('cloudBrowseCategoryId')
  const userDetailsStorage = uni.getStorageSync('cloudUserDetails')
  let paramUrl = '/mall4cloud_search/ua/search/page'
  const paramData = {
    pageNum,
    pageSize
  }
  // prodRecommendation 0:关(新品推荐)  1:开(个性化推荐)
  if (userDetailsStorage && userDetailsStorage.prodRecommendation === 1) {
    paramUrl = '/mall4cloud_product/ma/spu/recommend_list'
    paramData.categoryId = categoryId
  } else {
    paramData.sort = 1
  }

  const params = {
    url: paramUrl,
    method: 'GET',
    data: paramData
  }
  http.request(params).then((res) => {
    // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
    paging.value.complete(res.list[0].spus)
  })
}

/**
 * 计算各个订单数量
 */
const onLoadOrderCountFun = () => {
  const params = {
    url: '/mall4cloud_order/my_order/order_count',
    method: 'GET',
    data: {}
  }
  http.request(params).then((res) => {
    orderCountInfo.value = res
  })
}

/**
 * 获取用户信息栏数据
 */
const onQueryUserInfo = () => {
  const params = {
    url: '/mall4cloud_user/user/user_info',
    method: 'GET',
    data: {}
  }
  http.request(params).then((res) => {
    userInfo.value = res
  })
}

const unreadSystemMessagesNum = ref(0) // 系统消息未读数量
// 查询用户未读系统消息数量
const onGetNumOfUnreadSystemMessage = () => {
  const params = {
    url: '/mall4cloud_biz/notify_log/unread_count',
    method: 'GET',
    data: {}
  }
  http.request(params).then((res) => {
    unreadSystemMessagesNum.value = res || 0
  })
}

// 去登陆
const onToLogin = () => {
  util.checkAuthInfo(() => {
    uni.navigateTo({
      url: '/package-user/pages/user-login/user-login'
    })
  })
}

// 去我的订单
const onToMyOder = (sts) => {
  util.checkAuthInfo(() => {
    uni.navigateTo({
      url: sts !== -1 ? '/package-user/pages/order/order?orderStatus=' + sts : '/package-refund/pages/refund-list/refund-list'
    })
  })
}

// 跳转到商品详情页
const onToProdDetail = (spuId) => {
  uni.navigateTo({
    url: `/pages/detail/detail?spuId=${spuId}`
  })
}

/**
 * 统一跳转方法
 * @param {*} url 跳转的地址路径
 */
const onRouteToUrl = (url) => {
  if (url === 'member-center') {
    uni.navigateTo({
      url: `/package-activities/pages/${url}/${url}`
    })
    return
  }
  if (url === 'address-list' || url === 'user-settings') {
    util.checkAuthInfo(() => {
      uni.navigateTo({
        url: `/package-user/pages/${url}/${url}`
      })
    })
    return
  }
  if (url === 'my-chat') {
    util.checkAuthInfo(() => {
      uni.navigateTo({
        url: '/package-user/pages/my-chat/my-chat?shopid=0'
      })
    })
    return
  }
  util.checkAuthInfo(() => {
    uni.navigateTo({
      url: `/pages/${url}/${url}`
    })
  })
}

let distShow = true // 控制分销中心显示和隐藏的
/**
 * 查询分销相关信息
 */
const onGetDistInfo = () => {
  // 查询分销开关是否开启
  const params = {
    url: '/mall4cloud_marketing/distribution_set/info',
    method: 'GET',
    dontShowLogin: true
  }
  http.request(params).then((res) => {
    if (res.distributionSwitch === 1) {
      distShow = true
    } else {
      distShow = null
    }
  })
}

/**
 * 跳转分销员中心
 */
const onToDistCenter = () => {
  // 判断分销中心功能是否开启
  if (!distShow) {
    return uni.showToast({
      title: $t('distribution.distributionErrorTxt'),
      icon: 'none'
    })
  }
  util.checkAuthInfo(() => {
    http.request({
      url: '/mall4cloud_marketing/distribution_user/distribution_user_info',
      method: 'GET',
      selfLoading: true
    }).then((res) => {
      if (res && res.state === 1) {
        uni.setStorageSync('cloudDistributionUserId', res.distributionUserId)
        uni.setStorageSync('cloudDistInfo', res)
        uni.navigateTo({
          url: '/package-activities/pages/distribution-center/distribution-center'
        })
      } else if (res && res.state === 0) {
        uni.showToast({
          title: $t('distribution.applicationReview'),
          icon: 'none'
        })
      } else if (res && res.state === 3) {
        uni.showModal({
          title: '',
          content: $t('distribution.applicationFailed'),
          cancelText: $t('cancel'),
          confirmText: $t('confirm'),
          confirmColor: '#eb2444',

          success (res2) {
            if (res2.confirm) {
              if (res.recruitState) {
                uni.navigateTo({
                  url: '/package-activities/pages/apply-distribution/apply-distribution'
                })
              } else {
                uni.navigateTo({
                  url: '/package-activities/pages/apply-distCon/apply-distCon'
                })
              }
            }
          }

        })
      } else if (res && res.state === -1) {
        uni.showModal({
          title: '',
          content: $t('distribution.distributorBanned'),
          confirmColor: '#eb2444',
          cancelText: $t('cancel'),
          confirmText: $t('confirm'),
          showCancel: false
        })
      } else if (res && res.state === 2) {
        uni.showModal({
          title: '',
          content: $t('distribution.distributorCleared'),
          confirmColor: '#eb2444',
          cancelText: $t('cancel'),
          confirmText: $t('confirm'),
          showCancel: false
        })
      } else {
        if (res.recruitState) {
          uni.navigateTo({
            url: '/package-activities/pages/apply-distribution/apply-distribution'
          })
        } else {
          uni.navigateTo({
            url: '/package-activities/pages/apply-distCon/apply-distCon'
          })
        }
      }
    })
  })
}

/**
 * 分包路径的跳转
 */
const onSubPackageRoute = (url) => {
  if (url === 'coupon-center') {
    uni.navigateTo({
      url: `/package-activities/pages/${url}/${url}`
    })
    return
  }
  // 会员页面跳转调整: 跳转到用户对应类型的会员页面(付费-付费, 普通-普通)
  if (url === 'member') {
    url = userDetails.value.levelType === 0 ? 'member-center-general' : 'member-center'
  }
  util.checkAuthInfo(() => {
    uni.navigateTo({
      url: `/package-activities/pages/${url}/${url}`
    })
  })
}

const isUserPic = ref(true)
const imgError = () => {
  isUserPic.value = false
}

/**
 * 商家入驻弹框
 */
const onMerchantEntry = () => {
  uni.showModal({
    content: `商家入驻请前往PC商家端注册\n${import.meta.env.VITE_APP_MERCHANT_PLATFORM_URL}`,
    showCancel: false,
    confirmColor: '#F81A1A',
    confirmText: '复制网址',
    success: () => {
      // 复制网址
      uni.setClipboardData({
        data: import.meta.env.VITE_APP_MERCHANT_PLATFORM_URL,
        success: () => {}
      })
    }
  })
}

// 猜你喜欢相关数据
const likeProdData = ref([])
const onHandlePicError = (index) => {
  likeProdData.value[index].mainImgUrl = ''
}

// 扫一扫
const onSacnCode = util.debounce(() => {
  util.checkAuthInfo(() => {
    // #ifdef H5
    if (!Wechat.isWechat()) {
      uni.showToast({
        title: '请在微信浏览器打开',
        icon: 'none'
      })
      return
    }
    Wechat.scanQRCode((codeStr) => {
      let code = ''
      let flag = 0 // flag为0时，表示结果为自提点二维码，flag为1时，表示结果为商家二维码
      // 处理扫码结果
      if (codeStr.indexOf(',') > -1) {
        code = codeStr.split(',')[1]
      } else if (codeStr.indexOf('?shopId=') > -1) {
        code = codeStr.split('?shopId=')[1]
        flag = 1
      } else {
        code = codeStr
      }
      if (!/^\d+$/.test(code)) {
        uni.showModal({
          title: '提示',
          content: '请扫描正确的自提点二维码',
          confirmText: '确定',
          showCancel: false
        })
      } else {
        uni.navigateTo({
          url:
            '/package-user/pages/station-order-list/station-order-list?' +
            (flag ? 'shopId=' : 'stationId=') +
            code
        })
      }
    }, () => {
      uni.showToast({
        title: '唤起扫码失败，请稍后重试',
        icon: 'none'
      })
    })
    // #endif

    // #ifdef APP-PLUS || MP-WEIXIN
    uni.scanCode({
      success: (e) => {
        let code = ''
        let flag = 0 // flag为0时，表示结果为自提点二维码，flag为1时，表示结果为商家二维码
        // 处理扫码结果
        if (e.result.indexOf(',') > -1) {
          code = e.result.split(',')[1]
        } else if (e.result.indexOf('?shopId=') > -1) {
          code = e.result.split('?shopId=')[1]
          flag = 1
        } else {
          code = e.result
        }
        if (!/^\d+$/.test(code)) {
          uni.showModal({
            title: '提示',
            content: '请扫描正确的自提点二维码',
            confirmText: '确定',
            showCancel: false
          })
        } else {
          uni.navigateTo({
            url:
              '/package-user/pages/station-order-list/station-order-list?' +
              (flag ? 'shopId=' : 'stationId=') +
              code
          })
        }
      }
    })
    // #endif
  })
}, 1000)
</script>

<style lang="scss" scoped>
@use "./my.scss";
</style>
