<template>
  <ManagerPopup v-model="managerPopupVisible" />
  <div class="my">
    <div class="top">
      <img class="avatar" v-if="data.userimg" :src="$file(data.userimg)">
      <div class="_info">
        <div class="name">
          {{ $substring(data.nickname, 0, 12) }}
        </div>
        <div class="user">
          <img src="/img/my-i1.png" />{{ data.cellphone }}
        </div>
        <div class="box">
          <div class="vBicon vip">
            {{ data.userlevelname }}
          </div>
          <div class="vBicon svip" v-if="data.col3">
            {{ data.col3name }}
          </div>
          <div class="vBicon director" v-if="data.col1">
            {{ data.col1name }}
          </div>
        </div>
      </div>
      <!-- v-if="data.isstudio" -->
      <div class="shopcenter" v-if="data.col2 || data.isshop" @click="$showManagerPopup()">
        <span>
          管理中心
          <van-icon name="arrow" />
        </span>
      </div>
    </div>

    <div class="wallet_box">
      <div @click="$navigate('Balance')">
        <div class="t">
          <img src="/img/my_w1.png" alt="">
          <span>余额</span>
        </div>
        <b>{{ data.zijin?.toFixed(2) }}</b>
      </div>

      <div @click="$navigate('CV')">
        <div class="t">
          <img src="/img/my_w2.png" alt="">
          <span>会员卡</span>
        </div>
        <b>{{ data.xiaofeiquan?.toFixed(2) }}</b>
      </div>

      <div @click="$navigate('Point')">
        <div class="t">
          <img src="/img/my_w3.png" alt="">
          <span>积分</span>
        </div>
        <b>{{ data.xiaofeijifen?.toFixed(2) }}</b>
      </div>
    </div>

    <div class="my_order">
      <div class="t">
        <b>我的订单</b>

        <span class="r" @click="$navigate('TradeList')">
          更多
          <van-icon name="arrow"></van-icon>
        </span>
      </div>
      <div class="c">
        <van-badge :dot="data.ordercountdaifukuan > 0" :offset="[3, -3]">
          <div class="st_box" @click="$navigate(`/TradeList?state=0`)">
            <img src="/img/my_o1.png">
            <p>待付款</p>
          </div>
        </van-badge>
        <van-badge :dot="data.ordercountdaifahuo > 0" :offset="[3, -3]">
          <div class="st_box" @click="$navigate(`/TradeList?state=1`)">
            <img src="/img/my_o2.png">
            <p>待发货</p>
          </div>
        </van-badge>
        <van-badge :dot="data.ordercountdaishouhuo > 0" :offset="[3, -3]">
          <div class="st_box" @click="$navigate(`/TradeList?state=3`)">
            <img src="/img/my_o3.png">
            <p>待收货</p>
          </div>
        </van-badge>
        <div class="st_box" @click="$navigate(`/TradeList?state=4`)">
          <img src="/img/my_o4.png">
          <p>已完成</p>
        </div>
      </div>
    </div>

    <div class="fast_to">
      <div>
        <img src="/img/my_f1.jpg" @click="toInvite()" alt="">
        <img src="/img/my_f2.jpg" @click="$navigate('Team')" alt="">
      </div>
      <div>
        <img src="/img/my_f3.jpg" @click="$navigate('Allow')" alt="">
        <img src="/img/my_f4.jpg" @click="$navigate('Certificate')" alt="">
      </div>
    </div>

    <div class="service_center">
      <div class="tit">
        <b>服务中心</b>
      </div>
      <div class="list">
        <div @click="$navigate('CashoutAccount')">
          <img src="/img/my_s1.png" alt="">
          <span>提现账号</span>
          <van-icon name="arrow" class="r"></van-icon>
        </div>

        <div @click="$navigate('Address')">
          <img src="/img/my_s2.png" alt="">
          <span>收货地址</span>
          <van-icon name="arrow" class="r"></van-icon>
        </div>

        <div @click="$navigate('Service')">
          <img src="/img/my_s3.png" alt="">
          <span>联系客服</span>
          <van-icon name="arrow" class="r"></van-icon>
        </div>

        <div @click="settingVisibled = true">
          <img src="/img/my_s4.png" alt="">
          <span>设置中心</span>
          <van-icon name="arrow" class="r"></van-icon>
        </div>
      </div>
    </div>

    <van-action-sheet v-model:show="settingVisibled" title="设置中心" class="setting">
      <div style="height: 1rem" />
      <van-cell is-link icon="/img/set-i1.png" title="个人资料" size="large"
        @click="tempData = {}; Object.assign(tempData, data); tempData.AvatarUploader = [{ url: $file(tempData.userimg), isImage: true }]; showInfo = true;">
        <template #right-icon>
          <img class="y50" :src="$file(data.userimg)" width="29" height="29" />
        </template>
      </van-cell>
      <van-cell is-link icon="/img/set-i2.png" title="登录密码" size="large" value="修改"
        @click="changePasswordVisibled = true">
      </van-cell>
      <van-cell is-link icon="/img/set-i3.png" title="提现账户" size="large" value="管理"
        @click="$navigate('/CashoutAccount')">
      </van-cell>
      <van-cell is-link icon="/img/set-i4.png" title="退出登录" size="large" @click="logout">
        <template #right-icon> </template>
      </van-cell>
      <div style="height: 2rem" />
    </van-action-sheet>

    <van-action-sheet v-model:show="showInfo" title="个人信息">
      <van-form @submit="save">
        <van-cell-group inset>
          <van-field name="uploader" label="头像" required>
            <template #input>
              <van-uploader v-model="tempData.AvatarUploader" :after-read="upload" :max-count="1" upload-text="头像" />
            </template>
          </van-field>
          <van-field v-model="tempData.nickname" label="昵称" placeholder="请输入昵称"
            :rules="[{ required: true, message: '请填写昵称' }]" clearable required />
          <van-field v-model="tempData.cellphone" label="手机号" readonly>
            <template #button>
              不可更改
            </template>
          </van-field>
          <van-cell>
            <template #title>
              <van-button color="#ca2904" style="width: 100%" round type="primary" native-type="save"
                :loading="saving">保存</van-button>
            </template>
          </van-cell>
        </van-cell-group>
      </van-form>
    </van-action-sheet>

    <van-action-sheet v-model:show="changePasswordVisibled" title="修改登录密码">
      <div class="my-setting-password">
        <van-cell-group inset>
          <van-field style="white-space: nowrap;" v-model="tempPasswordData.code" center clearable label-width="24vw"
            :label="this.data.cellphone" placeholder="请输入短信验证码">
            <template #button>
              <van-button @click="getSmsCode" color="#ca2904" size="small" type="primary" :disabled="isSendCode">{{
                isSendCode ? `${sendCodeTime}s` : '获取验证码' }}</van-button>
            </template>
          </van-field>
          <van-field v-model="tempPasswordData.newpwd" type="password" label="新密码" placeholder="请输入新密码" required />
          <van-field v-model="tempPasswordData.repwd" type="password" label="确认密码" placeholder="请再次输入新密码" required />
          <van-cell size="large">
            <template #title>
              <van-button round color="#ca2904" type="primary" size="large" @click="setPassword"
                :loading="saving">保存</van-button>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
    </van-action-sheet>

    <van-dialog v-model:show="showFollow" :closeOnClickOverlay="false" :showConfirmButton="false"
      style="background: transparent; display: flex; align-items: center; flex-direction: column;">
      <img :src="$file(FollowQRCode)" style="width: 60vw" />
      <div style="margin: 3.333vw 0">
        <span style="color: #fff">为了更好为您提供服务<br />请长按识别二维码关注公众号</span>
      </div>
      <van-button style="background: #fff; width: 60vw" @click="showFollow = false">关闭</van-button>
    </van-dialog>

  </div>

