<template>
  <div class="create-container">
    <div class="create-body" v-loading="loading">
      <div class="title">企业信息认证</div>
      <el-form :model="authentication" :rules="rules" ref="authentication" label-width="12%" class="demo-report">
        <el-form-item label="公司名" prop="enterpriseName">
          <el-input v-if="isModifyMode" v-model="authentication.enterpriseName"></el-input>
          <span v-if="!isModifyMode">{{authentication.enterpriseName}}</span>
        </el-form-item>
        <el-form-item label="公司营业执照" prop="file">
          <el-upload
            v-if="isModifyMode"
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :http-request="uploadFile"
            :before-upload="beforeFileUpload">
            <img v-if="authentication.businessLicensePhoto" :src="authentication.businessLicensePhoto" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span v-if="!isModifyMode">
          <el-image
            style="width: 100px;"
            :src="authentication.businessLicensePhoto"
            fit="scale-down"></el-image>
        </span>
          <!--<div v-if="!isModifyMode">-->
          <!--<span v-if="authentication.photo==null">暂无文件</span>-->
          <!--<a :href="authentication.photo" v-if="authentication.photo!=null"><i class="fa fa-file-text-o"></i>-->
          <!--{{authentication.photo}}</a>-->
          <!--</div>-->
        </el-form-item>
        <el-form-item v-if="!isModifyMode" label="认证状态" prop="name">
          <el-tag :type="authentication.authStatus.style">{{authentication.authStatus.text}}</el-tag>
        </el-form-item>
        <el-form-item v-if="!isModifyMode && authentication.authStatus.text == '认证失败'" label="失败原因" prop="name">
          <el-link v-if="authentication.explain!=null&&authentication.explain!=''" type="danger" disabled>
            {{authentication.explain}}
          </el-link>
          <el-link v-if="authentication.explain==null || authentication.explain==''" type="danger" disabled>管理员未填写
          </el-link>
        </el-form-item>
        <el-form-item label="公司法人姓名" prop="legalPersonName">
          <el-input v-if="isModifyMode" v-model="authentication.legalPersonName"></el-input>
          <span v-if="!isModifyMode">{{authentication.legalPersonName}}</span>
        </el-form-item>
        <el-form-item label="对公账户" prop="bankAccount">
          <el-input v-if="isModifyMode" v-model="authentication.bankAccount"></el-input>
          <span v-if="!isModifyMode">{{authentication.bankAccount}}</span>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
          <el-input v-if="isModifyMode" v-model="authentication.unifiedSocialCreditCode"></el-input>
          <span v-if="!isModifyMode">{{authentication.unifiedSocialCreditCode}}</span>
        </el-form-item>
        <el-form-item label="公司地址" prop="address">
          <el-input v-if="isModifyMode" v-model="authentication.address"></el-input>
          <span v-if="!isModifyMode">{{authentication.address}}</span>
        </el-form-item>

        <el-form-item v-if="!isModifyMode">
          <div class="btn btn-medium btn-info" @click="modifyInfo()">修改</div>
        </el-form-item>
        <el-form-item v-if="isModifyMode">
          <div class="btn btn-primary btn-info" @click="updateAuthInfo()">提交</div>
          <div class="btn btn-primary" @click="cancelModify()">取消</div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Http from '@/js/http'
import Apis from '@/js/api'
import {notify} from '@/constants/index'
import {
  defaultValue,
  getCurrentEnterpriseAuthInfo,
  getCurrentUser,
  getRolesPermissions,
  storageGet,
  storageSave,
  updateEnterpriseAuthInfo
} from '@/js/index'

