<template>
  <div class="course-baojia">
    <!--  第一行报价人数  -->
    <div class="baojia-counts">
      <i></i><span>已有 {{ sum }} 位客户成功报价</span>
    </div>
    <!--  手机号  -->
    <div class="baojia-phone">
      <el-input class="phone-input" v-model="baojia.phone" placeholder="请输入手机号(必填)"></el-input>
    </div>
    <!--  进度条  -->
    <div class="baojia-nc">
      <div id="baojiaId" class="nc-container"></div>
    </div>
    <!--  验证码+按钮  -->
    <div class="baojia-btns-code">
      <el-input v-model="baojia.code" placeholder="请输入验证码"/>
      <el-button class="code-btn" :disabled="btnTextDisabled" @click="checkVerification">{{ btnText }}</el-button>
    </div>
    <!--  称呼  -->
    <div class="baojia-custom-name">
      <el-input v-model="baojia.name" placeholder="请输入您的称呼(必填)"/>
    </div>
    <!--  按钮  -->
    <div class="baojia-btn">
      <el-button type="primary" @click="handleBaojia">预约咨询顾客</el-button>
    </div>
    <!--  底部滚动  -->
    <div class="baojia-bottom" v-if="userData.length">
      <div v-swiper:mySwiper="swiperOption" class="swiper-container">
        <div class="swiper-wrapper">
          <div class="swiper-slide div-row" v-for="(d,index) in userData" :key="index">
            <span class="icon-w1">
              <i></i>
              <span>{{ d.chenghu }}</span>
            </span>
            <span>{{ d.phone }}</span>
            <span>{{ d.timer }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Swiper, {Autoplay} from 'swiper';
Swiper.use([Autoplay]);
export default {
  name: "course-baojia",
  props: {
    sum: {
      type: Number,
      default: 0
    },
    tag: {
      type: String,
      default: 'dhl'
    },
    userList: {
      type: Array,
      default: [],
    }
  },
  components: {
    mySwiper: Swiper
  },
  computed: {
    curTag() {
      const tag = {
        'wkl': 1,
        'dhl': 2,
        'ppt': 3,
      }
      return tag[this.tag]
    },
    userData() {
      const userList = this.userList.filter(user => user.chenghu)
      return userList.map(user => {
        const chenghu = user.chenghu.length > 2 ? `${user.chenghu[0]}**` : `${user.chenghu[0]}*`;
        const ps = user.phone.split('');
        const phone = `${ps[0]}${ps[1]}${ps[2]}****${ps[7]}${ps[8]}${ps[9]}${ps[10]}`;
        return {chenghu, phone, timer: this.getTimeString(user['endSecond'])}
      })
    },
  },
  data() {
    return {
      baojia: {
        phone: '',
        code: '',
        name: ''
      },
      btnTextDisabled: false,
      btnText: '获取验证码',
      countdown: 60, // 60秒倒计时
      swiperOption: {
        autoplay: {
          delay: 2000,
        },
        height: 28,
        direction: 'vertical',
        paginationClickable: true,
        speed: 800,
        loop: true,
        observer: true,
        observeParents: true,
        autoplayDisableOnInteraction: false,
        allowTouchMove: false,
      },
      appKey: 'FFFF0N00000000007EC0',
    }
  },
  methods: {
    getTimeString(timer) {
      let m10 = 10 * 60 * 1000;
      let m30 = 30 * 60 * 1000;
      let h1 = 60 * 60 * 1000;
      let h6 = 6 * 60 * 60 * 1000;
      let d1 = 24 * 60 * 60 * 1000;
      let z1 = 7 * 24 * 60 * 60 * 1000;
      let M1 = 30 * 24 * 60 * 60 * 1000;

      if (timer > M1) {
        return `1个月前`
      }

      if (timer > z1) {
        return `1周前`
      }

      if (timer > d1) {
        return `1天前`
      }

      if (timer > h6) {
        return `6小时前`
      }

      if (timer > h1) {
        return `1小时前`
      }

      if (timer > m30) {
        return `30分钟前`
      }

      if (timer > m10) {
        return `10分中前`
      }

      return `刚刚`;
    },
    // 倒计时60秒
    setTime() {
      if (this.countdown === 0) {
        this.btnTextDisabled = false;
        this.btnText = '获取验证码';
        this.countdown = 60;
      } else if (this.countdown === -1) {
        this.btnTextDisabled = false;
        this.btnText = '获取验证码';
        this.countdown = 60;
      } else {
        this.btnTextDisabled = true;
        this.btnText = '重新发送(' + this.countdown + 's)';
        this.countdown--;
        this.countTimer = setTimeout(() => this.setTime(), 1000);
      }
    },
    /**
     * 串联加载指定的脚本
     * 串联加载[异步]逐个加载，每个加载完成后加载下一个
     * 全部加载完成后执行回调
     * @param array|string 指定的脚本们
     * @param function 成功后回调的函数
     * @return array 所有生成的脚本元素对象数组
     * 异步加载js后运行回调函数callback / scripts 为数组或字符串
     */
    seriesLoadScripts(scripts, callback) {
      if (typeof (scripts) != 'object') {
        var scripts = [scripts];
      }
      var HEAD = document.getElementsByTagName('head').item(0) || document.documentElement;
      var s = new Array(), last = scripts.length - 1, recursiveLoad = function (i) { //递归
        s[i] = document.createElement('script');
        s[i].setAttribute('type', 'text/javascript');
        s[i].onload = s[i].onreadystatechange = function () { //Attach handlers for all browsers
          if (!/*@cc_on!@*/0 || this.readyState == 'loaded' || this.readyState == 'complete') {
            this.onload = this.onreadystatechange = null;
            this.parentNode.removeChild(this);
            if (i != last) {
              recursiveLoad(i + 1);
            } else if (typeof (callback) == 'function') {
              callback();
            }
          }
        };
        s[i].setAttribute('src', scripts[i]);
        HEAD.appendChild(s[i]);
      };
      recursiveLoad(0);
    },
    // 滑块
    sliderFun() {
      const nc_token = [this.appKey, (new Date()).getTime(), Math.random()].join(':');
      const NC_Opt = {
        //声明滑动验证需要渲染的目标元素ID。
        renderTo: '#baojiaId',
        //应用类型标识。它和使用场景标识（scene字段）一起决定了滑动验证的业务场景与后端对应使用的策略模型。您可以在人机验证控制台的配置管理页签找到对应的appkey字段值，请务必正确填写。
        appkey: this.appKey,
        //使用场景标识。它和应用类型标识（appkey字段）一起决定了滑动验证的业务场景与后端对应使用的策略模型。您可以在人机验证控制台的配置管理页签找到对应的scene值，请务必正确填写。
        scene: 'nc_message',
        //滑动验证码的主键，请勿将该字段定义为固定值。确保每个用户每次打开页面时，其token值都是不同的。系统默认的格式为：”您的appkey”+”时间戳”+”随机数”。
        token: nc_token,
        //滑动条的宽度。
        customWidth: 300,
        //业务键字段，可为空。为便于线上问题的排查，建议您按照线上问题定位文档中推荐的方法配置该字段值。
        trans: {'key1': 'code0'},
        //通过Dom的ID属性自动填写trans业务键，可为空。建议您按照线上问题定位文档中推荐的方法配置该字段值。
        elementID: ['usernameID'],
        //是否自定义配置底层采集组件。如无特殊场景，请使用默认值（0），即不自定义配置底层采集组件。
        is_Opt: 0,
        //语言。PC端Web页面场景默认支持18国语言，详细配置方法请参见自定义文案与多语言文档。
        language: 'cn',
        //是否启用。一般情况，保持默认值（true）即可。
        isEnabled: true,
        //内部网络请求的超时时间。一般情况建议保持默认值（3000ms）。
        timeout: 3000,
        //允许服务器超时重复次数，默认5次。超过重复次数后将触发报错。
        times: 5,
        //用于自定义滑动验证各项请求的接口地址。一般情况，请勿配置该参数。
        apimap: {
          // 'analyze': '//a.com/nocaptcha/analyze.jsonp',
          // 'get_captcha': '//b.com/get_captcha/ver3',
          // 'get_captcha': '//pin3.aliyun.com/get_captcha/ver3'
          // 'get_img': '//c.com/get_img',
          // 'checkcode': '//d.com/captcha/checkcode.jsonp',
          // 'umid_Url': '//e.com/security/umscript/3.2.1/um.js',
          // 'uab_Url': '//aeu.alicdn.com/js/uac/909.js',
          // 'umid_serUrl': 'https://g.com/service/um.json'
        },
        //前端滑动验证通过时会触发该回调参数。您可以在该回调参数中将请求标识（token）、会话ID（sessionid）、签名串（sig）字段记录下来，随业务请求一同发送至您的服务端调用验签。
        callback: (data) => {
          this.sliderData = Object.assign({}, data, {
            appkey: NC_Opt.appkey,
            scene: NC_Opt.scene,
          });
          console.log(this.sliderData);
        },
      };
      let date11 = () => {

        let _date = new Date();
        let year = _date.getFullYear().toString();
        let month = _date.getMonth().toString();
        let day = _date.getDate().toString();
        let a = _date.getHours().toString();
        let b = _date.getMinutes().toString();
        let c = _date.getSeconds().toString();

        return year + month + day + a + b + c;
      };
      let c = date11();
      const scripts = [
        `https://g.alicdn.com/sd/ncpc/nc.js?t=${c}`,
      ];
      this.seriesLoadScripts(scripts, function () {
        var nc = new noCaptcha(NC_Opt);
        nc.upLang('cn', {
          _startTEXT: '请按住滑块，拖动到最右边',
          _yesTEXT: '验证通过',
          _error300: '哎呀，出错了，点击<a href="javascript:__nc.reset()">刷新</a>再来一次',
          _errorNetwork: '网络不给力，请<a href="javascript:__nc.reset()">点击刷新</a>',
        });
      });

    },
    // 验证码
    checkVerification() {
      if (this.sliderData.appkey === undefined) {
        this.$message.error('请先通过滑块校验');
        return;
      }
      this.$axios.$post(`/develop/exists`, {phone: this.baojia.phone}).then(res => {

        if (res.code === 0 && res.data) {

          let req = {
            'appkey': this.sliderData.appkey,
            'phone': this.baojia.phone,
            'scene': this.sliderData.scene,
            'sessionid': this.sliderData.csessionid,
            'sig': this.sliderData.sig,
            'token': this.sliderData.token,
            'type': 0,
          }
          this.$axios.$post('/sendCode', req).then(res => {
            if (res.code === 0 && res.data) {
              this.setTime();
            } else {
              this.$message.error(res.msg || '手机号已存在');
            }
          })
        } else {
          this.$message.error(res.msg || '手机号已存在');
          return false;
        }

      })
    },
    // 申请报价
    handleBaojia() {
      const opt = {
        type: this.curTag,
        phone: this.baojia.phone,
        code: this.baojia.code,
        chenghu: this.baojia.name
      }

      if (!this.baojia.phone) {
        this.$message.error("请填写手机号");
        return;
      }
      if (!this.baojia.code) {
        this.$message.error("验证码不能为空");
        return;
      }
      if (!this.baojia.name) {
        this.$message.error("请输入您的称呼");
        return;
      }

      this.confirmTl(opt)
    },
    confirmTl(options){
      // 请求后台
      this.$axios.$post('/develop/add',options).then(res=>{
        if (res.code === 0 && res.data) {
          this.$message.success('申请成功');
          this.resetCode();
        } else {
          this.$message.error('申请失败');
          this.resetCode();
        }
      });
    },
    resetCode() {
      this.btnTextDisabled = false;
      this.btnText = '获取验证码';
      this.countdown = 60; // 60秒倒计时
      this.swiperOption = {};
      this.countTimer && clearTimeout(this.countTimer);
    }
  },
  mounted() {
    this.sliderFun();
  }
}
</script>

<style lang="scss" scoped>
.course-baojia {
  box-sizing: border-box;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: -8px 0px 35px 8px rgba(196, 198, 200, 0.34);
  overflow: hidden;
  position: relative;
  width: 379px;
  height: 471px;
  padding: 34px 22px;

  .baojia-counts {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    background-color: rgba(73, 172, 252, 0.08);
    border-radius: 6px;
    margin-bottom: 22px;
    width: 335px;
    height: 44px;

    > i {
      display: inline-block;
      background-image: url("~static/images/client/course/animation/fire.png");
      background-size: contain;
      background-repeat: no-repeat;
      margin: 0 5px 0 14px;
      width: 19px;
      height: 22px;
    }

    > span {
      font-size: 14px;
      font-weight: 400;
      text-align: left;
      color: #2779f7;
    }
  }

  .baojia-phone {
    margin-bottom: 17px;

    .phone-input {
      border: 1px solid #d3d3d3;
      border-radius: 6px;
      width: 335px;
      height: 50px;

      ::v-deep .el-input__inner {
        border: none;
        height: 50px;
        line-height: 50px;
      }
    }
  }

  .baojia-nc {
    background: #f7f7f7;
    margin-bottom: 22px;
    width: 335px;
    height: 30px;

    .nc-container {
      ::v-deep .nc_wrapper {
        // 此处id会随机生成 借用class + important 冲掉 id权重
        width: 100% !important;
      }
    }


  }

  .baojia-btns-code {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    width: 100%;

    ::v-deep .el-input {
      border: 1px solid #d3d3d3;
      border-radius: 6px;
      width: 200px;
      height: 50px;
    }

    ::v-deep .el-input__inner {
      border: none;
      height: 50px;
      line-height: 50px;
    }

    .code-btn {
      background: linear-gradient(to right, #247bfa 0%, #4baffc 100%);
      border-radius: 6px;
      box-shadow: 0 0 0px 0 #257df9;
      border: none;
      width: 123px;
      height: 50px;
      margin-left: 10px;

      ::v-deep span {
        color: #fff;
      }
    }
  }

  .baojia-custom-name {
    border: 1px solid #d3d3d3;
    border-radius: 6px;
    margin-bottom: 20px;
    width: 335px;
    height: 50px;

    ::v-deep .el-input__inner {
      border: none;
      height: 50px;
      line-height: 50px;
    }
  }

  .baojia-btn {

    ::v-deep .el-button {
      background: linear-gradient(to right, #247bfa 0%, #4baffc 100%);
      border-radius: 6px;
      box-shadow: 0 0 0px 0 #257df9;
      width: 335px;
      height: 50px;

      span {
        font-size: 16px;
        font-weight: 400;
        text-align: left;
        color: #ffffff;
      }
    }
  }

  .baojia-bottom {
    background: rgba(39, 127, 250, 0.07);
    position: absolute;
    bottom: 0;
    left: 0;
    width: 379px;
    height: 36px;

    .icon-w1 {
      display: flex;
      align-items: center;
      justify-content: flex-start;

      i {
        background-image: url('~static/images/client/course/animation/yinling.png');
        display: inline-block;
        width: 13px;
        height: 14px;
        margin: 13px 15px 0 28px;

      }

      span {
        margin-top: 13px;
      }

    }

    .swiper-slide {
      display: flex;
      justify-content: space-between;
      align-items: center;

      > span {
        font-size: 14px;
        font-weight: 400;
        text-align: left;
        color: #2779f7;

        &:nth-child(2), &:nth-child(3) {
          margin-top: 13px;
          margin-right: 20px;
        }
      }
    }
  }


  @media (max-width: 768px){
    & {
      width: 90%;

      .baojia-counts {
        width: 100%;
      }

      .baojia-phone {
        .phone-input {
          width: 100%;
        }
      }

      .baojia-nc {
        width: 100%;
      }

      .baojia-custom-name {
        width: 100%;
      }

      .baojia-btn {
        ::v-deep .el-button {
          width: 100%;
        }
      }

      .baojia-bottom {
        width: 100%;
      }
    }
  }

}
</style>
