<template>
  <view class="Mall4j page-user-settings">
    <view
      v-if="isLogined"
      class="first-box"
    >
      <view class="item">
        <view class="text">
          头像
        </view>
        <view class="img">
          <image src="@/static/images/head-sculpture.png" />
          <!-- 上传组件 -->
          <view :class="['up', userDetails.pic ? 'visible' : '']">
            <img-box
              :img-url="userDetails.pic"
              :need-delete-btn="false"
              :type="'user'"
              @get-image-path="onGetImgPath"
            />
          </view>
        </view>
        <view class="text-arrow" />
      </view>
      <view
        class="item"
        @tap.stop="toAddressList"
      >
        <view class="text">
          地址管理
        </view>
        <view class="text-arrow" />
      </view>
    </view>

    <view
      v-if="isLogined && isLoaded && paySettlementType===1"
      class="other-entrance"
    >
      <view
        class="item"
        @tap.stop="onToEditPage('verification')"
      >
        <view class="text">
          实名认证
        </view>
        <view
          v-if="!allinpayMemberInfo.isIdentityChecked"
          class="text-arrow"
        />
        <view
          v-else
          class="text-user-name"
        >
          已实名
        </view>
      </view>
      <!-- 实名认证和绑定手机号合并，但实名认证成功后绑定手机号失败时，用户可从该位置进入绑定 -->
      <view
        v-if="allinpayMemberInfo.isIdentityChecked"
        class="item"
        @tap.stop="onToEditPage('bindMobile')"
      >
        <view
          v-if="!allinpayMemberInfo.isPhoneChecked"
          class="text"
        >
          绑定手机
          <text class="tip">
            （保障账户余额安全）
          </text>
        </view>
        <view
          v-else
          class="text"
        >
          修改保障余额手机
        </view>
        <view
          v-if="!allinpayMemberInfo.isPhoneChecked"
          class="text-arrow"
        >
          去绑定
        </view>
        <view
          v-else
          class="text-arrow"
        />
      </view>
      <view
        class="item"
        @tap.stop="onToEditPage('myBankCard')"
      >
        <view class="text">
          我的银行卡
        </view>
        <view class="text-arrow" />
      </view>
      <view
        class="item"
        @tap.stop="onToSignContract"
      >
        <view class="text">
          提现协议
        </view>
        <view
          v-if="!allinpayMemberInfo.acctProtocolNo"
          class="text-arrow"
        >
          去签约
        </view>
        <view
          v-else
          class="text-user-name"
        >
          已签约
        </view>
      </view>
      <view
        class="item"
        @tap.stop="onToSetAllinpayPwd"
      >
        <view class="text">
          支付密码
        </view>
        <view class="text-arrow" />
      </view>
    </view>
    <view
      v-if="isLogined"
      class="other-entrance"
    >
      <view
        v-if="userDetails.userName"
        class="item"
        @tap.stop="onToEditPage('')"
      >
        <view class="text">
          用户名
        </view>
        <view class="text-user-name">
          {{ userDetails.userName }}
        </view>
      </view>
      <view
        class="item"
        @tap.stop="onToEditPage('nickName')"
      >
        <view class="text">
          昵称
        </view>
        <view class="text-arrow">
          {{ userDetails.nickName }}
        </view>
      </view>
      <view class="item">
        <view
          class="text"
          @tap.stop="onChangeGenders"
        >
          性别
        </view>
        <view
          class="text-arrow"
          @tap.stop="onChangeGenders"
        >
          {{ userDetails.sex === '0' ? '男' : userDetails.sex === '1' ? '女' : '' }}
        </view>
      </view>
      <view class="item">
        <view
          class="text"
          @tap.stop="onChangeBirthDate"
        >
          生日
        </view>
        <view
          class="text-arrow"
          @tap.stop="onChangeBirthDate"
        >
          {{ userDetails.birthDate || '' }}
        </view>
      </view>
      <view
        class="item"
        @tap.stop="onToEditPage('phone')"
      >
        <view class="text">
          修改手机
        </view>
        <view class="text-arrow">
          {{ privacyPhone }}
        </view>
      </view>
      <view
        class="item"
        @tap.stop="onToEditPage('password')"
      >
        <view class="text">
          修改密码
        </view>
        <view class="text-arrow" />
      </view>
      <view
        class="item"
        @tap.stop="goPersonalRecommend"
      >
        <view class="text">
          个性化推荐
        </view>
        <view class="text-arrow">
          {{ userDetails.prodRecommendation?'开':'关' }}
        </view>
      </view>
      <view
        class="item"
        @tap.stop="onCancellation"
      >
        <view class="text">
          注销账号
        </view>
        <view class="text-arrow" />
      </view>
      <view
        class="item"
        @tap.stop="onToTermsOfService('serviceTerms')"
      >
        <view class="text">
          服务条款
        </view>
        <view class="text-arrow" />
      </view>
      <view
        class="item"
        @tap.stop="onToTermsOfService('servicePolicy')"
      >
        <view class="text">
          隐私策略
        </view>
        <view class="text-arrow" />
      </view>
    </view>
    <view
      class="login-out"
      @tap.stop="onLoginOut"
    >
      退出登录
    </view>

    <!-- 性别/生日选择器 -->
    <user-details-picker
      v-show="showPicker"
      ref="pickerRef"
      :show-picker="showPicker"
      :genders="parseInt(userDetails.sex)"
      :birth-date="userDetails.birthDate"
      :gender-array="genderArray"
      @set-user-info="onUserInfoPickerConfirm"
    />

    <!-- 确定弹窗 -->
    <confirm-pop
      :show-pop="showPop"
      :pop-content="popContent"
      @handle-pop-cancel="onPopCancel"
      @handle-pop-confirm="onPopConfirm"
    />
  </view>
