<template>
  <div class="information-wrap">
    <van-nav-bar
      title="个人资料"
      left-text=""
      left-arrow
      right-text="保存"
      :class="{isEdit: isEdit}"
      @click-left="back"
      @click-right="setData"
    >
      <van-icon :name="backHome ? 'wap-home' : 'arrow-left'" slot="left" />
    </van-nav-bar>
    <div class="wrap">
      <div class="avatar pr">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          ref="upload"
          :show-file-list="false"
          :data="uploadData"
          name="files"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="form.avatar" :src="form.avatar">
          <img v-else src="../../assets/imgs/avatar.png">
          <i class="pa icon icon-shangchuanzhaopian1"></i>
        </el-upload>
      </div>
      <van-cell-group>
        <div class="input">
          <input type="text" placeholder="昵称">
          <input type="text" v-model="form.userName">
        </div>
        <van-cell title="性别选择" @click="showGender = true" is-link v-if="form.sex == 1" :value="'男'" class="gender"/>
        <van-cell title="性别选择" @click="showGender = true" is-link v-else-if="form.sex == 2" :value="'女'" class="gender"/>
        <van-cell title="性别选择" @click="showGender = true" is-link v-else value="" class="gender"/>
        <van-cell title="生日" @click="showBirhday = true" is-link :value="form.birth" class="birthday"/>
        <van-cell title="身份验证"
          @click="getVerification"
          is-link
          :value="verification"
          :class="{active: verification == '未验证'}"
          class="verification"
        />
      </van-cell-group>
      <van-actionsheet
        v-model="showGender"
        :actions="actions"
        cancel-text="取消"
        @select="onSelect"
      />
      <van-popup v-model="showBirhday" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          @cancel="showBirhday = false"
          @confirm="getDate"
          :min-date="minDate"
          :max-date="maxDate"
        />
      </van-popup>
    </div>
  </div>
</template>

