<template>
  
  <BaseContainer>
    <NavBar title="个人资料" />
    <view class="user-info">
			<view class="info-box">
				<view class="avatar" @click="handlePickAvatar">
					<view class="name">头像</view>
					<image :src="xUserInfo.avatar" class="image" mode="aspectFill" />
					<view class="iconfont iconxiangyou"></view>
				</view>
				<view class="list">
					<view class="item">
						<span class="name">昵称</span>
						<input v-model="xUserInfo.nickname" class="value input" type="text" />
					</view>
					<navigator v-if="xUserInfo.phone" class="item" url="/pages/my/save_phone">
						<span class="name">手机号</span>
						<span class="value">{{ xUserInfo.phone }}</span>
						<span class="iconfont iconxiangyou"></span>
					</navigator>
				</view>
			</view>
			<view class="info-box">
				<view class="list">
					<view class="item">
						<span class="name">收货邮箱</span>
						<input v-model="xUserInfo.email" class="value input" type="text" />
					</view>
					<navigator class="item" :url="`/pages/forgotPwd/index?phone=${xUserInfo.phone}`">
						<span class="name">修改密码</span>
						<span class="value"></span>
						<span class="iconfont iconxiangyou"></span>
					</navigator>
				</view>
      </view>
      <view class="btn-group">
        <button class="btn flex flex-center" type="button" @click="save_user_info">
          提交
        </button>
        <button class="btn flex flex-center out-btn" type="button" @click="logout">
          退出
        </button>
        <button class="btn flex flex-center out-btn" type="button" @click="deleteUser">
          注销
        </button>
      </view>
    </view>
    <view :class="{ mask: popupShow }" @click="popupShow = false"></view>
    <view :class="{ on: popupShow }" class="popup">
      <navigator @click="popupShow = false" class="close-btn">
        <i class="iconfont iconguanbi"></i>
      </navigator>
      <view class="popup-title">修改密码</view>
      <view class="popup-body">
        <view class="item">
          <i class="iconfont iconshouji"></i>
          <input :value="xUserInfo.phone" type="text" readonly />
        </view>
        <view class="item">
          <view>
            <i class="iconfont iconyanzhengma"></i>
            <input v-model.trim="code" type="text" placeholder="请填写验证码" />
          </view>
          <button class="get-code-btn" :disabled="count >= 0" type="button" @click="getCode">
            {{ count< 0? "获取验证码" : "重新获取(" + count + "s)" }} </button>
        </view>
        <view class="item">
          <i class="iconfont iconmima"></i>
          <input v-model.trim="pwd" type="password" placeholder="请填写8-16位字母加数字组合密码" />
        </view>
        <button type="button" class="flex flex-center" @click="submitPassword">
          确认
        </button>
      </view>
    </view>
  </BaseContainer>
</template>

<script>
import userInfoMixin from "@/mixins/userInfo";
import store from "@/store";
import { changePwd, getAuthCode, saveUserInfo, logout, deleteUser } from "@/api/user";
import { VALID_LOGIN_STATUS, REQUEST_PERMISSIONS } from "@/store/types/action-types";
import { SET_LOGIN, SET_LOGOUT } from "@/store/types/muations-types";