</template>

<script setup>

const domainAddress = import.meta.env.VITE_APP_DOMAIN_ADDRESS
const { debounce, toAllinPay } = util
const userDetails = reactive({
  pic: '',
  nickName: '',
  sex: '',
  birthDate: ''
}) // 用户详细信息
const showPicker = ref(false)
const genderArray = reactive(['男', '女'])
const privacyPhone = ref('') // 隐藏手机号部分数字

// 公众号和小程序不显示退出登录
const isLogined = ref(false)

const allinpayMemberInfo = reactive({}) // 通联会员信息
const isLoaded = ref(false) // 是否加载完毕(控制通联模块是否显示)
let isMemberInfoLoaded = false // 是否加载完毕(控制是否可以点击)
const paySettlementType = uni.getStorageSync('cloudPaySettlementType') // 1通联支付
// 弹窗组件参数
const showPop = ref(false)
const popContent = reactive({})
let confirmType = -1 // 弹窗提示类型 0：未实名认证 1：未绑定手机号 2：未绑定银行卡 4:未设置支付密码
onLoad((options) => {
  isLogined.value = Boolean(uni.getStorageSync('cloudToken'))
  // #ifdef H5
  if (paySettlementType !== 1) {
    return
  }
  // 获取内存中的签约编号
  const acctProtocolNo = uni.getStorageSync('cloudAllinpayAcctProtocolNo')
  // 以下代码为H5页面签约成功执行, 小程序在App.vue的onShow中,APP则在单独的页面redirect.vue中
  // 如果本次签约和存储中的签约编号不一致，则需要提示签约成功并更新签约编号，否则不提示，避免重复提示签约成功
  if (Number(options.isSignSuccess) === 1 && options.bizContent && acctProtocolNo !== options.bizContent.acctProtocolNo) {
    uni.showToast({
      title: '签约成功',
      icon: 'none',
      duration: 1000
    })
    // 上方已经重新获取通联会员信息，所以不用再次请求
    uni.setStorageSync('cloudAllinpayAcctProtocolNo', options.bizContent.acctProtocolNo)
  } else if (Number(options.isSignSuccess) === 0) {
    uni.showToast({
      title: '签约失败',
      icon: 'none',
      duration: 1000
    })
  }
  // #endif
})
onShow(() => {
  onGetUserDetails() // 获取用户详细信息
  if (isLogined.value && paySettlementType === 1) {
    // 登录且是通联支付下，获取通联会员信息
    onGetMemberInfo()
  }
})
onHide(() => {
  showPicker.value = false
})

/**
 * 去条款页
 */
const onToTermsOfService = (key) => {
  uni.navigateTo({
    url: '/pages/terms-page/terms-page?sts=' + key
  })
}

/**
 * 获取用户详细信息
 */
