<template>
  <div :class="mobile ? 'companyVerifyInputMobile' : 'companyVerifyInput'">
    <div class="titleArea">
      <p>企业认证</p>
    </div>
    <div class="bodyArea">
      <div class="selectList">
        <div class="topTips">
          <p>认证优势：</p>
          <p>·同方向同时5次的预约机会（未认证企业只有1次）</p>
          <p>·能预约全部展示的优质开发者</p>
          <p>·全国最大中高端程序员共享工作台，独享展示标签</p>
          <p>·提升企业技术水平公信力，提高约单转化率</p>
          <!--<p>·认证需完善企业信息并支付认证费用58元</p>-->
        </div>
        <div class="inputArea">
          <div class="inputBox" v-for="item in inputList" :key="item.name">
            <p class="name">{{item.title}}</p>
            <input type="text" placeholder="请输入" v-model="item.value">
          </div>
        </div>
        <div class="uploadFile">
          <p class="name">请上传 <span>加盖公章</span> 的营业执照</p>
          <div class="uploadArea">
            <el-upload
              v-loading="uploading"
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :multiple="false"
              accept="image/png, image/jpeg"
              :before-upload="handleFileChange"
            >
              <i v-if="imageUrl" class="el-icon-delete avatar-uploader-icon" @click.stop="handleDeleteFile"></i>
              <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
              <div v-else class="noneImage">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <span class="title">上传照片</span>
              </div>
            </el-upload>
            <p class="tipps">
             (图片大小最大2M)
            </p>
          </div>
        </div>
      </div>
      <div class="submitButton">
        <div class="left"></div>
        <div class="right" @click="submitForm" :class="isSubmit ? '' : 'noSubmit' ">
          <p>{{calcBtnWord}}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    name: 'companyVerifyInput',
    data() {
      return {
        typeList: [],
        inputList: [
          { name: 'name', title: '企业名称', value: '' },
          { name: 'register_number', title: '工商执照注册号/统一社会信用代码', value: '' },
          { name: 'phone', title: '联系方式', value: '' },
        ],
        imageUrl: '',
        dataInfo: {},
        uploading: false,
        loadingStatus: null,
        getTimes: 30
      }
    },
    asyncData({ app }) {
      return {
        mobile: app.$deviceType.isMobile(),
      }
    },
    computed: {
      isSubmit() {
        const { verify_status } = this.dataInfo || {}
        if ([ 1, 2 ].indexOf(Number(verify_status)) !== -1) {
          return false
        }
        return true
      },
      calcBtnWord() {
        let { verify_status } = this.dataInfo || {}
        verify_status = Number(verify_status || 0)
        if (verify_status === 0) {
          return '立即认证'
        } else if (verify_status === 1) {
          return '审核中'
        } else if (verify_status === 2) {
          return '认证通过'
        } else if (verify_status === 3) {
          return '立即认证'
        }
      }
    },
    async created() {

    },
    async mounted() {
      await this.needLogin()
      this.getInfo()
    },
    methods: {
      /** 获取展示状态 */
      getInfo(isRefresh=false) {
        this.$axios.get('/api/remote/get_company_verify_info_for_apply').then(res => {
          if (res.data.status === 1) {
            this.dataInfo = res.data.data
            // status: "0" 未认证 1认证中 2已成功 3被拒绝
            this.inputList.forEach(item => {
              let value = this.dataInfo[ item.name ]
              if (value) {
                item.value = value
              }
            })
            const {need_pay, verify_status} = res.data.data
            if (res.data.data && (Number(need_pay) !== 1 || verify_status) && isRefresh) {
              this.$message.success("您已提交企业认证，请耐心等待审核结果!")
              clearInterval(this.interval)
              this.loadingStatus && this.loadingStatus.close()
            }
            this.inputList = [ ...this.inputList ]
            this.imageUrl = this.dataInfo.photo_url || ''
            console.log('ist', this.inputList)
          }
        })
      },

      /** 提交 **/
      submitForm() {

        //认证中 已认证 不能再次提交
        if (!this.isSubmit) {
          this.$message.warning('你已提交企业认证信息，修改请联系客服')
          return
        }
        let p = {
          name: '',
          register_number: '',
          phone: '',
          photo_url: ''
        }
        p.photo_url = this.imageUrl
        this.inputList.forEach(item => {
          p[ item.name ] = item.value
        })

        if (!p.name) {
          this.$message.warning('请输入企业名称');
          return;
        }
        if (!p.register_number) {
          this.$message.warning('请输入工商执照注册号');
          return;
        }
        if (!p.phone) {
          this.$message.warning('请输入手机号码');
          return;
        }
        if (!p.photo_url) {
          this.$message.warning('请上传加盖公章的营业执照');
          return;
        }

        this.$axios.post('/api/remote/save_company_verify_apply', p).then(res => {
          let data = res.data
          if (data.status === 1) {
            //跳转到支付58元钱，之后提交
            if (Number(this.dataInfo.need_pay) === 1) {
              this.$message.success('提交成功,正在跳转...')
              let appUrl = "proginn://pay?product_type=5&product_id=0"
              let url = '/pay?product_type=5'
              if (!this.$deviceType.app) {
                window.open(url, '_black')
              } else {
                console.log('跳转到移动端支付...', url)
                location.href = appUrl
              }
              setTimeout(()=>{
                this.loadingStatus = this.$loading({ fullscreen: true, text: '正在查询支付状态...' });
                this.getPayStatus()
              }, 1500)
            } else {
              this.$message.success('您已提交企业认证，请耐心等待审核结果!')
              setTimeout(() => {
                if (this.$deviceType.app) {
                  history.back()
                } else {
                  location.href = '/wo/work_todo'
                }
              }, 1000)
            }
          } else {
            this.$message.error('提交失败')
          }
        }).catch(e => {
          console.log(e)
          this.$message.error('提交失败')
        })
      },

      handleFileChange(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
          return
        }
        const formData = new FormData();
        formData.append("file", file);
        formData.append("original_filename", file.name);
        this.uploading = true;
        this.$axios
          .$post(`/upload_image`, formData, {
            headers: { "Content-Type": "multipart/form-data" }
          })
          .then(res => {
            console.log(res)
            this.imageUrl = res.filename
          }).catch((e)=>{
            this.$message.error("上传失败:" + e.message)
          })
          .finally(() => {
            this.uploading = false;
          });
      },
      handleDeleteFile() {
        this.imageUrl = ''
      },
      async getPayStatus() {
        let maxTime = 30
        this.interval = setInterval(()=>{
          this.getInfo(true)
          maxTime--
          if (maxTime < 0) {
            this.loadingStatus && this.loadingStatus.close()
            this.$message.error("支付结果查询超时，请刷新页面或重试。")
            clearInterval(this.interval)
            return
          }
        }, 3000)
      }
    },

  }
</script>
<style lang="scss" scoped>
  @import '../../../assets/css/otherpage/companyVerifyInput.scss';
</style>

<style lang="scss">
  @import '../../../assets/css/scssCommon.scss';
  .el-upload {
    width: 184px;
    height: 136px;
    border: 1px dashed #409eff;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    img {
      width: 100%;
      height: auto;
      object-fit: contain;
      object-position: top left;
    }
    &:hover {
      border-color: #409eff;
      .el-icon-delete {
        display: block;
      }
    }
  }
  .companyVerifyInputMobile {
    .el-upload {
      width: pxtovw(184);
      height: pxtovw(136);
      border: pxtovw(1) dashed #409eff;
      border-radius: pxtovw(6);
    }
  }

</style>