<script>
export default {
  name: "Information",
  data() {
    return {
      form: {
        avatar: "",
        userName: "",
        sex: "",
        birth: ""
      },
      copyForm: {},
      verification: "未验证",
      uploadData: {
        project: "hooli",
        contentType: "user/head"
      },
      isEdit: false,
      uploadUrl: this.$apis.api_upload_files,
      currentDate: new Date(),
      showGender: false,
      showBirhday: false,
      lang: this.$store.state.langStr,
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(),
      actions: [
        {
          name: "男",
          value: 1
        },
        {
          name: "女",
          value: 2
        }
      ],
      backHome: false
    };
  },
  created() {
    if (this.$util.sessionStorage.fetch("backHome")) {
      this.backHome = true;
    }
    const form = this.$util.sessionStorage.fetch("information");
    if (form) {
      this.isEdit = true;
      this.form = JSON.parse(decodeURIComponent(form));
    } else {
      this.getData();
    }
    let { uploadData } = this;
    Object.assign(uploadData, this.$net.commonParams());
    uploadData.signToken = this.$net.paramsSign(uploadData, this.uploadUrl);
    this.uploadData = uploadData;
  },
  watch: {
    form: {
      handler: function(val) {
        for (const key in val) {
          if (val.hasOwnProperty(key)) {
            if (val[key] != this.copyForm[key]) {
              this.isEdit = true;
              return;
            } else {
              this.isEdit = false;
            }
          }
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取数据
    getData() {
      let params = {};
      params.url = this.$apis.api_user_info_get;
      this.$net.req(params, this).then(
        res => {
          this.verification = res.data.cardContent;
          let data = this.$util.deepClone(res.data);
          this.form.avatar = data.avatar;
          this.form.userName = data.userName;
          this.form.sex = data.sex;
          this.form.birth = data.birth;
          this.copyForm = this.$util.deepClone(this.form);
        },
        e => {
          this.$Toast(e.msg);
        }
      );
    },
    // 上传之前验证图片
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt4M = file.size / 1024 / 1024 < 4;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG、PNG 格式!");
      }
      if (!isLt4M) {
        this.$message.error("上传头像图片大小不能超过 4MB!");
      }
      return isJPG && isLt4M;
    },
    // 上传成功
    handleAvatarSuccess(res) {
      this.form.avatar = res.data.host + res.data.url[0];
    },
    // 保存数据
    setData() {
      let params = {};
      params.url = this.$apis.api_user_info_set;
      params.data = this.form;
      if (this.isEdit) {
        if (!this.form.userName) {
          this.$Toast("请填写昵称");
          return;
        }
        if (this.form.userName.length < 2 || this.form.userName.length > 20) {
          this.$Toast("请输入2-20位的昵称");
          return;
        }
        this.$net.req(params, this).then(
          res => {
            const { code, msg, data } = res;
            if (parseInt(code) === 0) {
              this.$util.sessionStorage.remove("information");
              this.$util.setCookie(
                "loginUserInfo",
                encodeURIComponent(JSON.stringify(data))
              );
              this.$Toast(msg);
              window.location.href = "/";
            }
          },
          e => {
            this.$Toast(e.msg);
          }
        );
      } else {
        window.location.href = "/";
      }
    },
    confirmBack() {
      if (this.backHome) {
        this.$util.sessionStorage.remove("backHome");
        this.$util.sessionStorage.remove("information");
        this.$router.push("/");
      } else {
        window.history.length > 1
          ? this.$router.go(-1)
          : this.$router.push("/");
      }
    },
    // 返回
    back() {
      if (this.isEdit) {
        this.$Dialog
          .confirm({
            message: "您还没有保存信息，确定要退出？"
          })
          .then(() => {
            this.confirmBack();
          })
          .catch(() => {
            // on cancel
          });
      } else {
        this.confirmBack();
      }
    },
    // 选择性别
    onSelect(item) {
      this.showGender = false;
      this.form.sex = item.value;
    },
    // 选择生日
    getDate(val) {
      this.form.birth = this.$util.timestampToDate(Date.parse(val));
      this.showBirhday = false;
    },
    // 验证身份
    getVerification() {
      const form = encodeURIComponent(JSON.stringify(this.form));
      this.$util.sessionStorage.save("information", form);
      this.$router.push({
        path: "/" + this.lang + "/user/card"
      });
    }
  }
};
</script>
<style lang="less">
.van-picker__toolbar {
  z-index: 2003;
}
</style>


<style scoped lang='less'>
.information-wrap {
  background: #fff;
  min-height: 100vh;
  .wrap {
    padding: 0 20px;
    .avatar {
      margin: 26px 0 30px;
      width: 90px;
      height: 90px;
      .avatar-uploader {
        border-radius: 90px;
        width: 90px;
        height: 90px;
        object-fit: cover;
        background: #eee;
      }
      img {
        width: 90px;
        height: 90px;
        object-fit: cover;
        background: #eee;
        display: inline-block;
        border-radius: 90px;
      }
      i {
        bottom: 2px;
        right: 8px;
        font-size: 12px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 20px;
        color: #fff;
        background: rgba(0, 0, 0, 0.5);
      }
    }
    .van-cell-group:after {
      height: 0;
      border: 0;
    }
    .input {
      display: flex;
      margin-bottom: 10px;
      input:first-child {
        width: 30%;
        height: 60px;
        background: rgba(249, 249, 249, 1);
        border-radius: 4px;
        border: 0;
        text-indent: 15px;
        font-size: 16px;
        color: #333;
      }
      input:last-child {
        width: 70%;
        height: 60px;
        background: rgba(249, 249, 249, 1);
        border-radius: 4px;
        border: 0;
        padding-right: 15px;
        font-size: 16px;
        color: #333;
        text-align: right;
        font-weight: 500;
      }
    }
    .van-cell {
      background: rgba(249, 249, 249, 1);
      color: #bbb;
      font-weight: 500;
    }
    .van-cell:after {
      height: 0;
      border: 0;
    }
    .gender,
    .birthday,
    .verification {
      margin-bottom: 10px;
    }
    ::-webkit-input-placeholder {
      color: #bbb;
    }
    ::-moz-placeholder {
      color: #bbb;
    }
    ::-moz-placeholder {
      color: #bbb;
    }
    :-ms-input-placeholder {
      color: #bbb;
    }
  }
}
</style>
