<template>
  <div class="login-container">
    <!-- 公司log -->
    <div class="login_header">
      <div class="w_1200">
        <div class="login_header m_0_auto">
          <div class="login_logo">
            <div>
              <img class="f_left" src="../../assets/images/svg/logo.svg">
              <span class="qyzp f_left">戎归，高品质农副产品电商平台</span>
            </div>
            <router-link to="/login">
              <div class="f_right">
                <i class="el-icon-right" />
                返回
              </div>
            </router-link>
          </div>
        </div>
      </div>
    </div>
    <!-- 主体 -->
    <div class=" login_main_bg">
      <el-steps :active="active" finish-status="success">
        <el-step title="申请开通店铺" />
        <el-step title="等待审核" />
        <el-step title="审核结果" />
      </el-steps>
      <div v-if="active=='0'" class="login_main_right">
        <div class="login_form">
          <div class="tab-box">
            <el-form
              ref="form"
              :model="form"
              :rules="rules"
              label-width="120px"
              class="demo-ruleForm"
            >
              <div class="form_list">
                <el-form-item
                  v-if="showForm"
                  label="用户名"
                  prop="userName"

                >
                  <el-input v-model.trim="form.userName" type="text" autocomplete="off" :disabled="textdisable" style="display:none;" />
                  <el-input v-model.trim="form.userName" type="text" autocomplete="new-password" :disabled="textdisable" />
                </el-form-item>
                <el-form-item
                  v-if="!showForm"
                  label="用户名"
                >
                  <el-input v-model="form.userName" type="text" disabled />
                </el-form-item>

                <el-form-item
                  v-if="showForm"
                  ref="password"
                  label="密码"
                  prop="password"
                >
                  <el-input v-model="form.password" type="password" autocomplete="off" style="display:none;"  />
                   <el-input v-model="form.password" type="password" autocomplete="new-password" />
                </el-form-item>
                <el-form-item
                  v-if="showForm"
                  label="确认密码"
                  prop="password1"
                >
                  <el-input v-model.trim="form.password1" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item
                  label="店铺名称"
                   v-if="showForm"
                  prop="merchantsName"
                >
                  <el-input v-model="form.merchantsName" type="text" autocomplete="off" />
                </el-form-item>

                <el-form-item
                  label="店铺名称"
                   v-if="!showForm"
                  prop="merchantsNameId"
                >
                  <el-input v-model="form.merchantsName" type="text" autocomplete="off" />
                </el-form-item>

                <el-form-item
                  label="联系人"
                  prop="person"
                >
                  <el-input v-model="form.person" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="form.sex">
                    <el-radio label="1">先生</el-radio>
                    <el-radio label="0">女士</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  label="联系方式"
                  prop="tel"
                >
                  <el-input v-model="form.tel" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item
                  label="公司地址"
                  prop="address"
                >
                  <el-input v-model="form.address" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item
                  label="上传营业执照"
                  prop="fileList"
                >
                  <el-upload
                    action="#"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :before-upload="beforeUpload"
                    :file-list="form.businessLicense"
                    :on-remove="handleRemove"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
                <el-form-item>
                  <el-button
                    :loading="loading"
                    class="login-btn"
                    type="primary"
                    @click.native.prevent="showForm?handleRegister():handleEditMerchants()"
                  >
                    提交
                  </el-button>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </div>
      </div>
      <div v-if="active=='1'" class="login_main_right">
        <div class="statusText">
          <span class=""><img src="../../assets/images/certificationing.png"></span>
          <p class="m_t_20 text_align_center fs_16 fw_500 fc_black">申请成功！请等待平台审核，申请时间约1-2个工作日</p>
          <el-button type="text" @click="handleEdit">查看详情</el-button>
        </div>
      </div>
      <div v-if="active=='2'" class="login_main_right">
        <div class="statusText">
          <span class=""><img src="../../assets/images/fail.png"></span>
          <p class="m_t_20 text_align_center fs_16 fw_500 fc_black">{{ refundReason }}</p>
          <p class="m_t_20 text_align_center fs_16 fw_500 fc_black">{{ refundDesc }}</p>
          <el-button
            class="login-btn"
            type="primary"
            style="margin:20px 0"
            @click="handlegoback"
          >
            再次申请
          </el-button>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <div class="footer_bg" />
    <Refund v-if="active=='1'" ref="refund" />
  </div>
