<template>
  <div class="file">
    <back title="证件照上传"></back>
    <div v-if="loginInfo.need_upload_photo == 1">
      <!-- <h2>提示：证件照后缀名必须为 ".jpg", ".jpeg", ".png"格式</h2>
      <h2>上传证件照的像素、底色不限</h2>
      <h2 class="texttip"><b>不要</b>上传自己的身份证照片</h2> -->
      <img src="../../../static/img/tip.png" width="100%" height="30%" />
      <div class="imgreplace">
        <label class="input-file-button" for="upload">选择证件照</label>
        <!-- <input type="file" id="upload" /> -->
        <input
          type="file"
          class="updata"
          accept="image/*"
          @change="change($event)"
          ref="updata"
          id="upload"
        />
        <mt-button type="primary" size="small" @click="upload()" style="margin-top: 10px"
          >上传证件照</mt-button
        >
        <!-- <mt-button type="primary" size="small">选择证件照</mt-button> -->
      </div>
      <!-- <p>您上传的文件为：{{ filename }}</p> -->
      <p v-if="filename != ''" padding-top="33px">您上传的证件照名：{{ filename }}</p>
      <img :src="imageUrl" alt="" class="img" title="预览" /><br />
      <input type="hidden" :value="loginInfo.member_passport" ref="getValue" />
      <input type="hidden" v-model="filename" />
      <input type="hidden" v-model="photopath" id="" />
      <!-- <input type="text" :value="ImgObj.src"> -->
      <h2 style="padding-top: 1em; font-size: 2.3em">已上传的证件照</h2>
      <h2>（点击证件照预览）</h2>
      <img
        :src="photopath"
        alt=""
        style="
          width: 36%;
          border: 1px solid;
          box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
        "
        @click="photoPreview()"
      />
      <!-- <mt-button
        type="primary"
        size="small"
        @click="photoPreview()"
        style="margin-top: 10px"
        >预览</mt-button
      > -->
    </div>
    <div v-else-if="loginInfo.need_upload_photo != 1">
      <h1>暂未规定上传证件照</h1>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Back from "../common/Back.vue";
import axios from "axios";
import { MessageBox, Toast } from "mint-ui";
import { getStore, setStore } from "@/utils/storage";
// import Qs from "qs";
export default {
  data() {
    return {
      imageUrl: "",
      file: null,
      filename: "",
      photopath: "",
      ImgObj: new Image(),
    };
  },
  components: {
    Back,
  },
  methods: {
    change(e) {
      // console.log("e");
      // console.log(e);
      // console.log("e.target");
      // console.log(e.target);
      // console.log("e.target.files[0]");
      // console.log(e.target.files[0]);
      // console.log("file的名字：" + e.target.files[0].name);
      this.filename = e.target.files[0].name;
      // 判断是不是规定格式
      // 获取到第一张图片
      this.file = e.target.files[0];
      console.log("file文件：" + this.file.type);

      // 创建文件读取对象
      var reader = new FileReader();
      var that = this;

      //  将文件读取为DataURL
      reader.readAsDataURL(this.file);

      // 读取成功调用方法
      reader.onload = (e) => {
        console.log("读取成功");

        // e.target.result 获取 读取成功后的  文件DataURL
        that.imageUrl = e.target.result;

        // 如果要将图片上传服务器，就在这里调用后台方法
      };
    },
    upload() {
      console.log("证件号为：" + this.$refs.getValue.value);
      //限制图片的类型
      var fileTypes = [
        "image/jpeg",
        "image/JPEG",
        "image/jpg",
        "image/JPG",
        "image/png",
        "image/PNG",
      ];
      var filePath = this.filename;
      console.log("filepath:==" + filePath);
      if (filePath) {
        var isNext = false;
        // var fileEnd = filePath.substring(filePath.indexOf("."));
        for (var i = 0; i < fileTypes.length; i++) {
          if (fileTypes[i] == this.file.type) {
            isNext = true;
            break;
          }
        }
        if (!isNext) {
          MessageBox.alert('证件照的后缀名必须为".jpg", ".png", ".jpeg",格式');
          this.file = "";
          this.filename = "";
          return false;
        } else {
          MessageBox.confirm("确定上传该证件照吗?").then(
            (action) => {
              let formData = new FormData();
              formData.append("file", this.file);
              formData.append("filename", this.$refs.getValue.value + ".jpg");
              formData.append("apitoken", getStore("token"));
              const config = {
                headers: {
                  // 'Content-Type': 'multipart/form-data',
                  // "Access-Control-Allow-Origin": "*",
                  // "Access-Control-Allow-Method": "POST,GET",
                },
              };
              axios
                .post(
                  // "/uploadcardimage",formData
                  "https://adminssl.jiangtang360.com/api/card/uploadcardimage",
                  formData,
                  config
                  // Qs.stringify(formData)
                  //   {headers: {'Content-Type': 'multipart/form-data'}}
                )
                .then(
                  (res) => {
                    console.log(res);
                    // MessageBox.alert("上传成功").then((res) => {});
                    // this.$destroy();
                    Toast("上传成功");
                    location.reload();
                  },
                  (error) => {
                    Toast("上传失败,请刷新后再次尝试上传");
                  }
                );
            },
            () => {}
          );
        }
      } else {
        MessageBox.alert("请重新选择符合要求的证件照");
      }
    },
    photoPreview() {
      this.$router.push({ path: "/photoPreview" });
    },
  },
  created() {
    // 获取默认显示的图片
    // this.baseImg = require("../../../static/card/jianke_logo.png");
  },

  mounted() {
    this.photopath =
      "https://adminssl.jiangtang360.com/static/admin/cards/" +
      this.$refs.getValue.value +
      ".jpg" +
      "?ran=" +
      Math.random();
    this.ImgObj.src =
      "https://adminssl.jiangtang360.com/static/admin/cards/" +
      this.$refs.getValue.value +
      ".jpg" +
      "?ran=" +
      Math.random();
  },
  computed: {
    ...mapState(["loginInfo", "apitoken"]),
  },
};
</script>

<style scoped>
.file {
  padding-top: 5rem;
  /* width: 100%;
  height: 100%; */
  /* display: flex; */
  /* flex-direction: column;
  justify-content: space-around; */
  /* align-items: center; */
  /* position: relative;
  /* width: 200px; */
  /* height: 100%; */
  /* background-color: #ccc; */
}
/* .imgreplace {
  /* display: flex; */
/* width: 10em;
  height: 10em;
  border: 0.1em solid red; 
.updata {
position: absolute;
  width: 10em;
  height: 10em;
  z-index: 200; */
/* font-size: 0;
  padding-left: 30%;
} */
.texttip {
  margin-bottom: 3%;
}
.img {
  /* position: absolute;
  top: 0;
  left: 0; */
  width: 36%;
  /* height: 10%; */
}
.upload-button {
  padding: 6px 25px;
  background: #00bfff;
  border-radius: 4px;
  color: white;
  cursor: pointer;
}
input {
  display: none;
}
.input-file-button {
  font-size: 15px;
  color: white;
  background-color: #26a2ff;
  border-radius: 4px;
  padding: 8.3px;
  margin-bottom: 22px;
}
</style>
