<template>
  <div>
    <div
      style="
        height: 600px;
        position: relative;
        width: 100%;
        margin-top: 30px;
        min-height: 700px;
      "
    >
      <div
        style="
          margin-left: 200px;
          font-size: 14px;
          font-weight: 700;
          color: #666;
          padding: 4px 10px;
          border-left: 2px solid #666;
        "
      >
        {{ $t("common.PersonalInformation") }}
      </div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        style="
          position: absolute;
          left: 56%;
          top: 55%;
          transform: translate(-55%, -50%);
        "
      >
        <el-form-item :label="$t('common.Nickname')" prop="userNickName">
          <el-input
            v-model="form.userNickName"
            maxlength="20"
            show-word-limit
            v-bind:disabled="this.isModifyNick"
          ></el-input>
          <div style="color: #666666">{{ $t("common.notice") }}</div>
        </el-form-item>

        <el-form-item :label="$t('common.RealName')" prop="name">
          <el-input
            v-model="form.name"
            maxlength="10"
            show-word-limit
          ></el-input>
        </el-form-item>

        <!-- <el-form-item :label="$t('common.ID')" prop="idNumber">
          <el-input
            v-model="form.idNumber"
            maxlength="18"
            show-word-limit
          ></el-input>
        </el-form-item> -->

        <el-form-item :label="$t('common.Gender')">
          <el-radio
            v-model="form.genderDict"
            v-for="item in genderDicts"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-form-item>
        <el-form-item :label="$t('common.DateOfBirth')" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            :placeholder="$t('common.SelectDate')"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('common.Nationality')">
          <el-select
            :placeholder="$t('common.PleaseSelectNationality')"
            v-model="form.nationalityDict"
            style="width: 75%"
          >
            <el-option
              v-for="item in nationalityDicts"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('common.Address')">
          <el-input
            v-model="form.postalAddress"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- <div style="height: 300px;position: relative;width: 100%;margin-top: 30px;">
        <div style="margin-left: 200px;font-size: 14px;font-weight: 700;color: #666;padding: 4px 10px;border-left: 2px solid #666;">社交信息</div>
        <el-form ref="form" :model="form" :rules="rules"  label-width="100px" class="demo-ruleForm" style="position: absolute;left: 56%;top: 58%;transform: translate(-55%,-50%);">
            <el-form-item label="手机号:"  prop="mobilePhone">
              <el-input v-model="form.mobilePhone" disabled></el-input>
              <span style="margin-left: 20px;color: #2c5589;" class="cursor" @click="dialogVisibles">{{isBindPhone}}</span>
            </el-form-item>
            <el-form-item label="微信号:">
                <el-input v-model="form.wechat" ></el-input>
              </el-form-item>
              <el-form-item label="QQ:">
                <el-input v-model="form.qq" ></el-input>
              </el-form-item>
              <el-form-item label="微博:">
                <el-input v-model="form.weibo" ></el-input>
              </el-form-item>
        </el-form>
    </div> -->
    <div style="height: 200px">
      <div v-if="this.isAuth == false" style="margin-top: 100px">
        <el-button type="primary" style="margin-left: 300px" @click="save()">{{
          $t("common.Save")
        }}</el-button>
        <el-button style="margin-left: 30px" @click="reset()">{{
          $t("common.Reset")
        }}</el-button>
      </div>
    </div>
    <div>
      <el-dialog
        :title="$t('common.ModifyPhoneNumber')"
        :visible.sync="dialogVisible"
        width="30%"
        height="50%"
      >
        <div style="height: 100px; 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.OriginalPhone')">
              <el-input v-model="tel.oldTel"></el-input>
            </el-form-item>
            <el-form-item :label="$t('common.VerificationCode')">
              <el-input v-model="tel.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 v-if="addTag">
      <userCenterAddTag
        v-bind:systemLabel="systemLabel"
        :mergeSelectedLabels="mergeSelectedLabels"
        @closeMain="closeMain"
      ></userCenterAddTag>
    </div>
  </div>
