<template>
  <div class="app-container user-info" v-if="pageType">
    <div class="title-max-box">个人信息</div>
    <div class="user-max-box">
      <div class="left-user-box">
        <userAvatar :user="user" />
      </div>
      <div class="right-user-box">
        <div class="text-box">
          <p>用户名称：<span>{{user.nickName}}</span></p>
        </div>
        <div class="text-box">
          <p>联系方式：<span>{{user.phonenumber?user.phonenumber:'未填写'}}</span><span @click="phoneButton(1)">编辑</span></p>
        </div>
        <div class="text-box" v-if="user.dept">
          <p>学院：<span>{{user.dept.deptName}}</span></p>
        </div>
        <div class="text-box">
          <p>角色：<span>{{roleGroup}}</span></p>
        </div>
        <div class="text-box">
          <p>创建日期：<span>{{user.createTime}}</span></p>
        </div>
        <div class="text-box">
          <p>创建日期：<span>{{user.createTime}}</span></p>
        </div>
        <div>
          <div class="up-data-box">
            <div class="up-data-min-box" style="display: flex;">
              <p class="up-data-title">人脸照片：</p>
              <div class="up-data-button" v-if="!user.faceImg" @click="upFaceOpenClick(2)">
                <p>+</p>
                <p>上传</p>
              </div>
              <img class="img-one" :src="user.faceImg" v-if="user.faceImg" @click="upFaceOpenClick(2)">
            </div>
          </div>
          <div class="up-data-box">
            <div class="up-data-min-box" style="display: flex;">
              <p class="up-data-title">电子签名：</p>
              <el-upload
                class="position-button"
                :action="uploadImgUrlTwo"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="signatureChange"
                accept="image/jpeg,image/gif,image/png"
                :headers="headers"
                :before-upload="beforeAvatarUpload">
                <div class="up-data-button" v-if="!user.signature">
                  <p>+</p>
                  <p>上传</p>
                </div>
                <img class="img-two" :src="user.signature" v-if="user.signature">
              </el-upload>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="title-max-box">修改密码</div>
    <el-form class="pass-word-box" :model="form" ref="form" :rules="rules" >
      <el-form-item label="旧密码" prop="oldPassword" label-width="120px">
        <el-input type="password" v-model="form.oldPassword" placeholder="请输入旧密码"/>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword" label-width="120px">
        <el-input type="password" v-model="form.newPassword" placeholder="请输入新密码"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword" label-width="140px">
        <el-input type="password" v-model="form.confirmPassword" placeholder="请确认密码"/>
      </el-form-item>
      <p class="for-button-box inquire-button-one" @click="submit">修改</p>
    </el-form>
    <!--修改联系方式-->
    <el-dialog title="修改联系方式" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="phoneForm" :model="phoneForm" :rules="rules" label-width="80px">
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入联系方式" maxLength="11"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="phoneButton(2)">取 消</el-button>
        <el-button type="primary" @click="phoneButton(3)">确 定</el-button>
      </div>
    </el-dialog>
    <!--电子签名-->
    <el-dialog class="up-img-box" title="上传电子签名" :visible.sync="upImgOpen" width="600px" append-to-body>
      <p>示例</p>
      <img class="img-one" src="@/assets/ZDimages/icon_scdzqm_sl.png">
      <p>正楷签名</p>
      <div class="cropper-box">
        <vueCropper
          ref="cropper"
          :img="option.img"
          :outputSize="option.outputSize"
          :outputType="option.outputType"
          :info="option.info"
          :canScale="option.canScale"
          :autoCrop="option.autoCrop"
          :autoCropWidth="option.autoCropWidth"
          :autoCropHeight="option.autoCropHeight"
          :fixed="option.fixed"
          :fixedNumber="option.fixedNumber"
          :full="option.full"
          :fixedBox="option.fixedBox"
          :canMove="option.canMove"
          :canMoveBox="option.canMoveBox"
          :original="option.original"
          :centerBox="option.centerBox"
          :height="option.height"
          :infoTrue="option.infoTrue"
          :maxImgSize="option.maxImgSize"
          :enlarge="option.enlarge"
          :mode="option.mode"
          @realTime="realTime"
          @imgLoad="imgLoad"
        ></vueCropper>
        <p class="cropper-button" @click="upImgButton">保存查看</p>
        <el-upload
          class="position-button"
          :action="uploadImgUrl"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="signatureChange"
          accept="image/jpeg,image/gif,image/png"
          :headers="headers"
          :before-upload="beforeAvatarUpload">
          <p style="position: absolute;right:100px;top:10px;z-index:1;color:#fff;background:#14AE10;cursor: pointer;padding:5px 10px;margin:0;border-radius:6px;">选择签名</p>
        </el-upload>
      </div>
      <p style="color:#999;">请将签名置于选择框内以便提高识别度</p>
      <img class="cropper-img" v-if="signatureData" :src="signatureData">
      <div slot="footer" class="dialog-footer">
        <el-button @click="upImgOpenClick(1)">取 消</el-button>
        <el-button type="primary" @click="upSignatureData">确 定</el-button>
      </div>
    </el-dialog>
    <!--上传照片-->
    <el-dialog class="up-img-box" title="上传照片" :visible.sync="upFaceOpen" width="600px" append-to-body>
      <el-upload
        ref="faceUpLoad"
        class="position-button"
        :action="uploadImgUrl"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="faceChange"
        accept="image/jpeg,image/gif,image/png"
        :on-success="(res)=>handleAvatarSuccess(res)"
        :headers="headers"
        :before-upload="beforeAvatarUpload">
        <div v-if="!upFaceUrl" style="width:300px;height:300px;border: 1px dashed #E0E0E0;cursor: pointer;margin:20px 130px 0;">
          <p style="text-align: center;color:#999;font-weight:500;font-size: 20px;line-height:300px;margin:0;">+</p>
        </div>
        <img :src="upFaceUrl" v-if="upFaceUrl" style="width:300px;height:300px;border: 1px dashed #E0E0E0;cursor: pointer;margin:20px 130px 0;">
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="faceButton(1)">取 消</el-button>
        <el-button type="primary" @click="faceButton(2)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userAvatar from "./userAvatar";