const onGetUserDetails = (sts, tips) => {
  if (!uni.getStorageSync('cloudToken')) {
    return
  }
  const params = {
    url: '/mall4cloud_user/user/ma/user_detail_info',
    method: 'GET',
    data: {}
  }
  http.request(params).then(res => {
    // userDetails = res
    res && Object.assign(userDetails, res)
    uni.setStorageSync('cloudUserDetails', res)
    if (res.userMobile) {
      const pre = res.userMobile.substr(0, 3)
      const next = res.userMobile.substr(7, 4)
      privacyPhone.value = pre + '****' + next
    }
    if (sts && sts === 'update') {
      uni.showToast({
        title: tips,
        icon: 'none',
        duration: 1000
      })
    }
  })
}

// 获取用户扩展信息（通联支付）
const onGetMemberInfo = () => {
  uni.showLoading()
  isMemberInfoLoaded = false
  const params = {
    url: '/mall4cloud_payment/allinpay/member/get_user_info',
    method: 'GET'
  }
  http.request(params).then(res => {
    uni.hideLoading()
    // allinpayMemberInfo = res
    res && Object.assign(allinpayMemberInfo, res)
    isMemberInfoLoaded = true
    isLoaded.value = true
  }).catch((res) => {
    uni.hideLoading()
    uni.showToast({
      title: res.msg,
      icon: 'none',
      duration: 1000
    })
    isLoaded.value = true
    isMemberInfoLoaded = true
  })
}

// 去管理地址
const toAddressList = () => {
  uni.navigateTo({
    url: '/package-user/pages/address-list/address-list'
  })
}

// 去修改信息（性别生日用插件在本页选就好）
const onToEditPage = (type) => {
  if (type === '') return
  if (paySettlementType === 1 && !isMemberInfoLoaded) {
    // 通联支付下，如果会员信息未加载完毕，不允许点击
    return
  }
  // 点击去实名时，如果已经实名过了，就不跳转了
  if (type === 'verification' && allinpayMemberInfo && allinpayMemberInfo.isIdentityChecked) return
  if (type === 'nickName') {
    uni.navigateTo({
      url: '/package-user/pages/edit-page/edit-page?type=' + type + '&nickName=' + userDetails.nickName
    })
    return
  }
  if (type === 'phone') {
    uni.navigateTo({
      url: '/package-user/pages/edit-page/edit-page?type=' + type + '&userMobile=' + userDetails.userMobile
    })
    return
  }
  if (type === 'password') {
    uni.navigateTo({
      url: '/package-user/pages/user-login/user-login?isForgetPassword=true&isPersonalCenter=true'
    })
    return
  }
  if (type === 'verification') {
    // 实名认证
    uni.navigateTo({
      url: '/package-user/pages/realname-verification/realname-verification'
    })
    return
  }
  if (type === 'myBankCard') {
    if (!(allinpayMemberInfo && allinpayMemberInfo.isIdentityChecked)) {
      // 未实名认证
      showPop.value = true
      popContent.content = '请先进行实名认证'
      confirmType = 0
      return
    }
    // 我的银行卡
    uni.navigateTo({
      url: '/package-user/pages/bank-card-list/bank-card-list'
    })
    return
  }
  if (type === 'bindMobile') {
    if (allinpayMemberInfo.isPhoneChecked) {
      onUpdateMobile()
      return
    }
    uni.navigateTo({
      url: '/package-user/pages/bind-mobile/bind-mobile'
    })
    return
  }
  uni.navigateTo({
    url: '/package-user/pages/edit-page/edit-page?type=' + type
  })
}
const goPersonalRecommend = () => {
  uni.navigateTo({
    url: '/package-user/pages/personal-recommend/personal-recommend'
  })
}

/**
   * 跳转注销账号
   */
const onCancellation = () => {
  uni.redirectTo({
    url: '/package-user/pages/cancellation/cancellation'
  })
}

/**
 * 更新用户头像
 * @param {String} url 图片组件返回路径
 */
const onGetImgPath = (url) => {
  if (url) {
    const userData = {
      pic: url
    }
    onUpdateUserInfo('avatar', userData)
  }
}

/**
 * 修改用户性别弹窗显隐
 */
const pickerRef = ref(null)
const onChangeGenders = () => {
  showPicker.value = true
  nextTick(() => {
    pickerRef.value?.init('sex')
  })
}
/**
 * 修改用户生日弹窗显隐
 */
const onChangeBirthDate = () => {
  showPicker.value = true
  nextTick(() => {
    pickerRef.value?.init('birthDate')
  })
}

/**
 * picker选择返回
 */