</template>
<script>
import { isPassword, isPerson, isPhone } from '@/utils/validate'
import Refund from './refund'
import { setAccessToken, getAccessToken } from '@/utils/accessToken'
export default {
  name: 'Register',
  components: { Refund },
  data() {
    const validateusername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('用户名不能为空'))
      }
      const params = Object.assign({}, {
        type: 'valiUserName',
        data: {
          userName: value
        }
      })
      this.$http
        .post(this.$api.valiUserName, params)
        .then((res) => {
          if (res.resultMsg) {
            callback(new Error(res.resultMsg))
            return false
          } else {
            callback()
          }
        })
    }
    const validatePassword = (rule, value, callback) => {
      if (!isPassword(value)) {
        callback(new Error('只能输入6-20个字母、数字、下划线'))
      } else {
        callback()
      }
    }
    const validatePassword1 = (rule, value, callback) => {
      if (!isPassword(value)) {
        callback(new Error('只能输入6-20个字母、数字、下划线'))
      } else if (this.form.password !== value) {
        callback(new Error('两个密码不一致'))
      } else {
        callback()
      }
    }
    const validatePerson = (rule, value, callback) => {
      console.log(isPerson(value))
      if (!isPerson(value)) {
        callback(new Error('只能输入中文'))
      } else {
        callback()
      }
    }
    const validateTel = (rule, value, callback) => {
      if (!isPhone(value)) {
        callback(new Error('请填写正确的联系方式'))
      } else {
        callback()
      }
    }
    const validatemerchantsName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入店铺名称'))
      }
      const params = Object.assign({}, {
        type: 'valiMerchantsName',
        data: {
          merchantsName: value
        }
      })
      this.$http
        .post(this.$api.valiMerchantsName, params)
        .then((res) => {
          if (res.resultMsg) {
            callback(new Error(res.resultMsg))
            return false
          } else {
            callback()
          }
        })
    }
      //带供应商id的校验供应商名字唯一校验
     const merchantsNameId = (rule, value, callback) => {
       console.log(value)
      if (value === '') {
        callback(new Error('请输入店铺名称'))
      }
      const params = Object.assign({}, {
        type: 'valiMerchantsNameAndID',
        data: {
          merchantsName: this.form.merchantsName,
          merchantsID:this.form.merchantsId
        }
      })
      this.$http
        .post(this.$api.valiMerchantsNameAndID, params)
        .then((res) => {
          if (res.resultMsg) {
            callback(new Error(res.resultMsg))
            return false
          } else {
            callback()
          }
        })
    }
    

    const validateaddress = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入公司地址'))
      } else {
        callback()
      }
    }
    const validatemerbusinessLicense = (rule, value, callback) => {
      if (this.form.businessLicense.length <= 0) {
        callback(new Error('请上传营业执照'))
      } else {
        callback()
      }
    }
    const validatesex = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择性别'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      updateLoading: false, // 显示上传加载
      dialogImageUrl: '',
      showForm: true,
      dialogVisible: false,
      updateOtherData: null,
      active: localStorage.getItem('active') ? +localStorage.getItem('active') : '0',
      pwdType: 'text',
      textdisable: false,
      refundReason: localStorage.getItem('refundReason') ? localStorage.getItem('refundReason') : '',
      refundDesc: localStorage.getItem('refundDesc') ? localStorage.getItem('refundDesc') : '',
      avatar_file: '',
      form: {
        userName: '',
        password: '',
        password1: '',
        address: '',
        merchantsName: '',
        person: '',
        tel: '',
        sex: '',
        businessLicense: []
      },
      rules: {
        userName: [
          {
            required: true,
            trigger: ['blur'],
            validator: validateusername
          }
        ],
        password: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePassword
          }
        ],
        password1: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePassword1
          }
        ],
        address: [
          {
            required: true,
            trigger: 'blur',
            validator: validateaddress
          }
        ],
        person: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePerson
          }
        ],
        tel: [
          {
            required: true,
            trigger: 'blur',
            validator: validateTel
          }
        ],
        merchantsName: [
          {
            required: true,
            trigger: 'blur',
            validator: validatemerchantsName
          }
        ],
        fileList: [
          {
            required: true,
            trigger: 'blur',
            validator: validatemerbusinessLicense
          }
        ],
        sex: [
          {
            required: true,
            trigger: 'change',
            validator: validatesex
          }
        ],
        merchantsNameId:[
           {
            required: true,
            trigger: 'blur',
            validator: merchantsNameId
          }
        ]
      },
      defultAddress: {
        sheng: '',
        shi: '',
        qu: ''
      }
    }
  },
  created() {
    this.form = JSON.parse(getAccessToken()) ? JSON.parse(getAccessToken()) : this.form

    console.log(this.refundReason,"/////////////////////")
    if(this.form.merchantsId){
      this.getMerchantsState()
    }
  },
  methods: {
    beforeUpload(e) {
      var testmsg = e.name.substring(e.name.lastIndexOf('.') + 1)
      const extension =
        testmsg === 'jpg' ||
        testmsg === 'JPG' ||
        testmsg === 'png' ||
        testmsg === 'PNG' ||
        testmsg === 'bpm' ||
        testmsg === 'BPM' ||
        testmsg === 'jpeg'
      const isLt50M = e.size / 1024 / 1024 < 2
      if (!extension) {
        this.$message({
          message: '上传图片只能是jpg / png / bpm格式!',
          type: 'error'
        })
        return false // 必须加上return false; 才能阻止
      }
      if (!isLt50M) {
        this.$message({
          message: '上传文件大小不能超过 2M!',
          type: 'error'
        })
        return false
      }
      const avatar_data = '{"x":0,"y":0,"height":100,"width":100,"rotate":0}'
      const fd = new FormData()
      fd.append('avatar_file', e)
      fd.append('avatar_data', avatar_data)
      this.$http
        .post(this.$api.uploadAvatar, fd)
        .then((res) => {
          this.form.businessLicense.push(res)
        })
    },
    // 提交
    handleRegister(formName) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const params = Object.assign({}, {
            type: 'addMerchants',
            data: this.form
          })
          this.$store
            .dispatch('user/register', params)
            .then((response) => {
              this.form.merchantsId=response.merchantsId
              setAccessToken(JSON.stringify(this.form))
              localStorage.setItem('active', '1')
              this.active = 1
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 100)
          this.loading = false
          return false
        }
      })
    },
    // 放大
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 图片删除
    handleRemove(file, fileList) {
      const index = this.form.businessLicense.findIndex((item) => {
        return item.uid === file.uid
      })
      this.form.businessLicense.splice(index, 1)
    },
    // 再次申请
    handlegoback() {
      this.active = 0
      this.showForm = !this.showForm
      this.form = JSON.parse(getAccessToken())
      this.form.businessLicense=this.form.businessLicense
    },
    handleEdit() {
      this.$nextTick(() => {
        this.$refs['refund'].showEdit(this.form)
      })
    },
    // 编辑供应商/店铺
    handleEditMerchants() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const params = Object.assign({}, {
            type: 'editMerchants',
            data: this.form
          })
          this.$store
            .dispatch('user/editMerchants', params)
            .then((response) => {

              setAccessToken(JSON.stringify(this.form))
              localStorage.setItem('active', '1')
              this.active = 1
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 100)
          this.loading = false
          return false
        }
      })
    },
    //获取店铺状态
    getMerchantsState(){
      const params={
        type:'getMerchantsState',
        data:{
          merchantsID:this.form.merchantsId
        }
      }
      this.$http
        .post(this.$api.getMerchantsState, params)
        .then((res) => {
          console.log("获取店铺状态")
          console.log(res)

          if(res.state=='5'){
            console.log(123);
            localStorage.setItem('active', '2')
            localStorage.setItem('refundReason', res.refundReason);
            localStorage.setItem('refundDesc', res.refundDesc);
            this.active = 2
          }
        })
    }
  }
}
</script>
<style lang="scss" scoped>
$bg: #D4E8FF;
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  font-family: "Microsoft YaHei";
  .login_header{
    width: 100%;
    height: 72px;
    position: relative;
    background: #fff;
    margin-bottom: 90px;
    .login_logo{
      display: flex;
      justify-content: space-between;
      padding-top: 10px;
      img{
        margin-left: 20px;
        width: 110px;
        vertical-align: middle;
      }
      .f_right{
        cursor: pointer;
        line-height: 50px;
      }
    }
    .qyzp{
      font-size: 16px;
      font-weight: 600;
      color: #000;
      margin-left: 16px;
      display: inline-block;
    }
    .w_1200{
      width: 1160px;
      margin: auto;
    }
    .login_logo_rgzp{
      height: 50px;
      line-height: 50px;
      margin-top: 100px;
      position: absolute;
      left: 200px;
      font-size: 22px;
      display: inline-block;
      font-weight: 600;
      padding-top: 20px;
      color: #000;
      float: left;
      .p_r_10{
        margin-right: 10px;
      }
    }
  }
  .login_main_bg{
    width: 1160px;
    position: relative;
    margin: auto;
    height: auto;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #fff;
    overflow: auto;
    .el-steps{
      width: 60%;
      margin: auto;
      margin-top: 100px;
    }
    .login_main_right{
      width: 100%;
      background-color: #ffffff;
      margin-top: 20px;
      .login_form{
        margin: auto;
        width: 60%;
        padding: 20px 0;
        .login_method{
          height: 38px;
          border-bottom: 2px solid #D8D8D8;
          position: relative;
          .c_p{
            float: left;
            width: 50%;
            font-size: 16px;
            color: rgba(74,74,74,1);
            position: relative;
            .line{
              border-bottom: 2px solid #1890FF;
              width: 120px;
              position: absolute;
              left: 0;
              top: 36px;
              display: block;
              height: auto;
            }
          }
        }
      }
    }
  }
  .footer_bg{
    height: 200px;
    background: url(../../assets/images/footer_bg.png) no-repeat center center;
  }
   ::v-deep {
      .el-form-item {
        padding-right: 0;
        margin: 20px 0;
        color: #454545;
        background: transparent;
        border: 1px solid transparent;
        border-radius: 2px;
        &__error {
          position: absolute;
          top: 100%;
          left: 18px;
          line-height: 18px;
        }
      }
      .el-form-item__content {
        display: flex;
        .el-radio-group{
          display: flex;
          margin-top: 18px;
          .el-radio{
            margin-right:10px;
          }
        }
      }

      .el-input {
        width: auto;
        box-sizing: border-box;
        input {
          height: 48px;
          line-height: 48px;
          background: rgba(247,248,252,1);
          border:1px solid rgba(238,238,238,1);
          border-radius: 4px;
          width: 360px;
          margin-right: 10px;
        }
      }
      .el-select{
        input{
          width: auto;
        }
      }
    }
    .svg-container {
      position: absolute;
      top: 14px;
      left: 15px;
      z-index:999;
      font-size: 16px;
      color: #d7dee3;
      cursor: pointer;
      user-select: none;
    }
    .login-btn{
      width: 200px;
      background: linear-gradient(90deg,rgba(29,135,255,1) 0%,rgba(59,114,246,1) 100%);
      box-shadow: 0px 5px 9px 0px rgba(104,153,221,0.2);
      border-radius: 28px;
      margin-right: 20px;
    }
}
.statusText{
  width: 200px;
  margin: auto;
  text-align: center;
  margin-bottom: 300px;
  padding-top: 100px;
}
.aInput_touxiang{
  width: 100px;
  position: relative;
  input{
   position: absolute;
    left: 0;
    width: 100px;
    overflow: hidden;
    opacity: 0;
  }
}
.el-upload-list__item{
  overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    img{
      width: 100%;
      height: 100%;
    }
}
</style>
