<template>
  <el-form :model="form" :rules="rules" ref="form">
    <el-row>
      <el-col :span="12">
        <el-form-item :label="$t('hivuiMain_personalCenter_name')" prop="FUSERNAME">
          <el-input v-model="form.FUSERNAME"></el-input>
        </el-form-item>
        <el-form-item :label="$t('hivuiMain_personalCenter_sex')" prop="FSEX">
          <el-radio-group v-model="form.FSEX">
            <el-radio :label="1">{{ $t('hivuiMain_personalCenter_male') }}</el-radio>
            <el-radio :label="0">{{ $t('hivuiMain_personalCenter_female') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('hivuiMain_personalCenter_birthday')" prop="FBIRTHDAY">
          <el-date-picker
            format="yyyy-MM-dd"
            type="date"
            v-model="form.FBIRTHDAY"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('hivuiMain_personalCenter_mbphone')" prop="FMBPHONE">
          <el-input v-model="form.FMBPHONE"></el-input>
        </el-form-item>
        <el-form-item :label="$t('hivuiMain_personalCenter_email')" prop="FEMAIL">
          <el-input v-model="form.FEMAIL"></el-input>
        </el-form-item>
        <el-form-item label="QQ" prop="FQQ">
          <el-input v-model="form.FQQ"></el-input>
        </el-form-item>
        <el-form-item :label="$t('hivuiMain_personalCenter_WeChat')" prop="FWEIXIN">
          <el-input v-model="form.FWEIXIN"></el-input>
        </el-form-item>
        <el-form-item :label="$t('hivuiMain_personalCenter_usersfz')" prop="FUSERSFZ">
          <el-input v-model="form.FUSERSFZ"></el-input>
        </el-form-item>
        <el-form-item :label="$t('hivuiMain_personalCenter_address')"  prop="FADDRESS">
          <el-input
            type="textarea"
            :rows="3"
            v-model="form.FADDRESS"
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12" style="padding-left: 20px">
        <el-form-item label="" prop="FUSERPHOTO">
          <el-upload
            class="avatar-uploader"
            :http-request="uploadUserPhoto"
            :show-file-list="false"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
          >
            <div class="showImg" v-if="userPhotoUrl">
              <img :src="userPhotoUrl" class="avatar user" />
              <span ref="showActions" class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click.stop="handlePreview(file, 'userPhoto')"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click.stop="handleRemove(file, 'userPhoto')"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon user"
              :style="`background-image:url(${userPic});background-size: 100% 100%`"
            ></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="" prop="FUSERSFZPIC1">
          <el-upload
            class="avatar-uploader"
            :http-request="uploadSfzPic1"
            :show-file-list="false"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
          >
            <div class="showImg" v-if="sfzPic1Url">
              <img :src="sfzPic1Url" class="avatar sfz" />
              <span ref="showActions" class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click.stop="handlePreview(file, 'sfzPic1')"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click.stop="handleRemove(file, 'sfzPic1')"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
            <div
              v-else
              class="avatar-uploader-icon sfz"
              :style="`background-image:url(${sfz1Pic});background-size: 100% 100%`"
            ></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="" prop="FUSERSFZPIC2">
          <el-upload
            class="avatar-uploader"
            :http-request="uploadSfzPic2"
            :show-file-list="false"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
          >
            <div class="showImg" v-if="sfzPic2Url">
              <img :src="sfzPic2Url" class="avatar sfz" />
              <span ref="showActions" class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click.stop="handlePreview(file, 'sfzPic2')"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click.stop="handleRemove(file, 'sfzPic2')"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
            <div
              v-else
              class="avatar-uploader-icon sfz"
              :style="`background-image:url(${sfz2Pic});background-size: 100% 100%`"
            ></div>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item style="text-align: center">
      <el-button type="primary" @click="submitForm('form')">{{
        $t("hivuiMain_des_save")
      }}</el-button>
      <!-- <el-button @click="resetForm('form')">{{ $t("hivuiMain_des_cancel")}}</el-button> -->
    </el-form-item>
    <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible" ref="dialog">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </el-form>
</template>

<script>
import { update, upload } from "@main/api/user.js";
import { getToken } from "@main/utils/auth";
import userPic from "@main/assets/user.png";
import sfz1Pic from "@main/assets/sfz1.jpg";
import sfz2Pic from "@main/assets/sfz2.jpg";
export default {
  data() {
    return {
      form: {
        FUSERNAME: "",
        FSEX: "",
        FBIRTHDAY: "",
        FMBPHONE: "",
        FEMAIL: "",
        FQQ: "",
        FWEIXIN: "",
        FUSERSFZ: "",
        FADDRESS: [],
        FUSERPHOTO: "",
        FUSERSFZPIC1: "",
        FUSERSFZPIC2: "",
      },
      // userPhotoUrl: '',
      // sfzPic1Url: '',
      // sfzPic2Url: '',
      rules: {
        FMBPHONE: [
          {
            validator: this.isPhone,
            trigger: "blur",
          },
        ],
        FEMAIL: [
          {
            validator: this.isEmail,
            trigger: "blur",
          },
        ],
        FUSERSFZ: [
          {
            validator: this.isIdCard,
            trigger: "blur",
          },
        ],
      },
      dialogVisible: false,
      dialogImageUrl: "",
      userPic: userPic,
      sfz1Pic: sfz1Pic,
      sfz2Pic: sfz2Pic,
      copyForm:{}
    };
  },
  computed: {
    userPhotoUrl() {
      if (this.form && this.form.FUSERPHOTO) {
        return this._getImageUrl(this.form.FUSERPHOTO);
      } else {
        return "";
      }
    },
    sfzPic1Url() {
      if (this.form && this.form.FUSERSFZPIC1) {
        return this._getImageUrl(this.form.FUSERSFZPIC1);
      } else {
        return "";
      }
    },
    sfzPic2Url() {
      if (this.form && this.form.FUSERSFZPIC2) {
        return this._getImageUrl(this.form.FUSERSFZPIC2);
      } else {
        return "";
      }
    },
    reviewUrl(){
      return this.$HI.review.includes(window.HIVUI_SETTING.url) ? this.$HI.review : window.HIVUI_SETTING.url + this.$HI.review
    }
  },
  mounted() {},
  methods: {
    uploadUserPhoto(param) {
      this.handleUpload(param, "userPhoto");
    },
    uploadSfzPic1(param) {
      this.handleUpload(param, "sfzPic1");
    },
    uploadSfzPic2(param) {
      this.handleUpload(param, "sfzPic2");
    },
    /* 手动上传附件 */
    handleUpload(param, type) {
      let formData = new FormData();
      formData.append("files", param.file);
      let _this = this;
      upload(formData).then((res) => {
        if (type == "userPhoto") {
          let path = res.dataPack[0].nname;
          _this.form.FUSERPHOTO = path;
          // _this.userPhotoUrl = _this._getImageUrl(path);
        } else if (type == "sfzPic1") {
          let path = res.dataPack[0].nname;
          _this.form.FUSERSFZPIC1 = path;
          // _this.sfzPic1Url = _this._getImageUrl(path);
        } else if (type == "sfzPic2") {
          let path = res.dataPack[0].nname;
          _this.form.FUSERSFZPIC2 = path;
          // _this.sfzPic2Url = _this._getImageUrl(path);
        }
      });
    },
    _getImageUrl(path) {
      let token = getToken();
      if (typeof path == "string") {
        path = path.replace(/\\/g, "/");
        if(path.includes(";") && path.split(";").length >= 2){
          path = path.split(";")[2];
        }
      }
      return `${this.reviewUrl}?relativePath=${path}&access_token=${token}`;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = { ...this.form };
          if (form.FBIRTHDAY && typeof form.FBIRTHDAY == "object") {
            form.FBIRTHDAY = this.formatDate(form.FBIRTHDAY);
          }else{
            form.FBIRTHDAY = null
          }
          let data = this.getEditData()
          data.$old = { ...form };
          data.$m = "/platf/user-info/entity/SysUserInfoBizEntity.xml";
          update(data).then((res) => {
            this.$message({
              type: "success",
              message: this.$t("hivuiMain_personalCenter_editTips") || "修改成功",
            });
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // resetForm(formName) {
    //   this.$refs[formName].resetFields();
    // },
    isPhone(rule, value, callback) {
      const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (value == "" || value == undefined || value == null) {
        callback();
      } else {
        if (!reg.test(value) && value != "") {
          callback(
            new Error(
              this.$t("hivuiMain_validate_FMBPHONE") || "电话号码格式有误"
            )
          );
        } else {
          callback();
        }
      }
    },
    isEmail(rule, value, callback) {
      const reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
      if (value == "" || value == undefined || value == null) {
        callback();
      } else {
        if (!reg.test(value)) {
          callback(
            new Error(
              this.$t("hivuiMain_validate_FEMAIL") || "邮箱地址格式有误"
            )
          );
        } else {
          callback();
        }
      }
    },
    isIdCard(rule, value, callback) {
      const reg =
        /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      if (value == "" || value == undefined || value == null) {
        callback();
      } else {
        if (!reg.test(value)) {
          callback(
            new Error(
              this.$t("hivuiMain_validate_FIDCARD") || "身份证号格式有误"
            )
          );
        } else {
          callback();
        }
      }
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    handlePreview(file, type) {
      this.dialogImageUrl =
        type == "userPhoto"
          ? this.userPhotoUrl
          : type == "sfzPic1"
          ? this.sfzPic1Url
          : type == "sfzPic2"
          ? this.sfzPic2Url
          : "";
      this.dialogVisible = true;
      let dialog = this.$refs.dialog;
      dialog.$el.onclick = function () {
        event.stopPropagation();
      };
    },
    handleRemove(file, type) {
      if (type == "userPhoto") {
        this.form.FUSERPHOTO = "";
      } else if (type == "sfzPic1") {
        this.form.FUSERSFZPIC1 = "";
      } else if (type == "sfzPic2") {
        this.form.FUSERSFZPIC2 = "";
      }
    },
    getEditData(){
      let data = {}
      for(let key in this.form){
        if(this.form[key] !== this.copyForm[key]){
          data[key] = this.form[key]
        }
      }
      return data
    }
  },
};
</script>

<style lang="less" scope>
.avatar-uploader .el-upload {
  border: 1px dashed transparent;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon.user {
  font-size: 28px;
  color: #8c939d;
  width: 166px;
  height: 166px;
  line-height: 166px;
  text-align: center;
}
.avatar-uploader-icon.sfz {
  font-size: 28px;
  color: #8c939d;
  width: 318px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.avatar.user {
  width: 166px;
  height: 166px;
  display: block;
}
.avatar.sfz {
  width: 318px;
  height: 200px;
  display: block;
}
.el-upload-list__item-actions {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  cursor: default;
  text-align: center;
  color: #fff;
  opacity: 0;
  font-size: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  transition: opacity 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}
.showImg:hover {
  .el-upload-list__item-actions {
    opacity: 1;
  }
}
.el-upload-list__item-delete {
  display: block;
  position: static;
  font-size: inherit;
  color: inherit;
  .el-icon-delete {
    font-family: element-icons !important;
    speak: none;
    font-style: normal;
    font-weight: 400;
    font-variant: normal;
    text-transform: none;
    line-height: 1;
    vertical-align: baseline;
    display: inline-block;
    -webkit-font-smoothing: antialiased;
  }
}
.el-upload-list__item-actions span + span {
  margin-left: 15px;
}
.el-upload-list__item-name i:hover,
.el-upload-list__item-name a:hover {
  color: #409eff;
}
.el-radio--mini.is-bordered{
  display: block;
  width: fit-content;
  margin-bottom: 10px;
}
.el-radio.is-bordered+.el-radio.is-bordered{
  margin-left: 0;
}
</style>
