<template>
  <div class="right-modifyPsw" id="individualAuth" v-loading="loading">
    <div class="right-modifyPsw-title">
      <span style="font-size: 18px;font-weight: bold;margin-right: 10px">个人认证</span>
      <el-tag :type="authStatus.style" v-if="authType===1">{{authStatus.text}}</el-tag>
      <el-tag type="danger" v-if="authType===0">未认证</el-tag>
<!--      <el-button type="primary" class="pull-right" size="small" v-if="canEdit" @click="canEdit = true">编辑</el-button>-->
    </div>
    <!--    <div class="individual-steps-wrapper">-->
    <!--      <el-steps :active="active" process-status="finish" style="margin-bottom: 20px;width: 300px">-->
    <!--        <el-step title="填写认证信息"></el-step>-->
    <!--        <el-step title="认证结果"></el-step>-->
    <!--      </el-steps>-->
    <!--    </div>-->

    <el-alert
      v-if="failureReason&&failureReason!==''"
      :title="failureReason"
      type="error">
    </el-alert>
    <el-form ref="individualForm" :model="individualForm" :rules="rules" label-width="140px" style="width: 70%;margin-top: 10px">
      <el-form-item label="真实姓名" prop="realName">
        <el-input :disabled="!canEdit" v-model="individualForm.realName" placeholder="请输入您的姓名，需与身份证保持一致"></el-input>
      </el-form-item>
      <el-form-item label="身份证号码" prop="idCard">
        <el-input :disabled="!canEdit" v-model="individualForm.idCard" placeholder="身份证前后不能有空格"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="individualForm.gender" :disabled="!canEdit">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="身份证到期时间" prop="idCardDeadTime">
        <el-date-picker
          v-model="individualForm.idCardDeadTime"
          style="width: 100%"
          align="right"
          type="date"
          placeholder="请按身份证背面“有效期限”如实填写"
          :disabled="!canEdit"
          >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="家庭或单位地址" prop="address">
        <el-input :disabled="!canEdit" v-model="individualForm.address"></el-input>
      </el-form-item>
      <el-form-item label="认证权限" prop="roleList">
        <el-checkbox-group v-model="individualForm.roleList" :disabled="!canEdit">
          <el-checkbox :label="0">发包</el-checkbox>
          <el-checkbox :label="1">接包</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div class="upload-wrapper">
      <el-row style="width: 100%">
        <el-col :span="9" style="padding-left: 30px">
          <div style="width: 280px">
            <el-upload
              class="avatar-uploader"
              style="border: lightgrey 1px solid"
              action="https://jsonplaceholder.typicode.com/posts/"
              :before-upload="beforeFileUpload"
              :http-request="uploadFile"
              :data="{type:0}"
              :disabled="!canEdit"
            >
              <img v-if="individualForm.idCardPositivePhoto" :src="individualForm.idCardPositivePhoto" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon card-uploader-icon"></i>
            </el-upload>
            <div style="text-align: center">身份证正面照<span style="color:red">(必填)</span></div>
          </div>
        </el-col>
        <el-col :span="15">
          <div class="authentication-detail">
            <div class="authentication-detail-title">证件要求</div>
            <el-row>
              <el-col :span="11">
                <div class="idcard-example1"></div>
              </el-col>
              <el-col :span="13" style="padding-left: 10px">
                <ul class="authentication-detail-list">
                  <li>请上传本人<span class="authentication-detail-list-blue">手持</span>身份证正面头部照片和上 半身照片</li>
                  <li>照片为免冠、未化妆的数码照片原始图片<span class="authentication-detail-list-blue">请勿用任何软件编辑修改</span></li>
                  <li>必须看清证件信息，且证件信息不能被遮挡， 持证人五官清晰可见</li>
                  <li>仅支持.jpg .bmp .png .gif的图片格式，图 片大小不超过3M</li>
                  <li>核实手持证件与原件方向一致，对焦身份证 进行拍照</li>
                  <li>您提供的照片众测服务平台将予以保护，不 会用于其他用途</li>
                </ul>