const onUserInfoPickerConfirm = (type, val, isChange) => {
  showPicker.value = false
  if (type === 'sex' && isChange && val[0] !== parseInt(userDetails.sex)) {
    const userData = {
      sex: val[0]
    }
    // 如果在picker中进行了选择 且 选中的值不等于当前的值，
    onUpdateUserInfo('sex', userData)
    return
  }
  if (type === 'birthDate' && isChange) {
    const userData = {
      birthDate: val
    }
    onUpdateUserInfo('birthDate', userData)
  }
}

/**
 * 修改用户信息
 */
const onUpdateUserInfo = (type, userData) => {
  const tips = type === 'avatar' ? '头像更新成功' : type === 'sex' ? '性别更新成功' : type === 'birthDate' ? '生日更新成功' : ''
  if (type !== 'birthDate') {
    userData.birthDate = userDetails.birthDate
  }
  const params = {
    url: '/mall4cloud_user/user/set_user_info',
    method: 'PUT',
    data: userData
  }
  http.request(params).then(() => {
    onGetUserDetails('update', tips) // 重新获取用户信息
  }).catch(res => {
    uni.showModal({
      title: '提示',
      content: res.msg,
      showCancel: false,
      success (res) {
        if (res.confirm) {
          onGetUserDetails() // 重新获取用户信息
        }
      }
    })
  })
}

/**
 * 退出登录
 */
const onLoginOut = () => {
  uni.redirectTo({
    url: '/package-user/pages/logout/logout'
  })
}

// 去签约
const onToSignContract = debounce(async function () {
  if (allinpayMemberInfo.acctProtocolNo || !isMemberInfoLoaded) {
    // 已签约或者未获取到会员信息
    return
  }
  if (!(allinpayMemberInfo && allinpayMemberInfo.isIdentityChecked)) {
    // 未实名认证
    showPop.isMemberInfoLoaded = true
    popContent.content = '请先进行实名认证'
    confirmType.isMemberInfoLoaded = 0
    return
  }
  const bankCardNumber = await onGetBankCardNumber()
  if (!bankCardNumber) {
    showPop.val = true
    popContent.content = '请绑定最少一张银行卡'
    confirmType = 2
    return
  }
  const data = {
    signAcctType: 1,
    jumpUrl: domainAddress + '/package-user/pages/user-settings/user-settings?isSignSuccess=1',
    noContractUrl: domainAddress + '/package-user/pages/user-settings/user-settings?isSignSuccess=0',
    jumpPageType: 1
  }
  // #ifdef APP-PLUS
  data.jumpUrl = domainAddress + '/package-user/pages/redirect/redirect?isSignSuccess=1'
  data.noContractUrl = domainAddress + '/package-user/pages/redirect/redirect?isSignSuccess=0'
  // #endif
  // #ifdef MP-WEIXIN
  data.jumpPageType = 2
  // #endif
  uni.showLoading()
  const params = {
    url: '/mall4cloud_payment/allinpay/member/sign_acct_protocol',
    method: 'POST',
    dontTrunLogin: true,
    data
  }
  http.request(params).then((res) => {
    uni.hideLoading()
    // #ifdef H5
    window.location.href = res
    // #endif
    // #ifdef MP-WEIXIN
    toAllinPay({
      targetUrl: res
    })
    // #endif
    // #ifdef APP-PLUS
    // eslint-disable-next-line no-undef
    plus.runtime.openURL(res)
    // #endif
  }).catch(() => {
    uni.hideLoading()
  })
})

// 获取用户已绑定的银行卡数量
const onGetBankCardNumber = () => {
  return new Promise((resolve, reject) => {
    const params = {
      url: '/mall4cloud_payment/allinpay/member/query_bank_card',
      method: 'GET',
      selfLoading: true
    }
    http.request(params).then(res => {
      if (res) {
        resolve(res && res.length)
      } else {
        resolve(0)
      }
    }).catch((err) => {
      reject(err)
    })
  })
}

