<template>
  <div class="defbb">
    <div class="defbb pt-spac pb-spac mt-spac">
      平台账户授权 [
      <span class="gray-color" :class="{ 'green-color': progress }">{{
        stateText
      }}</span>
      ]<span class="ml-spac p-wcolor" v-if="waring"> [ 提醒：请先绑定“授权手机号”！]</span>
    </div>
    <div class="items p-spacd2">
      <div class="center justify-between p-spacd2">
        <div class="label-color">授权手机号</div>
        <div>
          <span>{{ value }}</span>
          <el-button class="ml-spac" type="text" @click="saveTel()" v-if="!$props.readOnly">{{
            bindPhoneText
          }}</el-button>
        </div>
      </div>
      <div class="center justify-between p-spacd2 defbt">
        <div class="label-color">转账授权</div>
        <div
          class="p-color"
          :class="{ 'gray-color': !isBindPhone,'green-color':balanceAuthed,pointer:!$props.readOnly}"
          @click="authEvent(0)"
        >
          <i class="el-icon-loading
" v-if="$reqState($interfaces.pay.sign_balance_protocol).ing"></i>{{balanceAuthed?'已授权':'去授权'}}
        </div>
      </div>
      <div class="center justify-between p-spacd2 defbt" v-if="isDealer">
        <div class="label-color">提现授权</div>
        <div
          class="p-color"
          :class="{ 'gray-color': !isBindPhone,'green-color':withdrawAuthed,pointer:!$props.readOnly }"
          @click="authEvent(1)"
        >
          <i class="el-icon-loading