export default {
  name: 'EnterpriseAuthentication',
  data () {
    return {
      userId: 0,
      user: {},
      isModifyMode: false,
      loading: false,
      authentication: {
        enterpriseName: '',
        legalPersonName: '',
        bankAccount: '',
        businessLicensePhoto: defaultValue.image,
        unifiedSocialCreditCode: '',
        address: '',
        authStatus: {text:"审核中", style:"warning"},
        explain: ''
      },
        rules: {
            enterpriseName: [
                {required: true, message: '请输入公司名称', trigger: 'blur'},
                {min: 3, max: 50, message: '机构名称长度在 3 到 50 个字符', trigger: 'blur'}
            ],
            legalPersonName: [
                {required: true, message: '请输入公司法人姓名', trigger: 'blur'}
            ],
            bankAccount: [
                {required: true, message: '请输入对公账户', trigger: 'blur'},
                {
                    validator: (rule, value, callback) => {
                        if (!this.checkNumber(value)) {
                            callback(new Error('对公账户输入有误'))
                        } else {
                            callback()
                        }
                    }, trigger: 'blur'
                },
            ],
            unifiedSocialCreditCode: [
                {required: true, message: '请输入统一社会信用代码', trigger: 'blur'},
                {
                    validator: (rule, value, callback) => {
                        if (!this.checkNumberAndWord(value)) {
                            callback(new Error('统一社会信用代码输入有误'))
                        } else {
                            callback()
                        }
                    }, trigger: 'blur'
                },
            ],
            address: [
                {required: true, message: '请输入公司地址', trigger: 'blur'}
            ]
        }
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    //初始化数据
    init () {
      this.setUserInfo()
      this.getAuthInfo()
    },
    //加载数据
    getAuthInfo () {
      this.showLoading()
      getCurrentEnterpriseAuthInfo(this.user.userVO.id, this.getAuthInfoSuccess, this.getAuthInfoFail)
    },
    getAuthInfoSuccess (res) {
        this.hideLoading()
      this.authentication.enterpriseName = res.enterpriseName == null ? '暂未填写' : res.enterpriseName
      this.authentication.legalPersonName = res.legalPersonName == null ? '暂未填写' : res.legalPersonName
      this.authentication.businessLicensePhoto = res.businessLicensePhoto == null ? defaultValue.image : res.businessLicensePhoto
      this.authentication.unifiedSocialCreditCode = res.unifiedSocialCreditCode == null ? '暂未填写' : res.unifiedSocialCreditCode
      this.authentication.bankAccount = res.bankAccount == null ? '暂未填写' : res.bankAccount
      this.authentication.address = res.address == null ? '暂未填写' : res.address
      this.authentication.authStatus = res.authStatus
      this.authentication.explain = res.explain
      console.log(this.authentication)
    },
    getAuthInfoFail (error) {
      this.hideLoading()
      notify('error', '加载认证信息失败：' + error.data)
    },
    //表单进入可编辑状态，可修改表单，不再使用
    modifyInfo () {
      this.isModifyMode = true
    },
    //提交认证信息
    updateAuthInfo () {
      //this.isModifyMode = false
      this.$refs['authentication'].validate(valid => {
          if (valid) {
              this.showLoading()
              const newAuthentication = {
                  userId: this.user.userVO.id,
                  enterpriseName: this.authentication.enterpriseName,
                  legalPersonName: this.authentication.legalPersonName,
                  businessLicensePhoto: this.authentication.businessLicensePhoto,
                  unifiedSocialCreditCode: this.authentication.unifiedSocialCreditCode,
                  bankAccount: this.authentication.bankAccount,
                  address: this.authentication.address,
              }
              updateEnterpriseAuthInfo(this.user.userVO.id, newAuthentication, this.updateAuthInfoSuccess, this.updateAuthInfoFail)
          } else {
              notify('error', '表单填写错误!')
              return false
          }
      })

    },
    updateAuthInfoSuccess (res) {
      this.hideLoading()
      this.cancelModify()
      console.log(res)
      this.authentication.enterpriseName = res.enterpriseName == null ? '暂未填写' : res.enterpriseName
      this.authentication.legalPersonName = res.legalPersonName == null ? '暂未填写' : res.legalPersonName
      this.authentication.businessLicensePhoto = res.businessLicensePhoto == null ? defaultValue.image : res.businessLicensePhoto
      this.authentication.unifiedSocialCreditCode = res.unifiedSocialCreditCode == null ? '暂未填写' : res.unifiedSocialCreditCode
      this.authentication.bankAccount = res.bankAccount == null ? '暂未填写' : res.bankAccount
      this.authentication.address = res.address == null ? '暂未填写' : res.address
      notify('success', '认证信息修改成功，正在为您刷新用户信息')
      getCurrentUser().then(res => {
        storageSave('user', res)
        this.user = res
        this.sendBusMessage()
        //this.rolesPermissions = getRolesPermissions(res.roleList)
        storageSave('rolesPermissions', getRolesPermissions(res.roleList))
        this.hideLoading()
        notify('success', '用户信息刷新成功')
      }).catch((error) => {
        this.hideLoading()
        notify('error', '重新获取用户信息失败：' + error.data)
      })
    },
    updateAuthInfoFail (error) {
      this.hideLoading()
      notify('error', error.data)
    },
    //取消修改表单，表单进入不可编辑状态，不再使用
    cancelModify () {
      this.isModifyMode = false
    },
    //上传文件时移除文件的响应函数
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    //添加文件时的响应函数
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
          } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    //移除文件前的响应函数
    beforeRemove (file, fileList) {
      //return this.$confirm(`确定移除 ${file.name}？`)
    },
    //文件上传前的响应函数
    beforeFileUpload () {
    },
    //上传文件，此处为上传图片
    uploadFile (param) {
      const formData = new FormData()
      let config = {
        //添加请求头
        headers: {'Content-Type': 'multipart/form-data'},
      }
      formData.append('file', param.file)
      Http.upload(Apis.FILE.UPLOAD_IMAGE.replace('{userId}', this.user.userVO.id), formData, config).then((res) => {
        console.log('上传成功')
        this.authentication.photoUrl = res.data
        console.log(res.data)
        notify('success', '上传成功')
      }).catch(error => {
        notify('error', error.data.msg)
      })
    },
    //
    setUserInfo () {
      this.user = storageGet('user')
    },
    //测试用函数
    test () {

    },
    showLoading () {
      this.loading = true
    },
    hideLoading () {
      this.loading = false
    },
    sendBusMessage () {
      this.$root.$emit('user', this.user)
    },
    checkNumber(value){
        return /^\d+$/.test(value);
    },
    checkNumberAndWord(value){
        return /^[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/g.test(value) || /^[A-Za-z0-9]\w{14}$/g.test(value);
    }
  },
}
</script>
<style scoped>
  .el-radio {
    margin: 10px 20px 10px 0;
  }

  .el-form-item /deep/ .el-tabs__content {
    max-height: 120px !important;
    overflow: auto;
  }

  .el-row {
    margin-bottom: 10px;
  }

  .el-input {
    width: 400px;
  }

  .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 {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 176px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

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

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