<!--                <a class="authentication-detail-list-blue">实名认证帮助></a>-->
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <el-row style="width: 100%">
        <el-col :span="9" style="padding-left: 30px">
          <div>
            <el-upload
              class="avatar-uploader"
              style="border: lightgrey 1px solid"
              action="https://jsonplaceholder.typicode.com/posts/"
              :before-upload="beforeFileUpload"
              :http-request="uploadFile"
              :data="{type:1}"
            >
              <img v-if="individualForm.idCardBackPhoto" :src="individualForm.idCardBackPhoto" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon card-uploader-icon"></i>
            </el-upload>

            <div style="text-align: center">身份证反面照<span style="color:red">(必填)</span></div>
          </div>
        </el-col>
        <el-col :span="15">
          <div class="authentication-detail">
            <div style="height: 40px;width: 100%"></div>
            <el-row>
              <el-col :span="11">
                <div class="idcard-example2"></div>
              </el-col>
              <el-col :span="13" style="padding-left: 10px">
                <ul class="authentication-detail-list">
                  <li>必须看清证件信息，且证件信息不能被遮挡</li>
                  <li>仅支持.jpg .bmp .png .gif的图片格式，图 片大小不超过3M</li>
                  <li>您提供的照片众测服务平台将予以保护，不 会用于其他用途</li>
                </ul>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>

    </div>
    <div class="enterprise-brn-wrapper">
      <!--      <button class="enterprise-btn previousBtn">上一步</button>-->
      <el-button type="primary" style="cursor: pointer" @click="submitIndividualAuth" v-if="canEdit && authType === 0">提交审核</el-button>
      <el-button type="primary" style="cursor: pointer" @click="submitIndividualAuth" v-if="canEdit && authType != 0">修改审核</el-button>
    </div>
  </div>
</template>

<script>
  import Apis from '@/js/api'
  import Http from '@/js/http'
  import {notify} from '@/constants/index'
  import {storageGet} from '@/js/index'
  import idcardPositive from '../../assets/img/idcard-positive.png'
  import idcardBack from '../../assets/img/idcard-back.png'

  export default {
    name: "IndividualAuth",
    data() {
      return {
        loading: false,
        active: 0,
        user: {},
        individualForm: {
          roleList: [],//0是发包 1是接包 如果两个都有那么权限都有。
          realName: "",
          gender: "",
          idCard: "",
          idCardPositivePhoto: '',
          idCardBackPhoto: '',
          idCardDeadTime: "",
          address: ""
        },
        failureReason: '',
        authType: -1,
        authDetail: {},
        authStatus: '',
        canEdit: false,
        rules:{
          realName: [
            { required: true, message: '请输入真实姓名', trigger: 'blur' },
          ],
          idCard: [
            { required: true, message: '请输入身份证号码', trigger: 'blur' },
          ],
          address:[
            { required: true, message: '请输入家庭或单位地址', trigger: 'blur' },
          ],
          gender: [
            { required: true, message: '请选择性别', trigger: 'blur' }
          ],
          roleList: [
            { type: 'array', required: true, message: '请至少选择一个认证权限', trigger: 'change' }
          ],
          idCardDeadTime: [
            {  required: true, message: '请选择身份证过期时间', trigger: 'change' }
          ]
        }
      }
    },
    methods: {
      setUserInfo() {
        this.type = this.$route.query.type;
        this.user = storageGet('user') && storageGet('user').userVO;
      },
      submitIndividualAuth() {
        this.$refs['individualForm'].validate(valid => {
          if (!valid) {
            notify('error', '信息填写不规范');
            return false
          }
        })
        if(!this.individualForm.idCardPositivePhoto){
          notify('error', '身份证正面照片上传不规范');
          return false;
        }
        if(!this.individualForm.idCardBackPhoto){
          notify('error', '身份证反面照片上传不规范');
          return false;
        }
        this.showLoading();
        let firstSubmit = this.$route.query.type;
        if(firstSubmit == 1){
          Http.post(`/api/user/${this.user.id}/personalAuth`, this.individualForm).then(res => {
            if (res) {
              notify('success', '提交成功');
              this.$router.push('/personal/authentication')
            }
          }).catch(err => {
            this.hideLoading();
            notify('error', err.data)
          })
        }else{
          Http.put(`/api/user/${this.user.id}/personalAuth`, this.individualForm).then(res => {
            if (res) {
              notify('success', '修改成功');
              this.$router.push('/personal/authentication')
            }
          }).catch(err => {
            console.log("错误信息");
            console.log(err);
            this.hideLoading();
            notify('error', err.data)
          })
        }
      },
      //获取当前认证状态
      getAuthStatus() {
        Http.get(`/api/user/${this.user.id}`).then(res => {
          if (res.personalAuthVO) {
            this.authType = 1  //个人已参与认证
            this.authStatus = res.personalAuthVO.authStatus
            //成功状态不可编辑，认证失败和审核中状态可编辑
            this.authStatus.style !== 'success' ? this.canEdit = true : null
            this.failureReason = res.personalAuthVO.explain
            this.setFormInfo(res.personalAuthVO);
          } else {
            this.authType = 0  //未参与个人认证
            this.canEdit = true
          }
        }).catch(err => {
          notify('error', err.data)
        })
      },
      setFormInfo(detail) {
        //回显认证信息
        this.individualForm.roleList = detail.roleList,
          this.individualForm.realName = detail.realName,
          this.individualForm.gender = detail.gender,
          this.individualForm.idCard = detail.idCard,
          this.individualForm.address = detail.address,
          this.individualForm.idCardPositivePhoto = detail.idCardPositivePhoto,
          this.individualForm.idCardBackPhoto = detail.idCardBackPhoto,
          this.individualForm.idCardDeadTime = detail.idCardDeadTime
      },
      //文件上传前的响应函数
      beforeFileUpload(file) {
        // 文件大小不能超过10M
        if (file.size > 10 * 1000 * 1000) {
          notify('error', '单个文件大小不能超过5M')
          return false;
        }
        let fileName = file.name
        let index = fileName.lastIndexOf('.');
        // 文件不能没有后缀
        if (index <= 0) {
          notify('error', '只能上传png/jpg/jpeg格式的文件')
          return false;
        }
        let fileSuffix = fileName.substr(index)
        // 文件后缀必须是.png或者.jpg
        if (fileSuffix !== '.jpg' && fileSuffix !== '.png' && fileSuffix !== '.jpeg') {
          notify('error', '只能上传png/jpg/jpeg格式的文件')
          return false;
        }
      },
      //上传文件，此处为上传图片
      uploadFile(param) {
        const formData = new FormData()
        let config = {
          //添加请求头
          headers: {'Content-Type': 'multipart/form-data'},
        }
        formData.append('file', param.file)
        //console.log(JSON.parse(this.user).userVO)
        Http.upload(Apis.FILE.UPLOAD_IMAGE.replace('{userId}', this.user.id), formData, config).then((res) => {
          if (param.data.type === 0) {
            this.individualForm.idCardPositivePhoto = res.data
          } else {
            this.individualForm.idCardBackPhoto = res.data
          }
          notify('success', '上传成功')
        }).catch(error => {
          notify('error', error.data)
        })
      },
      showLoading() {
        this.loading = true
      },
      hideLoading() {
        this.loading = false
      },
    },
    mounted() {
      this.setUserInfo();
      this.getAuthStatus()
    }
  }
