// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import common from './util/common'
// import MintUI from 'mint-ui'
import VueClipboard from 'vue-clipboard2'
import sa from 'sa-sdk-javascript';
import 'mint-ui/lib/style.css'
import scroll from "./base/scroll/scroll"
import {Popup, Lazyload, Button, Dialog, Toast} from 'vant';
import {getBillRefreshApi, getStatusWechatApi,getCourseInfoApi} from './service/api'
import './util/vancs.less'
import * as fundebug from 'fundebug-javascript';
import fundebugVue from 'fundebug-vue';

fundebug.apikey = '4d414770c72b034dfa896048206a72258ede4e4ad5f9c6c4320d19b7f91a567e';
fundebugVue(fundebug, Vue);

// import { init as initApm } from '@elastic/apm-rum'
// var apm = initApm({
//   // 设置所需的服务名称(允许使用的字符:a-z、A-Z、0-9、-、_ 和空格)
//   serviceName: 'ccqm',
//   // 设置定制 APM Server URL(默认值:http://localhost:8200)
//   serverUrl: 'http://apm.ops.changchangenglish.com/',
//   // 设置服务版本(源地图功能要求)
//   serviceVersion: ''
// })

Vue.config.productionTip = false;
//神策埋点
Vue.prototype.$sa = sa;
Vue.prototype.$sa.init({
  server_url: 'http://47.107.250.38:8106/sa?project=' + (process.env.NODE_ENV === 'production' ? "production" : "default"), // 替换成自己的神策地址
  show_log: false,// 打印console,自己配置,可以看到自己是否踩点成功,以及
  heatmap: {
    //是否开启点击图,默认 default 表示开启,自动采集 $WebClick 事件,可以设置 'not_collect' 表示关闭
    clickmap: 'default',
    //是否开启触达注意力图,默认 default 表示开启,自动采集 $WebStay 事件,可以设置 'not_collect' 表示关闭
    scroll_notice_map: 'default',
  },
  is_track_single_page: true
});
Vue.prototype.$sa.quick('autoTrack')
//神策埋点
Vue.use(VueClipboard);
Vue.use(Popup).use(Lazyload).use(Button).use(Dialog).use(Toast);
Vue.component('scroll', scroll);

// 支付宝支付完成,订单状态查询
let timer = null;
if (window.localStorage.out_trade_no) {
  timer = setInterval(() => {
    let outTradEno = JSON.parse(window.localStorage.out_trade_no);
    getBillRefreshApi({outTradeNo: outTradEno.out_trade_no}).then(res => {
      // 支付成功
      if (res.status === "SUCCESS") {
        getCourseInfoApi().then(response => {
          this.userCourse = JSON.parse(JSON.stringify(response));
          console.log(this.userCourse)
          localStorage.setItem("userCourse", JSON.stringify(this.userCourse));
          localStorage.setItem("buyindex", 1);
          Dialog.confirm({title: '标题', message: '支付成功', confirmButtonText: '去查看'}).then(() => {
            if (response.teacher_alias && response.teacher_alias.substr(0, 1) == 1 && outTradEno.goods_type != 4 && outTradEno.is_subscribe == 1) {
              clearInterval(timer);
              router.push({ name: "guide", query: {shopId: outTradEno.shopId} });
              localStorage.removeItem('out_trade_no')
            }else {
              if (res.buy_type == 1) {
                clearInterval(timer);
                router.push({name: "buySuccess", query: outTradEno});
                localStorage.removeItem('out_trade_no')
              } else {
                clearInterval(timer);
                router.push({name: "success", query: outTradEno});
                localStorage.removeItem('out_trade_no')
              }
            }
          }).catch(() => {
            clearInterval(timer);
            localStorage.removeItem('out_trade_no')
          });
        });
      } else if (res.status === "NO_SYNC") {
        Dialog.confirm({title: '标题', message: '您有一笔未支付的订单', confirmButtonText: '去查看'}).then(() => {
          clearInterval(timer);
          location.href = `http://${window.location.host}/#/guidelines?pay_url=${encodeURI(window.localStorage.pay_url)}`
          localStorage.removeItem('out_trade_no')
        }).catch(() => {
          clearInterval(timer);
          localStorage.removeItem('out_trade_no')
        });
      }
    })
  }, 6000)
}


// 全局错误日志
const errorHandler = (error, vm) => {
  Vue.prototype.$post(`api/client/report/errors/log`, {'routes_url': vm.$route.name, 'result_text': error.toString()})
}
Vue.config.errorHandler = errorHandler;
Vue.prototype.$throw = (error) => errorHandler(error, this);
Vue.prototype.$common = common
//VConsole关闭屏蔽代码
if (process.env.NODE_ENV != 'production') {
  new VConsole();
}

router.beforeEach((to, from, next) => {
  next()
  // chrome
  if (document.body.scrollTop !== null) {
    document.body.scrollTop = 0
  }
  // firefox
  if (document.documentElement !== null) {
    document.documentElement.scrollTop = 0
  }
})


new Vue({
  el: '#app',
  router,
  store,
  components: {App},
  template: '<App/>'
});


if (!Array.prototype.find) {
  Array.prototype.find = function (predicate) {
    'use strict';
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}