<template>
   <el-form ref="userRef" :model="user" :rules="rules" label-width="80px">
      <el-form-item label="用户昵称" prop="nickName">
         <el-input v-model="user.nickName" maxlength="30" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
         <el-input v-model="user.phonenumber" maxlength="11" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
         <el-input v-model="user.email" maxlength="50" />
      </el-form-item>
      <el-form-item label="性别">
         <el-radio-group v-model="user.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
         </el-radio-group>
      </el-form-item>
      <el-form-item label="电子印章">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="options.imgData != ''" class="avatar" :src="options.imgData"/>
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <el-link v-if="options.fileName != ''" :underline="false" type="primary" style='margin-left: 20px;'
            @click='deleteAvatar'>删除</el-link>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button type="danger" @click="close">关闭</el-button>
      </el-form-item>
   </el-form>
</template>

<script setup>
import { updateUserProfile } from "@/api/system/user";
import { uploadSeal , deleteSeal, getSeal} from '@/api/workflowManagement'
import key from '@/constant/key';
import { ElMessageBox , ElMessage} from 'element-plus'

const props = defineProps({
  user: {
    type: Object
  }
});

const { proxy } = getCurrentInstance();
const $p = getCurrentInstance()?.appContext.config.globalProperties.$t

const options = reactive({
  imgData: '', //预览图片
  imgFile: '', //UpLoad用
  changeflg: '',//变更有无flg
  fileName: '',//文件名
})

const rules = ref({
  nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  email: [{ required: true, message: "邮箱地址不能为空", trigger: "blur" }, { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
  phonenumber: [{ required: true, message: "手机号码不能为空", trigger: "blur" }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
});

onMounted(() => {
  getSeal().then(res => {
    options.imgData = res.i_sign_image
    options.fileName = res.i_sign_name
  })
})

/** 提交按钮 */
function submit() {
  proxy.$refs.userRef.validate(valid => {
    if (valid) {
      updateUserProfile(props.user).then(response => {
        if ('1' === options.changeflg) {
          const obj = new FormData()
          obj.append('i_language', localStorage.getItem(key.languageKey))
          obj.append("avatar_file", options.imgFile)
          uploadSeal(obj).then(res => {
            options.imgData = res.i_file_show
            options.fileName = res.i_file_name_new
            options.changeflg = ''
            proxy.$modal.msgSuccess("修改成功")
          })
        } else {
          proxy.$modal.msgSuccess("修改成功");
        }
      });
    }
  });
};
/** 关闭按钮 */
function close() {
  proxy.$tab.closePage();
};
/** 覆盖默认上传行为 */
function requestUpload() {}
/** 上传预处理 */
function beforeUpload(file) {
  if (!['image/jpg', 'image/jpeg', 'image/png', 'image/img', 'image/bmp', 'image/gif'].includes(file.type)) {
    ElMessage.error($p('imageType'));
  } else if (file.size / 1024 / 1024 / 1024 > 16) {
    ElMessage.error($p("imageSize"))
  } else {
    options.imgFile = file
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      options.imgData = reader.result
      options.changeflg = '1'
    }
  }
}
//删除电子印章
function deleteAvatar(){
  if (options.fileName != '') {
    ElMessageBox.confirm(
      $p("common_0070"), {
        confirmButtonText: $p("confirmConfirm"),
        cancelButtonText: $p("cancel"),
      }
    ).then(
      () => {
        deleteSeal(options.fileName).then(res =>{
          if (res.resultCode == '0') {
            ElMessage({
              type: 'success',
              message: $p("common_0080"),
            })
            options.imgData = ''
            options.fileName = ''
            options.imgFile = ''
            options.changeflg = ''
          }
        })
      }
    ).catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
  }
}
</script>

<style>

.avatar-uploader {
  width: 6vh;
  height: 6vh;
  display: block;
  display: inline;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 6vh;
  height: 6vh;
  text-align: center;
}

.avatar {
  border: 1px dotted var(--el-border-color);
  font-size: 28px;
  color: #8c939d;
  width: 6vh;
  height: 6vh;
  text-align: center;
}

</style>