<template>
  <div
    class="userInfo"
    :style="{
      '--main-color': themeColor['--main-color'],
      '--minor-color': themeColor['--minor-color'],
    }"
  >
    <div class="line"></div>
    <!--头像-->
    <div class="personal-top">
      <div class="updateHeadPic flex flex-cen">
        <div class="van-cell__title">
          <span>头像</span>
        </div>
        <div class="van-cell__value">
          <!--   <div class="van-field__icon" >
          </div>-->
          <div class="userPic">
            <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
              <image
                mode="aspectFill"
                v-if="userMsg.headPortraitUrl != ''"
                :src="userMsg.headPortraitUrl"
              />
              <image
                v-else
                src="http://mayi-newshop.oss-cn-shanghai.aliyuncs.com/public/jpg/39ada9cc-aff3-4842-8376-9f49e36c5811.jpg"
                alt
              />
            </button>
          </div>
        </div>
        <van-icon name="arrow" />
      </div>
    </div>
    <div class="line"></div>
    <!--个人信息-->
    <div class="updateInfo">
      <!-- 昵称 -->
      <van-field
        placeholder="请输入昵称"
        :value="userMsg.nickname"
        @change="changeNickName"
        maxlength="20"
        label="昵称"
        type="nickname"
        class="shuru"
        input-align="right"
      />
      <van-field
        placeholder="请输入姓名"
        :value="userMsg.realname"
        @change="changeRealName"
        maxlength="20"
        label="姓名"
        class="shuru"
        input-align="right"
      />

      <!-- 性别 -->
      <van-cell
        title="性别"
        @click="sex_show = true"
        :value="sex_list[userMsg.gender]"
        is-link
      />
      <!-- <div class="covername sex">{{userMsg.gender}}</div> -->
      <!-- 设置生日 -->
      <div @click="birthShow = true">
        <van-cell
          v-if="userMsg.birth"
          title="生日"
          :value="userMsg.birth"
          is-link
        />
        <van-cell v-else title="生日" value="未设置" is-link />
      </div>

      <div class="line"></div>
      <!--手机-->
      <div class="tel flex flex-btw">
        <div>手机号</div>
        <div
          class="font15"
          v-if="userMsg.mobilephone"
          @click="toUpdateBindPhone"
        >
          <!-- {{ correctTel(userMsg.mobilephone) ? userMsg.mobilephone : "未认证" }} -->
          {{mobilephone}}
          <van-icon name="arrow" />
        </div>
      </div>
    </div>

    <div class="btn-user" @click="submit">保存</div>
    <!-- 性别弹出层 -->
    <div catchtouchmove="ture">
      <van-popup :show="sex_show" position="bottom">
        <van-picker
          :columns="sex_list"
          :show-toolbar="true"
          @confirm="chooseSex"
          @cancel="chooseSexCancel"
        />
      </van-popup>
    </div>
    <!-- 设置生日弹框 -->
    <div catchtouchmove="ture">
      <van-popup :show="birthShow" position="bottom">
        <van-datetime-picker
          :min-date="minDate"
          :max-date="maxDate"
          :value="currentTime"
          type="date"
          :show-toolbar="true"
          @confirm="chooseBirth"
          @cancel="chooseBirthCancel"
        />
      </van-popup>
    </div>
    <!-- <div @click="click">按下试试</div> -->
  </div>
</template>