// 换绑手机号
const onUpdateMobile = () => {
  if (!allinpayMemberInfo.isSetPayPwd) {
    showPop.value = true
    popContent.content = '请先设置支付密码，以保障您的账户余额安全'
    confirmType = 4
    return
  }
  if (!(allinpayMemberInfo && allinpayMemberInfo.isIdentityChecked)) {
    // 未实名认证
    showPop.value = true
    popContent.content = '请先进行实名认证'
    confirmType = 0
    return
  }
  const data = {
    jumpUrl: domainAddress + '/package-user/pages/user-settings/user-settings',
    errorJumpUrl: domainAddress + '/package-user/pages/user-settings/user-settings',
    jumpPageType: 1
  }
  // #ifdef APP-PLUS
  // 如果是app打开，则需要在url后面拼接isUpdateMobile=1，用于判断是否是换绑手机号成功后返回的页面
  data.jumpUrl = domainAddress + '/package-user/pages/redirect/redirect?isUpdateMobile=1'
  data.errorJumpUrl = domainAddress + '/package-user/pages/redirect/redirect?isUpdateMobile=1'
  // #endif
  // #ifdef MP-WEIXIN
  data.jumpPageType = 2
  // #endif
  uni.showLoading()
  const params = {
    url: '/mall4cloud_payment/allinpay/member/update_phone_by_pay_pwd',
    method: 'PUT',
    dontTrunLogin: true,
    data
  }
  http.request(params).then((res) => {
    uni.hideLoading()
    // #ifdef H5
    window.location.href = res
    // #endif
    // #ifdef MP-WEIXIN
    toAllinPay({
      targetUrl: res
    })
    // #endif
    // #ifdef APP-PLUS
    // eslint-disable-next-line no-undef
    plus.runtime.openURL(res)
    // #endif
  }).catch(() => {
    uni.hideLoading()
  })
}
// 设置或修改支付密码
const onToSetAllinpayPwd = () => {
  if (!isMemberInfoLoaded) {
    // 会员信息未加载完成禁止点击
    return
  }
  if (!(allinpayMemberInfo && allinpayMemberInfo.isIdentityChecked)) {
    // 未实名认证
    showPop.value = true
    popContent.content = '请先进行实名认证'
    confirmType = 0
    return
  }
  if (!allinpayMemberInfo.isPhoneChecked) {
    // 未绑定手机号
    showPop.value = true
    popContent.content = '请先绑定用于保障账户余额安全的手机号'
    confirmType = 1
    return
  }
  if (allinpayMemberInfo.isSetPayPwd) {
    // 已设置支付密码,则进入支付密码管理页面
    uni.navigateTo({
      url: '/package-user/pages/allinpay-pwd/allinpay-pwd'
    })
    return
  }
  const data = {
    jumpUrl: domainAddress + '/package-user/pages/user-settings/user-settings',
    errorJumpUrl: domainAddress + '/package-user/pages/user-settings/user-settings',
    jumpPageType: 1
  }
  // #ifdef APP-PLUS
  // 如果是app打开，则需要在url后面拼接isSetPayPwd=1，用于判断是否是设置或修改支付密码成功后返回的页面
  data.jumpUrl = domainAddress + '/package-user/pages/redirect/redirect?isSetPayPwd=1'
  data.errorJumpUrl = domainAddress + '/package-user/redirect/redirect?isSetPayPwd=1'
  // #endif
  // #ifdef MP-WEIXIN
  data.jumpPageType = 2
  // #endif
  const method = 'POST'
  const url = '/mall4cloud_payment/allinpay/member/set_pay_pwd'
  uni.showLoading()
  const params = {
    url,
    method,
    dontTrunLogin: true,
    data
  }
  http.request(params).then((res) => {
    uni.hideLoading()
    onPopCancel()
    // #ifdef H5
    window.location.href = res
    // #endif
    // #ifdef MP-WEIXIN
    toAllinPay({
      targetUrl: res
    })
    // #endif
    // #ifdef APP-PLUS
    // eslint-disable-next-line no-undef
    plus.runtime.openURL(res)
    // #endif
  }).catch((err) => {
    uni.hideLoading()
    uni.showToast({
      title: err.msg,
      icon: 'none'
    })
  })
}

// 弹窗确认事件
const onPopConfirm = () => {
  showPop.value = false
  if (confirmType === 0) { // 未实名认证
    uni.navigateTo({
      url: '/package-user/pages/realname-verification/realname-verification'
    })
  } else if (confirmType === 1) { // 未绑定手机号
    uni.navigateTo({
      url: '/package-user/pages/bind-mobile/bind-mobile'
    })
  } else if (confirmType === 2) { // 未绑定银行卡
    uni.navigateTo({
      url: '/package-user/pages/bind-bank-card/bind-bank-card'
    })
  } else if (confirmType === 4) {
    onToSetAllinpayPwd()
    return
  }
  // 清空弹窗
  onPopCancel()
}

// 弹窗取消事件
const onPopCancel = () => {
  showPop.value = false
  delete popContent.content
  confirmType = -1
}

</script>

<style lang="scss"  scoped>
@use "./user-settings.scss";
</style>