</template>

<script>
import ManagerPopup from "@/components/ManagerPopup.vue"

export default {
  name: 'My',
  components: { ManagerPopup },
  computed: {
  },
  beforeRouteEnter(to, from, next) {
    if (!localStorage.getItem('member_token')) {
      next({ name: 'Login', query: { redirect: to.fullPath } });
    } else {
      next();
    }
  },
  mounted() {
    this.init();
    this.$get('/v1/client/HWxinfoClient/qrcode').then(res => {
      this.FollowQRCode = res.data;
    });
    if (this.$isWechat()) {
      // alert(localStorage.getItem('openid'))
      this.$get(`/v1/client/DUsersClient/subscribe?openid=${localStorage.getItem('openid')}`).then(res => {
        // alert(JSON.stringify(res))
        if (res.data === false) {
          this.showFollow = true;
        }
      }).catch(() => { });
      // this.showFollow = true;
    }
    window.addEventListener('showManagerPopup', this.onShowManagerPopup)
    window.addEventListener('closeManagerPopup', this.onCloseManagerPopup)
  },
  beforeUnmount() {
    window.removeEventListener('showManagerPopup', this.onShowManagerPopup)
    window.removeEventListener('closeManagerPopup', this.onCloseManagerPopup)
  },
  data() {
    return {
      managerPopupVisible: false,
      data: { userimg: '', username: '' },
      settingVisibled: false,
      changePasswordVisibled: false,
      tempPasswordData: {
        code: '',
        newpwd: '',
        repwd: '',
      },
      showInfo: false,
      saving: false,
      tempData: {},
      showFollow: false,
      hf_data: {},
      hfLoading: true,
      isSendCode: false,
      sendCodeTime: 0,
      FollowQRCode: '',
    }
  },
  methods: {
    init() {
      if (!this.$isLogin()) {
        this.$showFailToast('登录状态异常，请重新登录')
        location.replace('#/Login')
        return
      }
      window.addEventListener('showManagerPopup', this.onShowManagerPopup)
      window.addEventListener('closeManagerPopup', this.onCloseManagerPopup)
      Promise.all([
        this.$get('/v1/client/DUsersClient').then(data => {
          // console.log(data);
          this.data = data.data;
          this.$ls.set('cellphone', data.data.cellphone);
          this.$ls.set('userimg', data.data.userimg);
          this.$ls.set('nickname', data.data.nickname);
          this.$ls.set('isshop', data.data.isshop);
          this.$ls.set('iscenter', data.data.col2);
          this.$ls.set('user_id', data.data.id);
          this.$ls.set('huiyuankaid', data.data.huiyuankaid);
          this.$ls.set('user_cv', data.data.xiaofeiquan);
          this.$ls.set('user_point', data.data.xiaofeijifen);
        }),
      ]
      )

    },
    onShowManagerPopup() {
      this.managerPopupVisible = true
    },
    onCloseManagerPopup() {
      this.managerPopupVisible = false
    },

    logout() {
      this.$showConfirmDialog({
        title: "确认退出？",
      }).then(() => {
        this.$ls.remove('member_token');
        location.replace('#/Login');
        setTimeout(() => {
          location.reload();
        }, 100);
      }).catch(() => { });
    },
    toInvite() {
      if (!this.data.allowinvitation) {
        this.$showFailToast('您暂无邀请权限');
        return
      }
      this.$navigate('Invite')

    },
    upload(file) {
      this.tempData.userimg = file.file;
    },
    save() {
      const fd = new FormData();
      fd.append('nickname', this.tempData.nickname);
      fd.append('cellphone', this.tempData.cellphone);
      if (this.tempData.userimg instanceof File) {
        fd.append('file', this.tempData.userimg);
      }
      this.$postForm('/v1/client/DUsersClient/userinfo', fd).then(() => {
        this.$showSuccessToast('保存成功');
        this.showInfo = false;
        window.location.reload();
      }).catch(err => {
        this.$showFailToast(err.message || '保存失败');
      });
    },
    valid(field, msg) {
      if (!field) {
        this.$showFailToast(msg);
        return false;
      }
      return true;
    },
    getSmsCode() {
      if (this.isSendCode) return;
      this.isSendCode = true;
      this.sendCodeTime = 60;
      const id = setInterval(() => {
        if (this.sendCodeTime > 0) this.sendCodeTime--;
        else { clearInterval(id); this.isSendCode = false; }
      }, 1000);

      this.$post('/v1/client/AuthClient/sendcode', {
        "purpose": "chgpwd",
        "cellphone": this.data.cellphone
      }).then(res => {
        if (res.status === 200) {
          this.$showSuccessToast('验证码发送成功')
        }
      }).catch(err => {
        clearInterval(id);
        this.isSendCode = false;
        this.$showFailToast(err.message);
      });
    },
    setPassword() {
      if (!this.tempPasswordData.newpwd) {
        this.$showFailToast('请输入新密码');
        return;
      }
      if (this.tempPasswordData.newpwd !== this.tempPasswordData.repwd) {
        this.$showFailToast('两次输入的密码不一致');
        return;
      }
      this.saving = true;
      this.$put('/v1/client/DUsersClient/changepwd', {
        "password": this.tempPasswordData.newpwd,
        "code": this.tempPasswordData.code
      }).then(res => {
        if (res.status === 200) {
          this.$showDialog({
            title: '密码重置成功！',
            message: '点击确认登录中心重新登录',
            theme: 'round-button',
            confirmButtonText: '确定',
          }).then(() => {
            this.saving = false;
            this.$ls.remove('member_token');
            location.replace('#/Login');
          });
        } else {
          this.$showFailToast(res.message);
          this.saving = false;
        }
      }).catch(err => {
        this.$showFailToast(err.message);
        this.saving = false;
      });
    },
  }
}
</script>