<script>
import live from "@/api/live";
import index from "@/api/index";
import { DFSImg } from "@/utils/index";
import { themeColor } from "@/utils/mayi.js";
import { formatTime } from "@/utils/index";
const app = getApp()
export default {
  name: "userInfo",
  data() {
    return {
      userMsg: {
        headPortraitUrl: "",
        birth: 0,
        realname: "",
        mobilephone: "",
        nickname: "",
      },
      imgArr: [],
      minDate: new Date(1900, 1, 1).getTime(),
      maxDate: new Date().getTime(),
      birthShow: false,
      sex_show: false,
      sex_list: ["女", "男", "未设置"],
      imgNumLimit: 1,
      currentTime: new Date().getTime(),
      currentTime2: new Date().getTime(),
      update_info_data: {},
      maxSize: 3145728,
      themeColor: {
        "--main-color": "",
        "--minor-color": "",
      },
      ossConfig: {},
    };
  },
  computed: {
    mobilephone() {
      return this.correctTel(this.userMsg.mobilephone) ? this.userMsg.mobilephone : "未认证";
    }
  },
  onLoad() {
    console.log("onLoad-----------------");
    if (themeColor["--main-color"] != "#ffffff") {
      this.themeColor = themeColor;
    } else {
      this.mpApp.themeColorCallBack = (res) => {
        this.themeColor = res;
      };
    }
  },
  onShow() {
    this.getUserMsg();
  },
  methods: {
    toUpdateBindPhone() {
      let _this = this;
      if (this.correctTel(this.userMsg.mobilephone)) {
        app.$themeToLink({
          type: 1,
          link: `/personalCenter/updateBindPhone?mobilephone=${_this.userMsg.mobilephone}`,
        })
      } else {
        console.log(this.$store.state.userInfo, "-------------------135");
        app.$themeToLink({
          type: 1,
          link: `/login/wxRegister?openId=${_this.$store.state.userInfo.wxMiniOpenId}`,
        })
      }
    },
    click() {
      console.log(999999);
    },
    // 返回
    returnClick() {
      // this.$router.back(-1);
      //会员信息组件跳转回原组件
      if (this.$route.query.memberInfo) {
        this.$router.back(-1);
      } else {
        this.$router.push("/personalCenter");
      }
    },
    getUserMsg() {
      live.getUserInfo().then((res) => {
        let result = res.data.data;
        this.userMsg = {
          ...result,
          birth: result.birth ? result.birth.split(" ")[0] : "",
          headPortraitUrl: DFSImg(
          result.headPortraitUrl,
            400,
            400,
            1
          )
        };
        console.log(this.userMsg, "--------------userMsg");
      });
    },
    changeNickName(val) {
      this.userMsg.nickname = val.mp.detail;
    },
    changeRealName(val) {
      this.userMsg.realname = val.mp.detail;
    },
    submit() {
      // 获取需要提供的数据
      // this.userMsg.headPortraitUrl=this.uploadImg;
      this.update_info_data.userId = this.userMsg.userId;
      this.update_info_data.mobilephone = this.userMsg.mobilephone;
      this.update_info_data.nickname = this.userMsg.nickname;
      this.update_info_data.birth = this.userMsg.birth
        ? `${this.userMsg.birth} 00:00:00`
        : "";
      this.update_info_data.gender = this.userMsg.gender.toString();
      this.update_info_data.headPortraitUrl = this.userMsg.headPortraitUrl;
      this.update_info_data.realname = this.userMsg.realname;

      if (this.userMsg.nickname == "" || this.userMsg.nickname == " ") {
        wx.showToast({
          title: "昵称不得为空",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      if (this.userMsg.nickname.length > 20) {
        wx.showToast({
          title: "昵称不得超过20个字符",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      index.update_info(this.update_info_data).then((res) => {
        if (res.data.code == 200) {
          let _this = this;
          this.currentTime = new Date(_this.userMsg.birth).getTime();
           wx.showToast({
            title: "保存成功",
            icon: "success",
            duration: 2000,
          });
          wx.setStorageSync("reloadTabbarPage",1)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000,
          });
        }
      });
    },
    // onRead(file) {
    //   console.log(file)
    //   this.uploadImg = file.content;
    //   let uploadImgReq = this.uploadImg
    //   common.getUploadImg({uploadImgReq:uploadImgReq}).then(res => {
    //     console.log(res);
    //   })

    // },
    chooseSex(value) {
      console.log(value, "------------------264");
      let val = value.mp.detail.index;
      this.userMsg.gender = val;
      // if (val == "女") {
      // } else if (val == "男") {
      //   this.userMsg.gender = 1;
      // } else {
      //   this.userMsg.gender = 2;
      // }
      this.sex_show = false;
    },
    chooseSexCancel() {
      this.sex_show = false;
    },
    chooseBirth(val) {
      console.log(
        val,
        formatTime(new Date(val.mp.detail)).split(" ")[0].replace(/\//g, "-"),
        "----------val"
      );
      let brith = formatTime(new Date(val.mp.detail))
        .split(" ")[0]
        .replace(/\//g, "-");
      this.userMsg.birth = brith;
      this.birthShow = false;
    },
    chooseBirthCancel() {
      this.birthShow = false;
    },
    // 校验真实手机号
    correctTel(val) {
      return /^1\d{10}$/.test(val);
    },
    sexTransform(value) {
      console.log(value, "--------------249");
      if (value == 0) {
        return "女";
      } else if (value == 1) {
        return "男";
      } else {
        return "未设置";
      }
    },
    onChooseAvatar(val) {
      let userImg = val.mp.detail.avatarUrl;
      console.log(userImg, "---------------------299");
      let _this = this;
      wx.showLoading({
        title: '上传中...',
      })
      this.get_oss_config(()=>{
        let fileName = `${_this.ossConfig.dir}${userImg.split("/").pop()}`;
        console.log(fileName,'----------fileName')
        wx.uploadFile({
          url: `${_this.ossConfig.host}`,
          filePath: userImg,
          name: "file",
          formData: {
            key: fileName,
            OSSAccessKeyId: _this.ossConfig.accessid,
            policy: _this.ossConfig.policy,
            signature: _this.ossConfig.signature,
            success_action_status: "200",
          },
          success(res) {
            if (res.statusCode == 200) {
              let host =
                _this.ossConfig.host.substr(-1) == "/"
                  ? _this.ossConfig.host
                  : `${_this.ossConfig.host}/`;
              _this.userMsg.headPortraitUrl = `${host}${fileName}`;
              console.log(_this.userMsg.headPortraitUrl,'---_this.userMsg.headPortraitUrl')
              wx.hideLoading();
            }
            //do something
          },
          fail(res) {
            console.log(res, "-----------------fail");
            wx.showToast({
              title: "上传失败",
              icon: "error",
              duration: 1000,
            });
          },
        });
      });
    },
    random_string(len) {
      len = len || 32;
      let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let maxPos = chars.length;
      let pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    get_oss_config(callback=()=>{}) {
      index.get_oss_config().then((res) => {
        console.log(res.data,'-------------------------res375')
        this.ossConfig = res.data;
        console.log(this.ossConfig, "--ossConfig");
        callback();
      });
    },
  },
};
</script>

<style scoped lang="scss">
.line {
  height: 10px;
  background-color: #f5f5f5;
}
.r {
  margin-right: 18px;
}
i {
  font-size: 18px;
}
.font15 {
  font-size: 15px;
  color: #929292;
}
.userInfo {
  .personal-top {
    width: 100%;
    height: 80px;
    position: relative;
    .updateHeadPic {
      height: 80px;
      padding: 0 17px 0 15px;

      .userPic {
        width: 58px;
        height: 58px;
        border-radius: 50%;
        overflow: hidden;
        border: 1px solid #acacac;
        margin-left: 80px;
        button {
          width: 100%;
          height: 100%;
          padding: 0;
        }
        image {
          width: 100%;
          height: 100%;
        }
      }
      .uploader {
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 10;
        right: 0;
      }
      .van-cell__title {
        flex: 1;
        font-size: 15px;
        font-weight: bold;
        color: #191919;
      }
      .van-cell__value {
      }
      .van-cell:not(:last-child)::after {
        right: 15px;
        border-color: #dbdbdb;
      }
    }
  }
  .updateInfo {
    position: relative;
    width: 100%;
    .van-cell {
      width: 100%;
      height: 55px;
      // border-bottom: 1px solid #f0f2f5;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .covername {
      width: 45px;
      height: 15px;
      position: absolute;
      right: 18px;
      top: 20px;
      font-size: 15px;
      font-family: MicrosoftYaHei;
      font-weight: 400;
      color: rgba(146, 146, 146, 1);
    }
    .sex {
      top: 70px;
    }
    .rightIco {
      padding-right: 14px;
      color: #929292;
    }
  }
  .tel {
    height: 55px;
    padding: 0 15px 0 15px;
    font-size: 15px;
    i {
      vertical-align: text-top;
    }
  }
  .btn-user {
    position: fixed;
    bottom: 20px;
    width: 350px;
    height: 44px;
    line-height: 44px;
    background: var(--main-color);
    border-radius: 4px;
    left: 50%;
    margin-left: -175px;
    font-size: 17px;
    color: #ffffff;
    text-align: center;
  }
}
/deep/ .van-cell__title,
.van-cell__value {
  font-size: 15px;
}
</style>