<template>
  <div class="boxs">
    <div style="width: 500px; margin: auto; margin-top: 30px">
      <div style="height: 100px; position: relative">
        <el-upload
          class="avatar-uploader"
          action="/api/file/upload/img?module=personnel"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :headers="myHeaders"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="form.userPic"
            :src="'api/file/pub/' + form.userPic"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <img
          src="@/assets/img/userCenter/setUp.png"
          alt=""
          style="position: absolute; right: 180px; bottom: -10px; width: 40px"
        />
        <!-- <img :src="'api/file/pub/'+ form.photo" alt="" style="width: 100px;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);"/> -->
      </div>
    </div>
    <div style="height: 400px; position: relative; width: 100%">
      <el-form
        ref="form"
        :model="form"
        label-width="140px"
        style="
          position: absolute;
          left: 53%;
          top: 55%;
          transform: translate(-55%, -50%);
          width: 400px;
          height: 400px;
        "
      >
        <el-form-item :label="$t('common.MobilePhone')">
          <el-input v-model="form.userPreferredMobile" disabled></el-input>
          <!--              <span style="margin-left: 20px;color: #2c5589;" class="cursor" @click="dialogVisibles(1)">修改邮箱</span>-->
        </el-form-item>
        <el-form-item :label="$t('common.Email') + ':'">
          <el-input v-model="form.userEmail" disabled></el-input>
          <!--              <span style="margin-left: 20px;color: #2c5589;" class="cursor" @click="dialogVisibles(1)">修改邮箱</span>-->
        </el-form-item>
        <el-form-item :label="$t('common.DateOfRegistration')">
          <el-input v-model="form.userAccountRegistertime" disabled></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.CustomerType')">
          <el-input v-model="form.region" disabled></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.LogInLast')">
          <el-input v-model="form.lastLoginTime" disabled></el-input>
        </el-form-item>
        <!--  <el-form-item label="修改密码:">
                <el-input v-model="form.date3" disabled></el-input>
                <span style="margin-left: 20px;color: #2c5589;" class="cursor" @click="dialogVisibles(2)">修改密码</span>
            </el-form-item>-->
      </el-form>
    </div>
    <div>
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="30%"
        height="50%"
        v-if="ifDiaslog == 2"
      >
        <div style="height: 200px; position: relative; width: 100%">
          <el-form
            ref="form"
            :model="form"
            label-width="80px"
            style="
              position: absolute;
              left: 56%;
              top: 55%;
              transform: translate(-55%, -50%);
              width: 400px;
            "
          >
            <el-form-item :label="$t('common.OriginalPassword')">
              <el-input v-model="passWord.passWord1"></el-input>
            </el-form-item>
            <el-form-item :label="$t('common.NewPassword')">
              <el-input v-model="passWord.passWord2"></el-input>
            </el-form-item>
            <el-form-item :label="$t('common.ConfirmPassword')">
              <el-input v-model="passWord.passWord3"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">{{
            $t("common.Cancel")
          }}</el-button>
          <el-button type="primary" @click="dialogVisible = false">{{
            $t("common.Confirm")
          }}</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="30%"
        height="50%"
        v-if="ifDiaslog == 1"
      >
        <div style="height: 200px; position: relative; width: 100%">
          <el-form
            ref="form"
            :model="form"
            label-width="100px"
            style="
              position: absolute;
              left: 56%;
              top: 55%;
              transform: translate(-55%, -50%);
              width: 400px;
            "
          >
            <el-form-item :label="$t('common.Mailbox')">
              <el-input v-model="passWord.passWord1"></el-input>
            </el-form-item>
            <el-form-item :label="$t('common.VerificationCode')">
              <el-input v-model="passWord.passWord2"></el-input>
              <span
                v-show="show"
                @click="getCode"
                style="margin-left: 20px; color: #2c5589"
                class="cursor"
                >{{ $t("common.GetCaptcha") }}</span
              >
              <span
                v-show="!show"
                class="count"
                style="margin-left: 20px; color: #999"
                >{{ count }}{{ $t("common.SendInSeconds") }}</span
              >
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">{{
            $t("common.Cancel")
          }}</el-button>
          <el-button type="primary" @click="dialogVisible = false">{{
            $t("common.Confirm")
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { findBasicInfo, saveUserPic } from "@/api/user";
import { getDicts } from "@/api/dict";
import { getToken } from "@/utils/auth";
import { addIntegral, addGrowth } from "@/utils/toCompleteTask";
import { getUserPointPage } from "@/api/user";
export default {
  name: "userCenterEssentialInformation",
  data() {
    return {
      informationsClass: "1",
      dialogVisible: false,
      ifDiaslog: "",
      imageUrl: "",
      title: "",
      form: {
        userPreferredMobile: "",
        userAccountRegistertime: "",
        userEmail: "",
        name: "1233@163.com",
        region: "",
        date1: "2018-05-19",
        date3: "2018-05-19",
        date2: "2020-05-25  11：20：23",
        delivery: false,
        type: [],
        resource: "",
        userPic: "/def/user.png",
        desc: "",
      },
      passWord: {
        passWord1: "",
        passWord2: "",
        passWord3: "",
      },
      Emal: {
        newEmal: "",
        VerificationCode: "",
      },
      userUsertypeDicts: [],
      show: true,
      count: "",
      timer: null,
      myHeaders: { Authorization: "Bearer " + getToken() },

      user: {
        umsUser: {},
      },
      pointStatus: null,
    };
  },
  computed: {
    userUsertypeMap: function () {
      return this.userUsertypeDicts.array2Obj("value", "label");
    },
  },
  watch: {
    "$i18n.locale"() {
      this.initData();
      this.userBasicInfo();
    },
  },
  created() {
    this.initData();
    this.userBasicInfo();
  },
  methods: {
    initData: function () {
      getUserPointPage().then((res) => {
        this.pointStatus = res.data.umsUserPoints[0].pointStatus;
      });
    },
    async userBasicInfo() {
      if (this.$i18n.locale.toUpperCase() == "EN") {
        await getDicts("USERTYPE_DICT_EN").then((result) => {
          if (result.data) {
            this.userUsertypeDicts = result.data["0"] || [];
          }
        });
      } else {
        await getDicts("USERTYPE_DICT").then((result) => {
          if (result.data) {
            this.userUsertypeDicts = result.data["0"] || [];
          }
        });
      }
      await findBasicInfo().then((result) => {
        this.form = result.data;
        console.log("this.form", this.form);
        if (!this.form.userPic) {
          this.form.userPic = "/def/user.png";
        }
        console.log(this.form.userAccountRegistertime);
        const regtime = this.YymmddFormat(
          new Date(this.form.userAccountRegistertime)
        );
        const logintime = this.YymmddFormat(new Date(this.form.lastLoginTime));
        if (this.form.userAccountRegistertime !== undefined)
          this.form.userAccountRegistertime = regtime;
        if (this.form.lastLoginTime !== undefined)
          this.form.lastLoginTime = logintime;
        var userUsertypeMap = this.userUsertypeDicts.array2Obj(
          "value",
          "label"
        );
        if (result.data.userUsertypeDict !== undefined) {
          console.log(userUsertypeMap[result.data.userUsertypeDict]);
          this.form.region = userUsertypeMap[result.data.userUsertypeDict];
        }
        if (this.form.userPreferredMobile) {
          this.form.userPreferredMobile =
            this.form.userPreferredMobile.substr(4, 3) +
            "****" +
            this.form.userPreferredMobile.substr(11);
        }
      });
    },
    getInformation(num) {
      this.informationsClass = num;
    },
    // handleClose(done) {
    //     this.$confirm('确认关闭？')
    //     .then(_ => {
    //         done();
    //     })
    //     .catch(_ => {});
    // },
    //中国标准时间 转 yy-MM-dd hh:mm:ss
    YymmddFormat(newDate) {
      let Month = newDate.getMonth() + 1;
      Month = Month >= 10 ? Month : "0" + Month;
      let d = newDate.getDate();
      d = d >= 10 ? d : "0" + d;
      return [
        [newDate.getFullYear(), Month, d].join("-"),
        [newDate.getHours(), newDate.getMinutes(), newDate.getSeconds()].join(
          ":"
        ),
      ].join(" ");
    },
    dialogVisibles(num) {
      this.ifDiaslog = num;
      if (num == 1) {
        this.title = "修改邮箱";
        this.$router.push({
          name: "",
        });
      } else if (num == 2) {
        this.title = "修改密码";
        this.$router.push({
          name: "",
        });
      }
      // this.dialogVisible=true
    },
    getCode() {
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.userPic = res.data;
      //保存图像
      saveUserPic(this.form.userPic)
        .then((result) => {
          if (
            this.user.umsUser.userUsertypeDict !== "2" &&
            this.pointStatus == "y"
          ) {
            addIntegral("point_task_upload_head_portrait", 20);
            addGrowth("point_task_upload_head_portrait");
          }
          this.$forceUpdate();
          this.$message({
            message: this.$t("common.uploadSuccess"),
            type: "success",
          });
          //头像路径更新到localstorage
          let user = JSON.parse(window.localStorage.getItem("user"));
          user.umsUser.userPic = this.form.userPic;
          window.localStorage.setItem("user", JSON.stringify(user));
        })
        .catch((error) => {
          this.$message({
            message: error.msg,
            type: "error",
          });
        });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      /* if (!isJPG) {
                 this.$message.error('上传头像图片只能是 JPG 格式!');
                 return;
                 }*/
      /*if (!isLt2M) {
                    this.$message.error(this.$t('common.uploadInfo'));
                    return;
                }*/
      // return isJPG && isLt2M;
    },
  },
};
</script>
<style scoped>
.box1:after {
  display: block;
  clear: both;
  content: "";
  visibility: hidden;
  height: 0;
}
.el-input {
  width: 75%;
}
.el-form {
  width: 500px !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 125px;
  height: 110px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 105px;
  height: 110px;
  display: block;
  border-radius: 60px;
  overflow: hidden;
}
.boxs >>> .el-upload {
  position: absolute;
  left: 50%;
  top: 0;
  transform: translateX(-50%);
}
</style>