export default {
  mixins: [userInfoMixin],
  data() {
    return {
      xUserInfo: {},
      popupShow: false,
      count: -1,
      COUNT_TIME: 60,
      code: "",
      pwd: "",
    };
  },
  onLoad() {
    if (this.userInfo?.nickname) {
      this.xUserInfo = {
        ...this.userInfo,
      };
      uni.setNavigationBarTitle({
        title: this.userInfo.nickname + " - 个人资料",
      });
    }
  },
  mounted: function () {
    // var that = this;
    // $(this.$refs.avatar).change(function (e) {
    //   var formdata = new FormData();
    //   if (e.target.files[0]) {
    //     formdata.append("file", e.target.files[0]);
    //     app.basePost($h.U({ c: "auth_api", a: "upload" }), formdata, function (res) {
    //       that.userInfo.avatar = res.data.data.url;
    //     });
    //   }
    // });
  },
  methods: {
    PhoneNumber(e) {
      console.log(e.detail.code)
    },
    async handlePickAvatar() {
			// #ifdef APP-PLUS
			let result = await store.dispatch("app/" + REQUEST_PERMISSIONS, 'CAMERA')
			if (result !== 1) return
			let result1 = await store.dispatch("app/" + REQUEST_PERMISSIONS, 'WRITE_EXTERNAL_STORAGE')
			if (result1 !== 1) return
			this.chooseImage();
			// #endif
			// #ifdef APP-PLUS
			this.chooseImage();
			// #endif
	},
		async chooseImage() {
			const { tempFilePaths } = await this.$util.wrapFn(uni.chooseImage, {
			  count: 1,
			  extension: ["png", "jpg", "jpeg"],
			});
			const path = tempFilePaths[0];
			
			uni.showLoading({
			  mask: true,
			});
			try {
			  console.log(path);
			  const result = await this.$util.uploadImg(path);
			  this.xUserInfo.avatar = result;
			  uni.hideLoading();
			} catch (err) {
			  uni.hideLoading();
			  this.$util.showMsg(err.msg || err);
			}
		},
    async save_user_info() {
      let { nickname, avatar, email } = this.xUserInfo;
      nickname = nickname.trim();
      if (nickname == "" || nickname.length > 15) {
        return this.$util.showMsg("昵称长度必须在1-15个字符之间！");
			}
			if (email === '' || !(/\w+[@]{1}\w+[.]\w+/.test(email))) {
        return this.$util.showMsg("邮箱格式错误！");
			}
      uni.showLoading({
        mask: true,
      });

      try {
        const result = await saveUserInfo({
          nickname,
          avatar,
					email,
        });
        this.$util.showMsg(result.msg);

        this.$store.dispatch("app/" + VALID_LOGIN_STATUS);
      } catch (err) {
        uni.hideLoading();
        this.$util.showMsg(err);
      }
    },
    async getCode() {
      this.count = this.COUNT_TIME;
      this.timer = setInterval(() => {
        this.count--;
        if (this.count < 0) {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);

      uni.showLoading({ mask: true });

      try {
        const { data } = await getAuthCode(this.xUserInfo.phone);
        uni.hideLoading();
        this.$util.showMsg(data.Message);
      } catch (errr) {
        uni.hideLoading();
        this.$util.showMsg(err.msg);
        clearInterval(this.timer);
        this.timer = null;
        this.count = -1;
      }
    },
    // 点击密码弹窗确认按钮
    async submitPassword() {
      if (!this.code) {
        return this.$util.showMsg("请填写验证码");
      }
      if (!this.pwd) {
        return this.$util.showMsg("请填写新密码");
      }
      if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(this.pwd)) {
        return this.$util.showMsg("请填写8-16位字母加数字组合密码");
      }

      uni.showLoading({ mask: true });
      try {
        const { data, msg } = await changePwd({
          account: this.xUserInfo.phone,
          pwd: this.$util.hexMd5(this.pwd),
          code: this.code,
          type: 2,
        });
        uni.hideLoading();
        this.popupShow = false;
        this.code = "";
        this.pwd = "";
        this.$util.showMsg(msg);
      } catch (err) {
        console.log(err);
        this.count = -1;
        uni.hideLoading();
        this.$util.showMsg(err.msg);
      }
    },
    // 退出登录
    logout() {
      uni.showModal({
        title: "提示",
        content: "确定退出登录？",
        success: ({ confirm }) => {
          if (!confirm) return;
          logout();
          this.$store.commit("app/" + SET_LOGOUT);
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/index/index",
            });
          }, 500);
        },
      });
    },
		deleteUser() {
			uni.showModal({
			  title: "提示",
			  content: "确定注销账号？",
			  success: async ({ confirm }) => {
			    if (!confirm) return;
					await deleteUser();
			    this.$store.commit("app/" + SET_LOGOUT);
			    setTimeout(() => {
			      uni.reLaunch({
			        url: "/pages/index/index",
			      });
			    }, 500);
			  },
			});
		}
  },
};
</script>