" v-if="$reqState($interfaces.pay.sign_balance_protocol).ing"></i>{{withdrawAuthed?'已授权':'去授权'}}
        </div>
      </div>
    </div>
    <el-dialog
      :append-to-body="true"
      title="修改手机号"
      :visible.sync="telDialogVisible"
      @close="closeEditTelDialog"
    >
      <el-steps :active="stepActive" align-center>
        <el-step title="解绑原手机号"></el-step>
        <el-step title="绑定新手机号"></el-step>
      </el-steps>
      <el-form
        :model="formStepOne"
        v-if="stepActive === 1"
        ref="formStepOne"
        :rules="formStepOneRules"
      >
        <el-form-item label="原手机号" prop="newTel">
          <el-input v-model="formStepOne.tel" disabled></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="formStepOne.code" clearable>
            <template slot="append"
              ><div class="getcode-btn" @click="getCodeEvent('formStepOne')">
                {{ codeBtn.text }}
              </div></template
            >
          </el-input>
        </el-form-item>
      </el-form>
      <el-form
        :model="formStepTwo"
        v-else-if="stepActive === 2"
        ref="formStepTwo"
        :rules="formStepTwoRules"
      >
        <el-form-item label="新手机号" prop="newTel">
          <el-input v-model="formStepTwo.newTel"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="formStepTwo.code" clearable>
            <template slot="append"
              ><div class="getcode-btn" @click="getCodeEvent('formStepTwo')">
                {{ codeBtn.text }}
              </div></template
            >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="footerBtnEvent">{{
          footerBtnText
        }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :append-to-body="true"
      title="绑定手机号"
      :visible.sync="bindTelDialogVisible"
      @close="closeBindTelDialog"
    >
      <el-form
        :model="formBindTel"
        ref="formBindTel"
        v-if="bindTelDialogVisible"
        :rules="formBindTelRules"
      >
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="formBindTel.tel"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code" clearable>
          <el-input v-model="formBindTel.code">
            <template slot="append"
              ><div class="getcode-btn" @click="getCodeEvent('formBindTel')">
                {{ codeBtn.text }}
              </div></template
            >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="bindTelEvent">确认绑定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { $sendVerificationCode, $unbindPhone, $bindPhone, $signContractQuery } from '@/service/pay'
export default {
  name: 'authorize',
  data() {
    return {
      authClicked: false,
      bindPhone: '66',
      formStepOne: {
        tel: '',
        code: ''
      },
      formStepOneRules: {
        code: [{ required: true, message: '此选项不能为空', trigger: 'blur' }]
      },
      formStepTwo: {
        newTel: '',
        code: ''
      },
      formStepTwoRules: {
        newTel: [
          { required: true, message: '此选项不能为空', trigger: 'blur' }
        ],
        code: [{ required: true, message: '此选项不能为空', trigger: 'blur' }]
      },
      telDialogVisible: false,
      bindTelDialogVisible: false,
      stepActive: 1,
      codeBtn: {
        text: '获取验证码',
        disabled: false
      },
      formBindTel: {
        tel: '',
        code: ''
      },
      formBindTelRules: {
        tel: [{ required: true, message: '此选项不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '此选项不能为空', trigger: 'blur' }]
      },
      footerBtnText: '下一步'
    }
  },
  props: {
    tradeType: {
      type: Number
    },
    value: {
      type: String,
      default: ''
    },
    carrierBalanceInfo: {
      type: Object,
      default: () => ({})
    },
    carrierWithdrawInfo: {
      type: Object,
      default: () => ({})
    },
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    /** 经销 */
    isDealer() {
      return this.$props.tradeType === 1
    },
    balanceAuthed() {
      return this.carrierBalanceInfo.balanceStatus === 2
    },
    withdrawAuthed() {
      return this.carrierWithdrawInfo.withdrawStatus === 2
    },
    progress() {
      let count = 0
      if (this.balanceAuthed) {
        count++
      }
      if (this.withdrawAuthed) {
        count++
      }
      return count
    },
    stateText() {
      let rv = '未完成'
      if (this.isDealer) {
        if (this.progress === 2) {
          rv = '已授权'
        } else {
          rv = `${this.progress}/2`
        }
      } else {
        if (this.carrierBalanceInfo.balanceStatus === 2) {
          rv = '已授权'
        }
      }
      return rv
    },
    isBindPhone() {
      return !!this.$props.value
    },
    bindPhoneText() {
      return this.isBindPhone ? '修改' : '绑定'
    },
    waring() {
      return !this.isBindPhone && this.authClicked
    }
  },
  created() {
    this.formStepOne.tel = this.$props.value
  },
  methods: {
    authEvent(type) {
      if (this.$props.readOnly) {
        return
      }
      if (!this.isBindPhone) {
        this.authClicked = true
        return
      }
      // 转账授权
      if (type === 0) {
        // 已授权
        if (this.carrierBalanceInfo.balanceStatus === 2) {
          this.$router.push('accountSetting/balanceProtocol')
        } else {
          const params = {
            source: 2,
            backUrl: window.location.href,
            jumpUrl: location.href.split('/#')[0] + '/#/signSuccess'
          }
          this.$http(this.$interfaces.pay.sign_balance_protocol, params).then(res => {
            window.location.href = res
          })
        }
      }
      // 提现授权
      if (type === 1) {
        // 已授权
        if (this.carrierWithdrawInfo.withdrawStatus === 2) {
          const params = {
            jumpUrl: window.location.href,
            source: 2
          }
          $signContractQuery(params).then(res => {
            if (res.code === 0) {
              window.location.href = res.data
            }
          })
        } else {
          const params = {
            source: 2,
            backUrl: window.location.href,
            jumpUrl: location.href.split('/#')[0] + '/#/signSuccess'
          }
          this.$http(this.$interfaces.pay.sign_withdraw_protocol, params).then(res => {
            window.location.href = res
          })
        }
      }
    },
    bindTelEvent() {
      this.$refs.formBindTel.validate((valid) => {
        if (valid) {
          const params = {
            verificationCode: this.formBindTel.code,
            phone: this.formBindTel.tel
          }
          $bindPhone(params).then((res) => {
            this.$message.success(res.message)
            this.$emit('input', this.formBindTel.tel)
            this.formStepOne.tel = this.formBindTel.tel
            this.bindTelDialogVisible = false
          })
        }
      })
    },
    saveTel() {
      if (this.isBindPhone) {
        this.telDialogVisible = true
        if (this.timer) {
          clearInterval(this.timer)
          this.codeBtn.text = '获取验证码'
          this.codeBtn.disabled = false
        }
      } else {
        this.bindTelDialogVisible = true
      }
    },
    getCodeEvent(param) {
      // let step = this.stepActive
      if (this.codeBtn.disabled) {
        return
      }
      if (param === 'formStepOne') {
        this.codeEvent(this.formStepOne.tel, param)
      } else if (param === 'formStepTwo') {
        this.$refs[param].validateField('newTel', (valid) => {
          if (!valid) {
            this.codeEvent(this.formStepTwo.newTel, param)
          } else {
            return null
          }
        })
      } else {
        this.$refs[param].validateField('tel', (valid) => {
          if (!valid) {
            this.codeEvent(this.formBindTel.tel, param)
          } else {
            return null
          }
        })
      }
    },
    codeEvent(tel, param) {
      let verificationCodeType = 0
      if (param === 'formStepTwo' || param === 'formBindTel') {
        verificationCodeType = 9
      } else {
        verificationCodeType = 6
      }
      const params = {
        phone: tel,
        verificationCodeType
      }
      $sendVerificationCode(params)
        .then((res) => {
          this.$message.success(res.message)
        })
        .catch((msg) => {
          clearInterval(this.timer)
          this.codeBtn.text = '获取验证码'
          this.codeBtn.disabled = false
        })
      let time = 60
      this.codeBtn.text = time + 's'
      this.timer = setInterval(() => {
        time--
        this.codeBtn.text = time + 's'
        this.codeBtn.disabled = true
        if (time < 0) {
          clearInterval(this.timer)
          this.codeBtn.text = '获取验证码'
          this.codeBtn.disabled = false
        }
      }, 1000)
    },
    footerBtnEvent() {
      if (this.stepActive === 1) {
        this.$refs.formStepOne.validateField('code', (valid) => {
          if (!valid) {
            const code = this.formStepOne.code
            const params = {
              phone: this.formStepOne.tel,
              verificationCode: code
            }
            $unbindPhone(params).then((res) => {
              if (res.code === 0) {
                this.stepActive = 2
                this.footerBtnText = '确认修改'
                this.$message.success(res.message)
                this.$emit('input', '')
                if (this.timer) {
                  clearInterval(this.timer)
                  this.codeBtn.text = '获取验证码'
                  this.codeBtn.disabled = false
                }
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            return null
          }
        })
      } else {
        this.$refs.formStepTwo.validate((valid) => {
          if (valid) {
            const params = {
              phone: this.formStepTwo.newTel,
              verificationCode: this.formStepTwo.code
            }
            $bindPhone(params).then((res) => {
              if (res.code === 0) {
                this.stepActive = 1
                this.formStepOne.code = ''
                this.formStepTwo.tel = ''
                this.formStepTwo.code = ''
                this.$message.success(res.message)
                this.$emit('input', this.formStepTwo.newTel)
                this.telDialogVisible = false
              } else {
                this.$message.error(res.message)
              }
            })
          }
        })
      }
    },
    closeBindTelDialog() {
      this.formBindTel.tel = ''
      this.formBindTel.code = ''
    },
    closeEditTelDialog() {
      this.formStepOne.code = ''
      this.formStepTwo.newTel = ''
      this.formStepTwo.code = ''
      this.stepActive = 1
      if (this.$refs.formStepOne) {
        this.$refs.formStepOne.clearValidate()
      }
      if (this.$refs.formStepTwo) {
        this.$refs.formStepTwo.clearValidate()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "submodule/utils/style/variables.scss";
.items {
  width: 400px;
}
.getcode-btn {
  width: 70px;
  text-align: center;
  cursor: pointer;
  color: $p-color;
}
</style>
