<!--
 * @Descripttion: 添加服务市场账号
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-10-16 14:22:10
 * @LastEditors: 无尘
 * @LastEditTime: 2020-10-19 15:40:22
-->
<!--
  使用帮助
  <add-market-dialog  @closeMarket="closeMarket"></add-market-dialog>
  import AddMarketDialog from '@/components/app/add-market-dialog.vue';
 -->
<template>
  <el-dialog title="绑定服务市场账号" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
    <div class="">
      <el-form ref="ruleForm" :model="marketForm" label-width="80px">
        <el-form-item label="手机号">
          <country-mobile :nation-code.sync="marketForm.nationCode" :input-width="480" :limit-class="'limit-color'" v-model="marketForm.phoneNumber" :holder="'请输入'"></country-mobile>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="marketForm.code" placeholder="请输入验证码" style="width:398px"></el-input><el-button class="m-l-10" :disabled="disableBtn" type="text" @click="sendCode()">{{ (disableBtn && countNum == 60) || (!disableBtn && !!countNum) ? '获取验证码' : countNum + 's' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loadBtn" @click="submitForm('ruleForm')">确认</el-button>
    </div>
  </el-dialog>
</template>
<script>
import countryMobile from '@/components/common/country-mobile.vue';
import { _debounce } from '@/common/js/public';
import fetch from '@/api/app-controls';
import PhoneNumber from 'awesome-phonenumber';
const { addMarketAccount, postPhoneCode, checkCode } = fetch;
import showMsg from '@/common/js/showmsg';
export default {
  name: 'AddMarketDialog',
  components: {
    countryMobile
  },
  data() {
    return {
      dialogVisible: true,
      loadBtn: false,
      marketForm: {
        nationCode: '86',
        phoneNumber: '',
        code: ''
      },
      disableBtn: true, // 发验证码.默认无手机号，不可点击
      countNum: 60,
    };
  },
  methods: {
    /**
     * @description: 倒计时
     * @author: 无尘
     */
    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);
    },
    /**
     * @description: 发送验证码
     * @returns {Boolean}
     * @author: 无尘
     */
    sendCode: _debounce(function() {
      const that = this;
      let { phoneNumber, nationCode } = that.marketForm;
      if (phoneNumber == '' ) {
        showMsg.showmsg('手机号不能为空', 'warning');
        return false;
      }
      const pn = new PhoneNumber('+' + nationCode + phoneNumber);
      if (!pn.isValid() || !pn.isMobile()) {
        showMsg.showmsg('手机号格式不正确', 'warning');
        return false;
      }
      let params = {
        phoneNumber,
        nationCode,
        type: 1
        // isTest: 1 , // 测试时使用
      };
      postPhoneCode(params)
        .then(res => {
          if (res.code == '0000') {
            that.disableBtn = true;
            that.countDown();
            const phone = String(phoneNumber);
            let handle = phone.substr(0, 3) + '****' + phone.substr(7, phone.length - 1);
            showMsg.showmsg(`已发送验证码到${nationCode || '86'}-${handle}`, 'success');
            return false;
          }
          showMsg.showmsg(res.message || '未知错误', 'warning');
        })
        .catch(function(error) {

        });
    }, 300),
    /**
     * @description: 校验验证码
     * @returns {Function}
     * @author: 无尘
     */
    checkCode() {
      const that = this;
      let { phoneNumber, nationCode, code } = that.marketForm;
      let params = {
        phoneNumber,
        nationCode,
        type: 1,
        code
      };
      return new Promise((resolve, reject) => {
        checkCode(params)
          .then(res => {
            if (res.code == '0000') {
              resolve(true);
              return false;
            }
            showMsg.showmsg(res.message || '未知错误', 'warning');
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    /**
     * @description: 保存
     * @param {String} formName
     * @author: 无尘
     */
    submitForm: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSave();
        }
      });
    }, 300),
    postSave() {
      const that = this;
      that.loadBtn = true;
      const data = {
      };
      addMarketAccount(data)
        .then(res => {
          that.loadBtn = false;
          if (res.code == '0000') {
            showMsg.showmsg('操作成功', 'success');
            that.$refs['ruleForm'].resetFields();
            that.$emit('closeMarket', true);
          }else {
            showMsg.showmsg(res.message || '未知错误', 'warning');
            that.$emit('closeMarket', true);
          }
        })
        .catch(error => {
          that.loadBtn = false;
        });
    },
    /**
     * @description: 关闭弹窗
     * @author: 无尘
     */
    handleClose() {
      const that = this;
      that.$emit('closeMarket');
    }
  },
  watch: {
    marketForm(obj) {
      const that = this;
      if (obj.phoneNumber) {
        that.disableBtn = false;
      }
    }
  },
};
</script>
<style lang="less" scoped>
.m-b-20 {
  margin-bottom: 20px;
}

</style>