import userInfo from "./userInfo";
import resetPwd from "./resetPwd";
import { getUserProfile,updateUserPwd,changePhone,genSign,updateSignature } from "@/api/system/user";
import { getToken } from "@/utils/auth";

export default {
  name: "Profile",
  components: {
    userAvatar,
    userInfo,
    resetPwd,
  },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.form.newPassword !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      uploadImgUrl: window.location.href.split('://')[0]+'://' + process.env.VUE_APP_BASE_API + "/laboratory/studentinfo/commit/face", // 上传的图片服务器地址
      uploadImgUrlTwo: this.uploadUrl(), // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      pageType:false,
      user: {},
      roleGroup: {},
      postGroup: {},
      activeTab: "resetPwd",
      form:{
        oldPassword:"",
        newPassword:"",
        confirmPassword:""
      },
      open:false,
      phoneForm:{
        phone:"",
      },
      // 表单校验
      rules: {
        oldPassword: [
          { required: true, message: "旧密码不能为空", trigger: "blur" },
          { required: true, message: "旧密码不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
          { required: true, message: "新密码不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" },
          { required: true, message: "确认密码不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入11位联系方式", trigger: "blur" },
          { validator: this.checkPhone, trigger: 'blur' },
          { min: 11, max: 11, message: "请输入11位联系方式", trigger: "blur" },
          { required: true, message: "请输入11位联系方式", validator: this.spaceJudgment, trigger: "blur" }
        ],
      },
      //上传签名开关
      upImgOpen:false,
      option:{
        img: '', // 裁剪图片的地址
        outputSize: 1,       //裁剪生成图片的质量(可选0.1 - 1)
        outputType: 'png',  //裁剪生成图片的格式（jpeg || png || webp）
        info: true,          //图片大小信息
        canScale: true,      //图片是否允许滚轮缩放
        autoCrop: true,      //是否默认生成截图框
        autoCropWidth: 240,  //默认生成截图框宽度
        autoCropHeight: 80, //默认生成截图框高度
        fixed: true,         //是否开启截图框宽高固定比例
        fixedNumber: [3, 1], //截图框的宽高比例
        full: false,         //false按原比例裁切图片，不失真
        fixedBox: true,      //固定截图框大小，不允许改变
        canMove: false,      //上传图片是否可以移动
        canMoveBox: true,    //截图框能否拖动
        original: false,     //上传图片按照原始比例渲染
        centerBox: false,    //截图框是否被限制在图片里面
        height: true,        //是否按照设备的dpr 输出等比例图片
        infoTrue: false,     //true为展示真实输出图片宽高，false展示看到的截图框宽高
        maxImgSize: 3000,    //限制图片最大宽度和高度
        enlarge: 1,          //图片根据截图框输出比例倍数
        mode: '560px 400px'  //图片默认渲染方式
      },
      previews:{},
      //上传人脸
      upFaceOpen:false,
      upFaceUrl:"",
      //临时签名数据
      signatureData:"",
    };
  },
  created() {
    this.getUser();
  },
  methods: {
    //上传签名
    upSignatureData(){
      if(!this.signatureData){
        this.msgError('请先选择签名上传并保存查看')
      }
      var blob = this.dataURLtoBlob(this.signatureData);
      var file = this.blobToFile(blob, 'dx.jpg');
      let formData = new FormData();
      formData.append('file',file,"DX.jpg")
      console.log("formData",formData);
      updateSignature(formData).then(response => {
        if(response.code == 200){
          this.msgSuccess("操作成功");
          this.upImgOpen = false;
          this.getUser();
        }
      });
    },
    //照片页面开关
    upFaceOpenClick(type){
      if(type == 1){
        this.upFaceOpen = false;
      }else if (type == 2){
        this.upFaceUrl = this.user.faceImg;
        this.upFaceOpen = true;
      }
    },
    //签名页面开关
    upImgOpenClick(type){
      if(type == 1){
        this.upImgOpen = false;
      }else if (type == 2){
        this.option.img = this.user.signature;
        this.signatureData = this.user.signature;
        this.upImgOpen = true;
      }
    },
    //确定签名
    upImgButton(){
      let self = this;
      this.$refs.cropper.getCropBlob(async (data) => {
        const file = new File([data], 'userImg.jpg', { type: 'image/jpeg', lastModified: Date.now() });
        let formData = new FormData();
        formData.append('file',file,"DX.jpg")
        genSign(formData).then(response => {
          if(response.code == 200){
            this.signatureData = 'data:image/png;base64,'+response.data;
          } else {
            this.msgError(response.msg)
          }
        });
      })
    },
    //照片选择
    faceChange(val){
      const windowURL = window.URL || window.webkitURL;
      this.upFaceUrl = windowURL.createObjectURL(val.raw)
    },
    //签名选择
    signatureChange(val){
      const windowURL = window.URL || window.webkitURL;
      this.option.img = windowURL.createObjectURL(val.raw)
      this.signatureData = "";
      this.upImgOpen = true;
    },
    // 照片上传按钮
    faceButton(type){
      if(type==1){
        this.upFaceOpen = false;
      }else if(type == 2){
        this.$refs.faceUpLoad.submit();
      }
    },
    //上传
    handleAvatarSuccess(res, type) {
      if(res.code == 200){
        this.user.faceImg = res.data.cardUrl;
        this.upFaceOpen = false;
        this.msgSuccess(res.msg)
        this.$forceUpdate()
      }else{
        this.msgError(res.msg)
      }
    },
    beforeAvatarUpload(file) {
      let type = false;
      if (file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') {
        type = true;
      }else{
        this.$message.error('只能上传png/jpeg/gif格式图片');
        type = false;
      }
      return type;
    },
    // 实时预览函数
    realTime(data) {
      this.previews = data;
    },
    //图片加载的回调 imgLoad 返回结果success, error
    imgLoad (msg) {
      // console.log('imgLoad')
      // console.log(msg)
    },
    //修改联系方式按钮
    phoneButton(type){
      let self = this;
      if(this.phoneType != type){
        if(type == 1){
          this.$set(this.phoneForm,'phone',this.user.phonenumber);
          this.open = true;
        }else if(type == 2){
          this.$set(this.phoneForm,'phone',"");
          this.open = false;
        }else if(type == 3){
          self.$refs["phoneForm"].validate(valid => {
            if (valid) {
              this.$confirm('确定要修改吗', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(function() {
                self.upPhoneData();
              }).then(() => {
              }).catch(() => {});
            }
          });
        }
      }
    },
    //手机修改接口
    upPhoneData(){
      changePhone({phonenumber:this.phoneForm.phone}).then(response => {
        this.$set(this.phoneForm,'phone',"");
        this.open = false;
        this.getUser();
        this.msgSuccess("修改成功")
      });
    },
    //手机号验证
    checkPhone(rule, value, callback) {
      if (!value) {
        return callback(new Error('不能为空'))
      } else {
        const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的联系方式'))
        }
      }
    },
    //修改按钮密码
    submit() {
      let self = this;
      self.$refs["form"].validate(valid => {
        if (valid) {
          this.$confirm('确定要修改吗', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            self.updateUserPwd();
          }).then(() => {
          }).catch(() => {});
        }
      });
    },
    //修改密码接口
    updateUserPwd(){
      updateUserPwd(this.form.oldPassword, this.form.newPassword).then(
        response => {
          this.form.oldPassword = "";
          this.form.newPassword = "";
          this.form.confirmPassword = "";
          this.msgSuccess("修改成功");
        }
      );
    },
    //获取信息
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
        this.pageType = true;
      });
    },
    //将base64转换为blob
    dataURLtoBlob: function(dataurl) {
      var  arr = dataurl.split(',')
      var  mime = arr[0].match(/:(.*?);/)[1]
      var  bstr = atob(arr[1])
      var  n = bstr.length
      var  u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    //将blob转换为file
    blobToFile: function(theBlob, fileName){
      theBlob.lastModifiedDate = new Date();
      theBlob.name = fileName;
      return theBlob;
    },
}
};
</script>
<style lang="scss" scoped>
  .user-info{
    display: flex!important;
    flex-direction: column;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
    padding:0 20px 15px!important;
    *{
      margin:0;
      padding:0;
    }
    .title-max-box{
      font-size:18px;
      color:#0045AF;
      line-height:80px;
      border-bottom:1px solid #E0E0E0;
    }
    .user-max-box{
      display: flex;
      .left-user-box{

      }
      .right-user-box{
        padding-top:42px;
        .text-box{
          display: inline-block;
          width:380px;
          height:20px;
          line-height:20px;
          margin-bottom:30px;
          p:nth-child(1){
            font-size:15px;
            color:#333;
            span{
              color:#999;
            }
            span:nth-child(2){
              margin-left:70px;
              font-size:15px;
              color:#0045AF;
              cursor: pointer;
            }
          }
        }
        .up-data-box{
          display: inline-block;
          width:380px;
          line-height:20px;
          margin-bottom:30px;
          .up-data-min-box{
            .up-data-title{
              font-size:15px;
              color:#333;
            }
            .up-data-button{
              width:120px;
              height:120px;
              border: 1px dashed #E0E0E0;
              cursor: pointer;
              p{
                text-align: center;
                color:#999;
                font-weight:500;
              }
              p:nth-child(1){
                font-size: 20px;
                line-height:40px;
                margin-top:20px;
              }
              p:nth-child(2){
                font-size: 16px;

              }
            }
            .img-one{
              width:120px;
              height:120px;
            }
            .img-two{
              width: 240px;
              height:80px;
            }
          }
        }
      }
    }
    .pass-word-box{
      display: flex;
      padding:30px 0;
      .for-button-box{
        margin-left:50px;
        font-size:14px;
      }
    }
    .svg-icon{
      margin-right:10px;
    }
  }
</style>
<style lang="scss">
  .up-img-box{
    .el-dialog__body{
      padding-top:0;
    }
    .img-one{
      width:560px;
      height:150px;
    }
    .cropper-img{
      display: block;
      border:1px solid #e0e0e0;
      width:360px;
      height:120px;
      margin:0 auto;
    }
    .cropper-box{
      width:560px;
      height:270px;
      position: relative;
      .cropper-button{
        position: absolute;
        right:10px;top:10px;
        z-index:1;
        background: #0183FA;
        color:#fff;
        cursor: pointer;
        padding:5px 10px;
        margin:0;
        border-radius:6px;
      }
    }
  }
</style>