<style scoped lang="scss">
input {
  height: 98rpx;
}
.user-info {
	padding-top: 10rpx;
	background: #f6f6f6;
	.info-box {
		background: #fff;
		padding: 0 30rpx;
		margin-bottom: 20rpx;
	}
}

.user-info .avatar {


  display: flex;


  align-items: center;
  background-color: #ffffff;
  border-bottom: 1px solid #f5f5f5;
}

.user-info .avatar .name {
  flex: 1;
  font-weight: 500;
  font-size: 30rpx;
  color: #333;
}

.user-info .avatar .image {
  width: 90rpx;
  height: 90rpx;
  border-radius: 50%;
  overflow: hidden;
}

.user-info .avatar .iconfont {
  margin-left: 30rpx;
  font-size: 24rpx;
  color: #999999;
}

.user-info .avatar .input {
  display: none;
}

.user-info .list {
  background-color: #ffffff;
}

.user-info .list .item {
  display: flex;
  align-items: center;
  height: 98rpx;
  border-bottom: 1px solid #e6e6e6;
	&:last-child {
		border-bottom: none;
	}
}

.user-info .list .item .name {
  flex: 1;
  font-weight: 500;
  font-size: 30rpx;
  color: #333;
}

.user-info .list .item .value {
  font-size: 28rpx;
  color: #666;
}

.user-info .list .item .iconfont {
  margin-left: 30rpx;
  font-size: 24rpx;
  color: #999999;
}

.user-info .list .item .input {
  font-family: inherit;
  text-align: right;
  flex: 1;
}

.user-info .btn-group {
  padding: 176rpx 30rpx 0;
}

.user-info .btn-group .btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  margin-bottom: 30rpx;
  background: linear-gradient(0deg, #0F74BB 0%, #3293FF 100%);;
  font-size: 32rpx;
  color: #ffffff;
	border: none;
	&:after {
		display: none;
	}
}

.user-info .btn-group .btn:last-child {
  margin-bottom: 0;
}

.user-info .btn-group .out-btn {
  background: #E5E5E5;
  color: #A2A2A2;
}

.user-info .group .link {
  display: block;
  width: 100%;
  height: 86rpx;
  border: 1px solid #ccc;
  border-radius: 43rpx;
  margin-top: 30rpx;
  font-weight: 500;
  font-size: 30rpx;
  line-height: 82rpx;
  text-align: center;
  color: #999999;
}

.user-info .list .item.password {
  justify-content: space-between;
}

.popup {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 60;
  border-radius: 20rpx 20rpx 0 0;
  background: #ffffff;
  transform: translateY(100%);
  transition: 0.3s;
}

.popup.on {
  transform: translateY(0);
}

.close-btn {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  z-index: 2;

  .iconfont {
    font-size: 27rpx;
    color: #8a8a8a;
  }
}

.popup-title {
  padding: 40rpx 0 34rpx;
  font-weight: bold;
  font-size: 36rpx;
  line-height: 50rpx;
  text-align: center;
  color: #282828;
}

.popup-body {
  padding: 0 30rpx calc(var(--safe-bottom) + 30rpx);
}

.popup .item {
  position: relative;
  display: flex;
  align-items: center;
  height: 119rpx;
  padding: 0 15rpx;
}

.popup .item::after {
  content: "";
  position: absolute;
  right: 15rpx;
  bottom: 0;
  left: 15rpx;
  z-index: 2;
  height: 1px;
  border-bottom: 1px solid #cccccc;
}

.popup .item .iconfont {
  font-size: 40rpx;
}

.popup .item input {
  flex: 1;
  min-width: 0;
  margin-left: 25rpx;
}

.popup .item:nth-child(2) {
  padding-right: 0;
}

.popup .item:nth-child(2) view {
  flex: 1;
  display: flex;
  align-items: center;
  min-width: 0;
}

.get-code-btn {
  width: 200rpx;
  font-size: 26rpx;
  color: #2c8eff;

  &::after {
    border: none;
  }
}

.popup>view>button {
  width: 100%;
  height: 86rpx;
  border-radius: 43rpx;
  margin-top: 50rpx;
  background: #2c8eff;
  font-size: 30rpx;
  color: #ffffff;
}
</style>
