<!--
 * @Author: your name
 * @Date: 2021-12-25 17:22:27
 * @LastEditTime: 2021-12-25 18:52:27
 * @LastEditors: Please set LastEditors
 * @Description: 人员档案 - 增加人员 or 编辑人员
 * @FilePath: \hyyfClient\src\views\BioSafety\personAdmin\AddOrEdit.vue
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="30%"
    @close="handleCancel"
  >
    <div class="reset-form">
      <el-form
        label-width="120px"
        size="small"
        :rules="rules"
        :model="form"
        ref="form"
      >
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="部门：" prop="departmentId">
          <el-select v-model="form.departmentId" style="width: 100%">
            <el-option
              v-for="item in departmentList"
              :key="item.label"
              :value="item.value"
              :label="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片：">
          <el-upload
            class="upload-demo"
            action="''"
            :auto-upload="false"
            :on-change="handleSuccess"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="file"
          >
            <el-button size="small" type="primary">选择图片</el-button>
            <!-- <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500kb
              </div>
            </template> -->
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleCancel">取 消</el-button>
      <el-button size="small" type="primary" @click="handleSubmit">
        确 定
      </el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addPerson, addPersonPicture, addPictureToPerson } from "@/utils/chenApi.js";
import { getFaceToken } from "@/utils/api.js";
export default {
  data() {
    return {
      title: "",
      dialogVisible: false,
      form: {
        id: undefined,
        name: "",
        departmentId: "",
      },
      rules: {
        name: [{ required: true, message: "姓名不可以为空", trigger: "blur" }],
        departmentId: [
          { required: true, message: "部门需要选择", trigger: "blur" },
        ],
      },
      departmentList: [
        {
          value: 4,
          label: "维修部门",
        },
        {
          value: 2,
          label: "技术部门",
        },
        {
          value: 5,
          label: "基层部门",
        },
      ],
      file: [],
    };
  },
  methods: {
    init(row) {
      if (row) {
        this.title = "编辑人员";
        this.$nextTick(() => {
          this.form = { ...row };
        });
      } else {
        this.title = "新增人员";
      }
      this.dialogVisible = true;
    },
    handleSubmit() {
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let request = addPerson;
      if (this.form.id) {
        // request = postDeviceEdit;
      }
      request({ ...this.form }).then(async (res) => {
        loading.close();
        if (res.code === 0) {
          try {
            const formData = new FormData();
            formData.append("file", this.file[0]);
            const { token } = await getFaceToken({});
            const { data } = await addPersonPicture(formData, token);
            console.log(data);
            if(data) {
              let params = {
                personId: res.data.data.id,
                path: data
              }
              addPictureToPerson(params).then(res => {
                if(res.code == 0) {
                 this.$message.success('新增档案成功！');
                 this.handleCancel();
                  this.$emit("reflash");
                }
              })
            }
          } catch (err) {
            this.$message.error(`照片${this.form.id ? "修改" : "添加"}成功`);
          }
          // this.$message.success(`${this.form.id ? "修改" : "添加"}成功`);
          // this.handleCancel();
          // this.$emit("reflash");
        } else {
          this.$message.error(`${this.form.id ? "修改" : "添加"}失败`);
        }
        this.file = [];
      });
    },
    // 取消
    handleCancel() {
      this.dialogVisible = false;
      if (this.form.id) {
        this.$nextTick(() => {
          this.$refs["form"].resetFields();
        });
      }
    },
    // 图片接口
    handleRemove() {
      this.file = [];
    },
    handleExceed() {
      this.$message.warning("请注意，只能选择一张图片");
    },
    beforeRemove(file) {
      return this.$confirm(`取消上传${file.name} ?`);
    },
    handleSuccess(file) {
      const isImg = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if(!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        this.file = [];
      }
      if(!isImg) {
        this.$message.error('上传头像图片只能是JPG或者png格式的图片！');
        this.file = [];
      } else {
        this.file.push(file.raw);
      }
    },
  },
};
</script>
<style scoped>
.reset-form {
  margin-right: 20px;
}
.dialog-footer {
  margin-right: 20px;
}
</style>
