<template>
  <div
    style="width: 100%; background: #fff; min-height: 700px"
    class="userCenterAuthenticationPersonal"
  >
    <div
      style="
        height: 80px;
        line-height: 80px;
        margin-top: 20px;
        margin: 0 20px;
        color: #666;
        font-size: 15px;
        border-bottom: 1px solid #bcbcbc;
      "
    >
      {{ $t("common.realAuthentication") }}({{
        this.realnameStatus[this.realnameAuthenticationPersonal]
      }})
      <!-- <span style="float: right;margin-top: 27px;"> <i class="el-icon-edit"></i> 修改</span> -->
    </div>

    <div style="width: 600px" v-if="realnameAuthenticationPersonal == '0'">
      <el-form
        ref="form"
        :rules="formRules"
        :model="form"
        label-width="160px"
        class="demo-ruleForm"
        style="margin-left: 100px; margin-top: 20px; width: 700px"
      >
        <el-form-item :label="$t('common.realName')" prop="name">
          <el-input
            :placeholder="$t('common.namePlaceholder')"
            v-model="form.name"
            style="width: 70%"
            maxlength="10"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.nationality')" prop="nationalityDict">
          <el-select
            :placeholder="$t('common.nationalityPlaceholder')"
            v-model="form.nationalityDict"
            style="width: 70%"
          >
            <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.idType')" prop="idTypeDict">
          <el-select
            :placeholder="$t('common.idTypePlaceholder')"
            v-model="form.idTypeDict"
            style="width: 70%"
            :no-data-text="$i18n.locale == 'zh' ? '无数据' : 'no data'"
          >
            <el-option
              v-for="item in userIdCardTypes"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.idTypeDict == 0 && form.idTypeDict != ''"
          :label="$t('common.idNumber')"
          prop="idNumber"
          key="formIdNumber1"
        >
          <el-input
            :placeholder="$t('common.idNumberPlaceholder')"
            v-model="form.idNumber"
            style="width: 70%"
            maxlength="18"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item v-else :label="$t('common.idNumber')" key="formIdNumber2">
          <el-input
            :placeholder="$t('common.idNumberPlaceholder')"
            v-model="form.idNumber"
            style="width: 70%"
            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-radio v-model="form.gender" label="F">女</el-radio>-->
        </el-form-item>
        <el-form-item
          :label="$t('common.idNumberFrontPhoto')"
          style="position: relative"
          prop="idNumberFrontPhoto"
        >
          <el-upload
            class="avatar-uploader"
            action="/api/file/upload/img?module=authenticationPersonal"
            :show-file-list="false"
            :on-success="frontHandleAvatarSuccess"
            :headers="myHeaders"
            :before-upload="beforeAvatarUpload1"
          >
            <img
              v-if="form.idNumberFrontPhoto"
              :src="'/api/file/pub/' + form.idNumberFrontPhoto"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div
            style="
              position: absolute;
              left: 230px;
              top: 0;
              font-size: 12px;
              color: #666;
              line-height: 22px;
            "
          >
            {{ $t("common.frontPhotoRemark1")
            }}<span style="color: #ff8400">{{
              $t("common.frontPhotoRemark2")
            }}</span>
            {{ $t("common.frontPhotoRemark3") }}
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('common.idNumberReversePhoto')"
          style="position: relative"
          prop="idNumberReversePhoto"
        >
          <el-upload
            class="avatar-uploader"
            action="/api/file/upload/img?module=authenticationPersonal"
            :show-file-list="false"
            :headers="myHeaders"
            :on-success="reverseHandleAvatarSuccess"
            :before-upload="beforeAvatarUpload2"
          >
            <img
              v-if="form.idNumberReversePhoto"
              :src="'/api/file/pub/' + form.idNumberReversePhoto"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!--                    <div style="position: absolute;left: 230px;top: 0;font-size: 12px;color: #666;line-height: 22px;">{{$t('common.reversePhotoRemark')}}</div>-->
        </el-form-item>

        <el-form-item :label="$t('common.idNumberEndTime')">
          <el-date-picker
            v-model="form.idNumberEndTime"
            type="date"
            style="width: 70%"
            :placeholder="$t('common.idNumberEndTimePlaceholder')"
          >
          </el-date-picker>
          <el-radio
            v-model="form.idNumberTerm"
            label="1"
            style="margin-left: 30px"
            >{{ $t("common.idNumberTerm") }}</el-radio
          >
        </el-form-item>
      </el-form>
    </div>
    <div
      v-if="realnameAuthenticationPersonal == '1'"
      style="margin-top: 122px; margin-left: 273px; height: 200px"
    >
      <img
        src="@/assets/img/userCenter/u55899.png"
        alt=""
        style="vertical-align: top; float: left"
      />
      <span
        style="float: left; margin-top: 40px; line-height: 30px; color: #666"
      >
        <div style="font-size: 18px; font-weight: 700">
          {{ $t("common.authenticationYes") }}
        </div>
        <div>{{ $t("common.realName") }} {{ this.username }}</div>
        <div>{{ $t("common.idNumber") }} {{ this.number }}</div>
      </span>
    </div>
    <div
      v-if="realnameAuthenticationPersonal == '2'"
      style="margin-top: 122px; margin-left: 273px; height: 200px"
    >
      <img
        src="@/assets/img/userCenter/u55899.png"
        alt=""
        style="vertical-align: top; float: left"
      />
      <span
        style="float: left; margin-top: 40px; line-height: 30px; color: #666"
      >
        <div style="font-size: 18px; font-weight: 700">
          {{ $t("common.underReview") }}
        </div>
      </span>
    </div>
    <div
      v-if="realnameAuthenticationPersonal == '3'"
      style="margin-top: 122px; margin-left: 273px; height: 200px"
    >
      <img
        src="@/assets/img/userCenter/u55899.png"
        alt=""
        style="vertical-align: top; float: left"
      />
      <span
        style="float: left; margin-top: 40px; line-height: 30px; color: #666"
      >
        <div style="font-size: 18px; font-weight: 700">
          {{ $t("common.auditFailed") }}：{{
            this.form.realnameValidatedProposal
          }}
        </div>
      </span>
    </div>
    <div style="height: 200px">
      <div style="margin-top: 100px">
        <el-button
          type="warning"
          style="margin-left: 300px"
          @click="goAithentication"
          v-if="realnameAuthenticationPersonal == '0'"
          >{{ $t("common.back") }}</el-button
        >
        <el-button
          type="warning"
          style="margin-left: 300px"
          @click="goAithentication2"
          v-if="realnameAuthenticationPersonal == '3'"
          >{{ $t("common.modifyAuthentication") }}</el-button
        >
        <el-button
          type="primary"
          style="margin-left: 30px"
          @click="submitAithentication"
          v-if="realnameAuthenticationPersonal == '0'"
          >{{ $t("common.submitAuthentication") }}</el-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import {
  submitAuthenticationPersonal,
  getAuthenticationStatus,
} from "@/api/userCenter/authenticationPersonal.js";
import { getToken } from "@/utils/auth";
import { formatDate } from "@/utils/formatUtils";
import { getDicts } from "@/api/dict";
import Base from "@/views/base/Base";
import { addIntegral } from "@/utils/toCompleteTask";
export default {
  name: "userCenterAuthenticationPersonal",
  extends: Base,
  data() {
    return {
      informationsClass: "1",
      dialogVisible: false,
      realnameAuthenticationPersonal: "",
      ifDiaslog: "",
      title: "",
      personnelAuthenticationInfo: "",
      myHeaders: { Authorization: "Bearer " + getToken() },
      number: "",
      username: "",
      personnelId: "",
      form: {
        name: "",
        idTypeDict: "",
        idNumber: "",
        genderDict: "M",
        nationalityDict: "",
        idNumberEndTime: "",
        idNumberTerm: "",
        idNumberFrontPhoto: "",
        idNumberReversePhoto: "",
        realnameValidatedProposal: "",
      },
      personnelAuthenticationInfo: {},
      genderDicts: [],
      nationalityDicts: [],
      nationDicts: [],
      userIdCardTypes: [],
      realnameStatus: {
        0: this.$t("common.NotCertified"),
        1: this.$t("common.Certified"),
        2: this.$t("common.UnderReview"),
        3: this.$t("common.Failed"),
      },
      user: {
        umsUser: {},
      },
    };
  },
  watch: {
    "$i18n.locale"() {
      this.initData();
      this.realnameStatus = {
        0: this.$t("common.NotCertified"),
        1: this.$t("common.Certified"),
        2: this.$t("common.UnderReview"),
        3: this.$t("common.Failed"),
      };
    },
  },
  mounted() {
    this.initData();
  },
  computed: {
    userIdCardTypesMap: function () {
      return this.userIdCardTypes.array2Obj("value", "label");
    },
    genderMap: function () {
      return this.genderDicts.array2Obj("value", "label");
    },
    nationalityMap: function () {
      return this.nationalityDicts.array2Obj("value", "label");
    },
    formRules() {
      return {
        name: [
          {
            required: true,
            message: this.$t("common.namePlaceholder"),
            trigger: "blur",
          },
        ],
        nationalityDict: [
          {
            required: true,
            message: this.$t("common.nationalityPlaceholder"),
            trigger: "blur",
          },
        ],
        idTypeDict: [
          {
            required: true,
            message: this.$t("common.idTypePlaceholder"),
            trigger: "blur",
          },
        ],
        idNumber: [
          {
            required: true,
            message: this.$t("common.idNumberPlaceholder"),
            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",
          },
        ],
        idNumberFrontPhoto: [
          {
            required: true,
            message: this.$t("common.frontPhotoPlaceholder"),
            trigger: "blur",
          },
        ],
        idNumberReversePhoto: [
          {
            required: true,
            message: this.$t("common.reversePhotoPlaceholder"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  methods: {
    initData() {
      this.user = JSON.parse(window.localStorage.getItem("user"));
      //查询用户是否认证
      var user = localStorage.getItem("user");
      var userInfo = JSON.parse(user);
      this.personnelId = userInfo.umsUser.personnelId;
      getAuthenticationStatus(this.personnelId)
        .then((result) => {
          var data = result.data;
          console.log(data);
          if (data == "" || data == undefined) {
            this.realnameAuthenticationPersonal = "0";
            return;
          }
          if (data.realnameValidatedStatusDict == "04") {
            this.realnameAuthenticationPersonal = "1";
            this.number =
              data.idNumber.substr(0, 2) + "****" + data.idNumber.substr(14);
            this.username =
              data.name.substr(0, 1) + "***" + data.name.substr(3);
          } else if (data.realnameValidatedStatusDict == "02") {
            this.realnameAuthenticationPersonal = "2";
          } else if (data.realnameValidatedStatusDict == "03") {
            //认证不通过
            this.realnameAuthenticationPersonal = "3";
            this.form.realnameValidatedProposal =
              data.realnameValidatedProposal;
            this.personnelAuthenticationInfo = data;
          } else {
            this.realnameAuthenticationPersonal = "0";
          }
          // 认证通过
          window.localStorage.setItem(
            "realNameVerifyPassed",
            data.realnameValidatedStatusDict
          );
        })
        .catch((error) => {
          this.$message({
            message: error.msg,
            type: " error",
          });
          this.realnameAuthenticationPersonal = "0";
        });
      // getDicts('GENDER_DICT,NATIONALITY_DICT,NATION_DICT,USER_ID_CARD_TYPE').then(result => {
      getDicts(
        this.$i18n.locale.toUpperCase() == "ZH"
          ? "GENDER_DICT,UNIT_COUNTRY_DICT,NATION_DICT,USER_ID_CARD_TYPE"
          : "GENDER_DICT_EN,UNIT_COUNTRY_DICT_EN,NATION_DICT_EN,USER_ID_CARD_TYPE_EN"
      ).then((result) => {
        var data = result.data;
        if (data) {
          this.genderDicts = result.data["0"] || [];
          this.nationalityDicts = result.data["1"] || [];
          this.nationDicts = result.data["2"] || [];
          this.userIdCardTypes = result.data["3"] || [];
        }
      });
      //realnameAuthenticationPersonal
    },
    goAithentication(num) {
      this.$emit("aithentication", 1);
    },
    goAithentication2(num) {
      this.realnameAuthenticationPersonal = "0";
      this.form = this.personnelAuthenticationInfo;
    },
    frontHandleAvatarSuccess(res, file) {
      // this.frontImageUrl = URL.createObjectURL(res.data);
      this.form.idNumberFrontPhoto = res.data;
    },
    reverseHandleAvatarSuccess(res, file) {
      // this.from.idNumberReversePhoto = URL.createObjectURL(res.data);
      this.form.idNumberReversePhoto = res.data;
    },
    beforeAvatarUpload1(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;
    },
    beforeAvatarUpload2(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;
    },
    formRules() {
      return {
        /*unitName: [
                        {
                            required: true,
                            message: this.$t('common.PleaseEnter') + '  ' + this.$t('common.fullName'),
                            trigger: 'blur'
                        }
                    ]*/
      };
    },
    submitAithentication() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.print();
          if (this.user.umsUser.userUsertypeDict !== "2") {
            addIntegral("point_task_verified_name", "50");
          }
        } else {
          this.$notify.error({
            title: this.$t("common.errorInfo"),
            message: this.$t("common.Supplementary2"),
          });
          return false;
        }
      });
    },
    print() {
      this.submitHandler((token) => {
        //使用的审核字典  audit_status_dict  02待审核  04审核通过 03审核驳回
        this.personnelAuthenticationInfo = this.form;
        this.personnelAuthenticationInfo.idNumberEndTime = this.form
          .idNumberEndTime
          ? formatDate(this.form.idNumberEndTime, "YYYY-MM-DD HH:mm:ss")
          : "";
        this.personnelAuthenticationInfo.idType =
          this.userIdCardTypesMap[this.personnelAuthenticationInfo.idTypeDict];
        this.personnelAuthenticationInfo.nationality =
          this.nationalityMap[this.personnelAuthenticationInfo.nationalityDict];
        this.personnelAuthenticationInfo.gender =
          this.genderMap[this.personnelAuthenticationInfo.genderDict];
        this.personnelAuthenticationInfo.personnelId = this.personnelId;
        //待审核
        this.personnelAuthenticationInfo.realnameValidatedStatusDict = "02";
        this.personnelAuthenticationInfo.realnameValidatedStatus = "待审核";
        this.personnelAuthenticationInfo.language = this.$i18n.locale;
        submitAuthenticationPersonal(
          JSON.stringify(this.personnelAuthenticationInfo)
        )
          .then((result) => {
            if (result.status == 200 && result.data.length != 0) {
              this.$message({
                message: this.$t("common.successInfo"),
                type: "success",
              });
              // personnelAuthenticationInfo.id=result.data;
              //待审核
              this.realnameAuthenticationPersonal = "2";
            }
          })
          .catch((error) => {
            this.$message({
              message: error.msg,
              type: "error",
            });
          });
      });
    },
    /*  submitAithentication(){
                  //使用的审核字典  audit_status_dict  0未审核  1审核通过 2审核驳回
                  this.personnelAuthenticationInfo = this.form;
                /!*  this.personnelAuthenticationInfo.idNumberEndTime = this.form.idNumberEndTime
                      ? formatDate(this.form.idNumberEndTime, "YYYY-MM-DD HH:mm:ss")
                      : "";*!/
                  this.personnelAuthenticationInfo.idType=this.userIdCardTypesMap[this.personnelAuthenticationInfo.idTypeDict];
                  this.personnelAuthenticationInfo.nationality=this.nationalityMap[this.personnelAuthenticationInfo.nationalityDict];
                  this.personnelAuthenticationInfo.gender=this.genderMap[this.personnelAuthenticationInfo.genderDict];
                  this.personnelAuthenticationInfo.personnelId = this.personnelId;
                  //待审核
                  this.personnelAuthenticationInfo.realnameValidatedStatusDict ="0";
                  this.personnelAuthenticationInfo.realnameValidatedStatus="待审核";
                  submitAuthenticationPersonal(JSON.stringify(this.personnelAuthenticationInfo)).then((result) => {
                      if(result.status == 200 && result.data.length != 0){
                          this.$message({
                              message: "提交成功,请等待审核通过！",
                              type: 'success'
                          });
                          // personnelAuthenticationInfo.id=result.data;
                          //待审核
                          this.realnameAuthenticationPersonal = "2";
                      }
                  }).catch((error) => {
                      this.$message({
                          message: error.msg,
                          type: 'error'
                      });
                  })
              },*/
  },
};
</script>
<style scoped>
.el-button {
  width: 200px;
  height: 45px;
}
.authenticationBox1 {
  margin-left: 35px;
  margin-right: 150px;
  height: 100px;
  border: 1px solid rgba(153, 153, 153, 1);
  border-radius: 10px;
  margin-top: 50px;
  position: relative;
}
.authenticationBox2 {
  margin: 50px 150px 0 35px;
  height: 100px;
  border: 1px solid rgba(153, 153, 153, 1);
  border-radius: 10px;
  position: relative;
}
.authenticationBox1:hover,
.authenticationBox2:hover {
  border: 1px solid #ff8400;
}
.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;
}
.userCenterAuthenticationPersonal >>> .el-upload {
  border: 1px solid rgba(204, 204, 204, 1);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