</script>

<style scoped lang="less">
  .avatar-uploader {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-right: 30px;
    width: 270px;
    height: 170px;
  }
  .avatar-uploader .el-upload {
    width: 270px !important;
    height: 170px !important;
    border-color: #409EFF;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 270px;
    height: 170px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 270px;
    height: 170px;
    display: block;
  }

  .right-modifyPsw {
    padding: 20px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 1px 6px 0px rgba(8, 6, 6, 0.13);

    .right-modifyPsw-title {
      padding: 10px;
      border-bottom: 1px solid #ccc;
      margin-bottom: 20px;
    }

    .individual-steps-wrapper {
      display: flex;
      justify-content: center;
    }

    .upload-wrapper {
      /*display: flex;*/
      /*padding: 0 30px;*/

      .idcard-uploader {
        width: 100%;

        .avatar {
          width: 100%;
        }

        .el-upload .el-upload--text {
          width: 100%;
        }
      }

      .authentication-detail {
        padding-left: 20px;
        border-left: 1px solid rgba(220, 220, 220, 1);

        .authentication-detail-title {
          font-size: 16px;
          font-family: Source Han Sans CN;
          font-weight: 600;
          border-bottom: 1px dashed rgba(220, 220, 220, 1);
          margin-bottom: 10px;
          padding-bottom: 5px;
        }

        .idcard-example1 {
          height: 140px;
          background-image: url("../../assets/img/idcard-example1.png");
          background-size: 100% 100%;
        }

        .idcard-example2 {
          height: 140px;
          background-image: url("../../assets/img/idcard-example2.png");
          background-size: 100% 100%;
        }
      }

      .authentication-detail-list {
        list-style-type: none;
        padding-left: 0;
        font-size: 12px;
        font-family: Source Han Sans CN;
        font-weight: 400;
        color: rgba(153, 153, 153, 1);

        li:before {
          content: "\2022";
          color: rgba(153, 153, 153, 1);
          font-size: 16px;
          margin-right: 10px;
        }

        .authentication-detail-list-blue {
          color: #148AE0;
        }

      }
    }

    .enterprise-brn-wrapper {
      margin-top: 40px;
      display: flex;
      justify-content: center;

      .enterprise-btn {
        border: 1px solid rgba(0, 118, 203, 1);
        width: 150px;
        background-color: white;
        color: rgba(0, 118, 203, 1);
        padding: 10px;
        margin: 0 30px;
      }

      .nextBtn {
        background-color: rgba(0, 118, 203, 1);
        color: white;
      }
    }

  }
</style>
<style lang="less">
  #individualAuth {
    .avatar-uploader .idcard-uploader {
      width: 100%;

      .avatar {
        width: 100%;
      }

      .el-upload .el-upload--text {
        width: 100% !important;
      }
    }
  }

</style>
