<template>
  <div>
    <el-dialog title="修改密码" top="8vh" :visible.sync="value" :close-on-click-modal="false" :close-on-press-escape="false"
      :show-close="false" width="30%">
      <el-form label-width="100px" :model="form" style="width:70%" :rules="rules" ref="ruleForm">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input placeholder="请输入旧密码" v-model="form.oldPassword" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input placeholder="请输入新密码" v-model="form.newPassword" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="newPassword2">
          <el-input placeholder="请输入新密码" v-model="form.newPassword2" show-password></el-input>
        </el-form-item>
        <el-form-item label="人脸信息">
          <!-- <el-input placeholder="请输入新密码" v-model="form.newPassword2" show-password></el-input> -->
          <div style="display: flex;">
            <el-upload :disabled="avatarImg != '' ? true : false" class="avatar-uploader" :show-file-list="false"
              :action="imgapi" :on-success="(file, fileList) => { fileSuccess(file, fileList); }">
              <img v-if="avatarImg !== ''" :src="avatarImg" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
          <span v-if="avatarImg !== ''" @click="removeFace" style="color: #f56c6c; cursor: pointer">删除</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('change', false)">取 消</el-button>
        <el-button type="primary" @click="rePassword('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { post, get, puk } from '@/api/common'
import { mapState } from 'vuex';
export default {
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    value: Boolean
  },
  computed: {
    ...mapState(['user'])
  },
  data () {
    const repasswordValidator = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      rules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        newPassword2: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { validator: repasswordValidator, trigger: 'blur' },
        ]
      },
      form: {
        oldPassword: "",
        newPassword: "",
        newPassword2: "",
      },
      encrypt: null,
      imgUrl: process.env.VUE_APP_BASE_IMG_URL,
      imgapi: process.env.VUE_APP_BASE_IMG_API, //上传图片地址
      sysUserId: "",
      avatarImg: "",
      userForm: {}
    }
  },
  created () {
    puk().then((res) => {
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(res.data);
      this.encrypt = encrypt;
    });
    // post('/CustomFace/groupAdd', {}).then(res => {
    //   console.log('创建人脸权限组成功')
    // })
  },
  mounted () {
    this.getUserInfo()
  },
  methods: {
    // 获取当前登录人信息
    getUserInfo () {
      get('/sysUser/page', { name: this.user.name }).then(res => {
        if (res.code == 10000) {
          if (res.data.list[0].faceImg != null && res.data.list[0].faceImg != '') {
            this.avatarImg = res.data.list[0].faceImg
          }
          // this.avatarImg = res.data.list[0].faceImg
          this.userForm = res.data.list[0]
        }
      })
    },
    // 面部图片上传成功
    fileSuccess (file, fileList) {
      if (file.code == 10000) {
        this.avatarImg = this.imgUrl + file.data
        this.faceRegistered(file.data)
      }
    },
    // 注册人脸
    faceRegistered (imgUrl) {
      let params = {
        imgPath: this.avatarImg,
        imgUrl: imgUrl,
        sysUserId: this.userForm.id
      }
      post('/CustomFace/faceRegistered', params).then(res => {
        if (res.code == 10000) {
          this.$message.success(res.data)
        }
      })
    },
    // 删除人脸信息
    removeFace () {
      this.$confirm('此操作将注销人脸信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {
          faceGroupId: this.userForm.faceGroupId,
          faceToken: this.userForm.faceToken,
          faceUserId: this.userForm.faceUserId,
        }
        post('/CustomFace/faceRemove', params).then(res => {
          if (res.code == 10000) {
            this.$message.success('删除成功')
            this.avatarImg = ""
          }
        })
      })
    },
    // 确认修改信息
    rePassword (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          this.editPassWord()
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    // 编辑密码
    editPassWord () {
      let oldPassword = this.encrypt.encrypt(this.form.oldPassword)
      let newPassword = this.encrypt.encrypt(this.form.newPassword)
      let params = {
        newPassword: newPassword,
        oldPassword: oldPassword,
      }
      post('/sysUser/changepw', params).then(res => {
        if (res.code == 10000) {
          this.$message.success('修改成功!')
          setTimeout(() => {
            this.$store.dispatch("user/logout");
            this.$router.push(`/login?redirect=${this.$route.fullPath}`);
          }, 1500)
        }

      })

    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  width: 200px;
  height: auto;
  margin-right: 10px;
  display: inline-block;

  .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}

.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: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 200px;
  height: auto;
  display: block;
}
</style>