<template>
  <el-dialog width="600px" title="授权校验" class="authMerchant-dailog" :visible.sync="memberVisible" append-to-body :before-close="handleClose">
    <div>
      <div role="alert" class="el-alert el-alert--info flex w-327 bg-F0F5FF">
        <i class="el-alert__icon el-icon-warning font-12 color-2f54eb m-r-9"></i>
        <span class="el-alert__title color-303133 font-13">授权商户需要校验GIC商户超级管理员手机号 </span>
      </div>
      <el-form :model="partForm" :rules="rules" ref="form" label-width="140px" class="dialog-form">
        <el-form-item label="超级管理员">
          {{ partForm.clerkName | formatName }}
        </el-form-item>
        <el-form-item label="超级管理员手机号" prop="">
          <span v-if="partForm.phoneNumber">{{ partForm.nationCode }}-</span>{{ partForm.phoneNumber | formatPhoneNum }} <el-button class="m-l-35" :disabled="!partForm.phoneNumber" type="text" @click="sendCode()">{{ (disableBtn && countNum == 60) || (!disableBtn && !!countNum) ? '点击短信验证' : countNum + 's' }}</el-button>
        </el-form-item>
        <el-form-item label="短信验证码" prop="code">
          <el-input style="width: 180px;line-height:40px;" maxlength="20" v-model="partForm.code" placeholder="请输入验证码"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel('form')">取消</el-button>
      <el-button type="primary" @click="submitForm('form')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
// import PhoneNumber from 'awesome-phonenumber';
export default {
  name: 'authMerchant-dailog',
  components: {},
  props: {
    item: {
      type: Object,
      default() {
        return { version: '3.0', clerkName: '', enterpriseId: '', enterpriseName: '', nationCode: '86', phoneNumber: '', code: '' };
      }
    }
  },
  data() {
    return {
      wxEnterpriseId: JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId,
      memberVisible: true,
      partForm: {},
      rules: {
        code: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }
        ]
      },
      disableBtn: true, // 发验证码.默认无手机号，不可点击
      countNum: 60
    };
  },
  methods: {
    /**
     * 倒计时
     */
    countDown() {
      const that = this;
      let time = setInterval(function() {
        if (that.countNum === 0) {
          clearInterval(time);
          that.countNum = 60;
          that.disableBtn = false;
          return false;
        }
        that.countNum--;
      }, 1000);
    },
    /**
     * 发送验证码
     */
    sendCode: _debounce(function() {
      const that = this;
      if (that.partForm.phoneNumber == '' || isNaN(String(that.partForm.phoneNumber))) {
        showMsg.showmsg(`超级管理员手机号不正确，请到 GIC 商户后台修改`, 'warning');
        return false;
      }
      /* if (that.partForm.nationCode == '' || isNaN(String(that.partForm.nationCode))) {
        showMsg.showmsg(`国家码不存在`, 'warning');
        return false;
      } */
      let params = {
        phoneNumber: that.partForm.phoneNumber,
        nationCode: that.partForm.nationCode || '86',
        type: 1,
        enterpriseId: this.partForm.enterpriseId
        // isTest: 1 // 测试时使用
      };
      getRequest('/haoban-manage3-web/send-code', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.disableBtn = true;
            that.countDown();
            const phone = String(that.partForm.phoneNumber);
            let handle = phone.substr(0, 3) + '****' + phone.substr(7, phone.length - 1);
            showMsg.showmsg(`已发送验证码到${that.partForm.nationCode || '86'}-${handle}`, 'success');
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }, 300),
    /**
     * 校验验证码
     */
    checkCode() {
      const that = this;
      let params = {
        phoneNumber: that.partForm.phoneNumber,
        nationCode: that.partForm.nationCode,
        type: 1,
        code: that.partForm.code
      };

      return new Promise((resolve, reject) => {
        getRequest('/haoban-manage3-web/validate-code', params)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              resolve(true);
              return false;
            }
            errMsg.errorMsg(resData);
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    /**
     * 关闭弹窗
     */
    handleClose(done) {
      const that = this;
      that.$refs['form'].resetFields();
      that.$emit('refreshData', 'close');
      done();
    },
    cancel() {
      const that = this;
      that.$refs['form'].resetFields();
      that.$emit('refreshData', 'close');
    },
    /**
     * 确定保存
     */
    async submitForm(form) {
      const that = this;
      if (!that.partForm.enterpriseId) {
        return false;
      }
      that.$refs[form].validate(async valid => {
        if (valid) {
          const flag = await that.checkCode();
          if (!flag) {
            return false;
          }
          that.$emit('refreshData', 'success');
        } else {
          return false;
        }
      });
    },
    /**
     * 获取数据
     */
    getData() {
      const that = this;
      let params = {
        staffId: that.partForm.staffId
      };
      getRequest('/haoban-manage3-web/staff-add', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.partForm = resData.result;
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    item(newData) {
      const that = this;
      if (Object.keys(this.item).length) {
        that.$nextTick(() => {
          that.partForm = JSON.parse(JSON.stringify(this.item));
        });
      }
    }
  },
  mounted() {
    const that = this;
    if (Object.keys(that.item).length) {
      that.$nextTick(() => {
        that.partForm = JSON.parse(JSON.stringify(this.item));
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.m-l-35 {
  margin-left: 35px;
}
.m-r-9 {
  margin-right: 9px;
}
.w-327 {
  width: 327px;
}
.font-12 {
  font-size: 12px;
}
.el-alert--info {
  height: 32px;
  padding: 0 0 0 17px;
  margin-bottom: 12px;
  background: #f0f5ff;
  border: 1px solid #85a5ff;
  border-radius: 2px;
}
.authMerchant-dailog {
  >>> .el-dialog__body {
    padding-top: 8px;
    padding-left: 21px;
  }
  >>> .el-form-item {
    margin-bottom: 0;
    >>> .el-form-item__label {
      line-height: 40px;
    }
  }
  >>> .el-dialog__footer {
    padding-top: 9px;
  }
}
</style>
<style>
.authMerchant-dailog .el-form-item .el-form-item__label {
  line-height: 40px;
}
</style>