</template>
<script>
import { saveUserInfo } from "@/api/user";
import { findUserInfo } from "@/api/user";
import { getDicts } from "@/api/dict";
import Base from "@/views/base/Base";
import { formatDate } from "@/utils/formatUtils";
import userCenterAddTag from "./userCenterAddTag";
import { addIntegral, addGrowth } from "@/utils/toCompleteTask";
import { getUserPointPage } from "@/api/user";
export default {
  name: "userCenterPersonalInformation",
  extends: Base,
  components: {
    userCenterAddTag,
  },
  data() {
    return {
      isBindPhone: "",
      bindPhone: "",
      codeFromTel: "",
      show: true,
      count: "",
      timer: null,
      informationsClass: "1",
      dialogVisible: false,
      ifDiaslog: "",
      addTag: false,
      props: { multiple: true },
      isAuth: "",
      options: [
        {
          value: 1,
          label: "东南",
        },
        {
          value: 2,
          label: "西北",
        },
        {
          value: 3,
          label: "上下",
        },
        {
          value: 4,
          label: "左右",
        },
      ],
      systemLabel: [
        {
          label: "标签一",
          type: "",
        },
        {
          label: "标签二",
          type: "",
        },
      ],
      mergeSelectedLabels: [],
      isModifyNick: false,
      form: {
        userNickName: "",
        postalAddress: "",
        // idNumber: "",
        hobby: "",
        name: "",
        fullName: "",
        IDCode: "",
        gender: "",
        genderDict: "M",
        nationalityDict: "",
        birthday: "",
        tel: "",
        nationality: "",
        region: "",
        label: [],
        tag: "",
        interest: [],
        wechat: "",
        qq: "",
        micro_blog: "",
        weibo: "",
      },
      genderDicts: [],
      nationalityDicts: [],
      tel: {
        oldTel: "",
        passWord2: "",
      },
      rules: {},
      rulesZh: {
        name: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        nationalityDict: [
          { required: true, message: "请选择国籍", trigger: "blur" },
        ],
        // idNumber: [
        //   { required: false, message: "请输入身份证号", trigger: "blur" },
        //   {
        //     pattern:
        //       /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/,
        //     message: this.$t("common.PleaseEnterYourLegalIDNumber"),
        //     trigger: "blur",
        //   },
        // ],
        genderDict: [
          { required: true, message: "请选择性别", trigger: "change" },
        ],
        birthday: [
          { required: false, message: "请选择出生日期", trigger: "blur" },
        ],
        postalAddress: [
          { required: false, message: "请输入地区", trigger: "blur" },
        ],
      },
      rulesEn: {
        name: [
          {
            required: true,
            message: "Please enter your real name",
            trigger: "blur",
          },
          {
            min: 3,
            max: 20,
            message: "The length is between 3 and 20 characters",
            trigger: "blur",
          },
        ],
        nationalityDict: [
          {
            required: true,
            message: "Please select nationality",
            trigger: "blur",
          },
        ],
        // idNumber: [
        //   {
        //     required: false,
        //     message: "Please enter ID number",
        //     trigger: "blur",
        //   },
        //   {
        //     pattern:
        //       /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/,
        //     message: this.$t("common.PleaseEnterYourLegalIDNumber"),
        //     trigger: "blur",
        //   },
        // ],
        genderDict: [
          {
            required: true,
            message: "Please select gender",
            trigger: "change",
          },
        ],
        birthday: [
          {
            required: false,
            message: "Please select the date of birth",
            trigger: "blur",
          },
        ],
        postalAddress: [
          { required: false, message: "Please enter region", trigger: "blur" },
        ],
      },
      user: {
        umsUser: {},
      },
      pointStatus: null,
    };
  },
  mounted() {
    this.userInfo();
    this.isBindOrModify();
  },
  watch: {
    "$i18n.locale"() {
      this.userInfo();
      this.isBindOrModify();
    },
  },
  computed: {
    genderMap: function () {
      return this.genderDicts.array2Obj("value", "label");
    },
    nationalityMap: function () {
      return this.nationalityDicts.array2Obj("value", "label");
    },
  },
  methods: {
    addTagChange() {
      this.addTag = true;
    },
    closeMain(val) {
      this.mergeSelectedLabels = val;
      console.log(this.mergeSelectedLabels);
      this.addTag = false;
    },
    userInfo() {
      getUserPointPage().then((res) => {
        this.pointStatus = res.data.umsUserPoints[0].pointStatus;
      });
      if (this.$i18n.locale.toUpperCase() == "EN") {
        getDicts("GENDER_DICT_EN,UNIT_COUNTRY_DICT_EN").then((result) => {
          var data = result.data;
          if (data) {
            this.genderDicts = result.data["0"] || [];
            this.nationalityDicts = result.data["1"] || [];
          }
        });
      } else {
        getDicts("GENDER_DICT,UNIT_COUNTRY_DICT").then((result) => {
          var data = result.data;
          if (data) {
            this.genderDicts = result.data["0"] || [];
            this.nationalityDicts = result.data["1"] || [];
          }
        });
      }
      findUserInfo()
        .then((result) => {
          if (result.data) {
            this.form = result.data;
            if (result.data.realnameValidatedStatus == "y") {
              //已实名认证  信息不可进行修改
              this.isAuth = true;
            }
            if (result.msg == "false") {
              //将昵称输入框置灰
              this.isModifyNick = true;
            }
            console.log("this.form:", this.form);
            this.user.umsUser.userNickName = result.data.userNickName;
            var params = {
              realName: result.data.name,
              umsUser: this.user.umsUser,
              userId: this.user.userId,
              username: this.user.username,
            };
            window.localStorage.setItem("user", JSON.stringify(params));
          }
        })
        .catch((error) => {
          this.$message({
            message: error.msg,
            type: "error",
          });
        });
    },
    getInformation(num) {
      this.informationsClass = num;
    },
    async save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          var basePersonnelInfo = new Object();
          //如果昵称是置灰状态，就不需要修改昵称了
          if (this.isModifyNick == true) {
            basePersonnelInfo.userNickName = "";
          } else {
            basePersonnelInfo.userNickName = this.form.userNickName;
          }
          basePersonnelInfo.birthday = this.form.birthday
            ? formatDate(this.form.birthday, "YYYY-MM-DD HH:mm:ss")
            : "";
          basePersonnelInfo.id = this.form.id;
          basePersonnelInfo.postalAddress = this.form.postalAddress;
          basePersonnelInfo.nationalityDict = this.form.nationalityDict;
          basePersonnelInfo.genderDict = this.form.genderDict;
        //   basePersonnelInfo.idNumber = this.form.idNumber;
          basePersonnelInfo.name = this.form.name;
          basePersonnelInfo.nationality =
            this.nationalityMap[this.form.nationalityDict];
          basePersonnelInfo.gender = this.genderMap[this.form.genderDict];
          saveUserInfo(
            basePersonnelInfo.userNickName,
            JSON.stringify(basePersonnelInfo)
          )
            .then((result) => {
              if (
                this.user.umsUser.userUsertypeDict !== "2" &&
                this.pointStatus == "y"
              ) {
                addIntegral("point_task_complete_info", 20);
                addGrowth("point_task_complete_info");
              }
              if (result.status != 200) {
                if (this.$i18n.locale.toUpperCase() == "EN") {
                  return this.$message.error("Save failed！");
                } else {
                  return this.$message.error("保存失败！");
                }
              }
              if (this.$i18n.locale.toUpperCase() == "EN") {
                return this.$message.success("Saved successfully！");
              } else {
                return this.$message.success("保存成功！");
              }
            })
            .catch((error) => {
              this.$message({
                message: error.msg,
                type: "error",
              });
            });
        }
      });
    },
    //中国标准时间 转 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() {
      //跳转页面
      this.$router.push({
        name: this.bindPhone,
      });
    },
    isBindOrModify() {
      if (this.$i18n.locale.toUpperCase() == "EN") {
        this.rules = this.rulesEn;
      } else {
        this.rules = this.rulesZh;
      }
      console.log("this.rules");
      console.log(this.rules);
      var users = localStorage.getItem("user");
      var user = JSON.parse(users);
      var userPreferredMobile = user.umsUser.userPreferredMobile;
      if (!userPreferredMobile) {
        this.isBindPhone = "绑定手机";
        this.bindPhone = "securitySettingBindPhone";
      } else {
        this.isBindPhone = "修改手机";
        this.bindPhone = "securitySettingChangePhone";
      }
    },
    reset() {
      this.form.name = "";
    //   this.form.idNumber = "";
      this.form.nationalityDict = "";
      this.form.postalAddress = "";
      this.form.birthday = "";
      this.form.genderDict = "";
    },
  },
};
</script>
<style scoped>
.box1:after {
  display: block;
  clear: both;
  content: "";
  visibility: hidden;
  height: 0;
}
.el-input,
.el-cascader {
  width: 75%;
}
.el-form {
  width: 500px !important;
}
.el-button {
  width: 200px;
  height: 45px;
}
</style>
