import VConsole from "vconsole";
import store from "../store/store";
import Vue from 'vue'
import axios from "axios";
import LzEvent from 'lz-event-tracking/lib/vue';
// import LzEvent from './LzEvent/vue';

import apis1 from './apis1.js';
// import {
//   jdReminder
// } from './jdReminderNew.js'
const getCookie = name => {
  //获取cookie
  var strCookie = document.cookie;
  var arrCookie = strCookie.split("; ");
  for (var i = 0; i < arrCookie.length; i++) {
    var arr = arrCookie[i].split("=");
    if (arr[0] == name) return arr[1];
  }
  return "";
};
const getUrlQueryValueByKey = (keyName, url) => {
  /*获取url地址栏中参数值，url为可选，默认为当前页面url*/
  if (!url) {
    url = location.href;
  }
  var reg = new RegExp("(^|[&?])" + keyName + "=([^&]*)(&|$)");
  var r = url.match(reg); //search,查询？后面的参数，并匹配正则
  if (r != null) return unescape(r[2]);
  return "";
};
// 助力之后去掉地址栏的shareUserId
const removeUrlShareUserId =(url) =>{
  if (!url) {
    url = location.href;
  }
  url = url.replace(/shareUserId=.[^&]+&?/, '')
 return location.href = url
}

// 设置debug工具
if (getUrlQueryValueByKey("isDebug") === "true") {
  new VConsole();
}

// 返回当前链接全部参数的一个对象
const getQueryObject = () => {
  let obj = {};
  let query = location.search.replace("?", "").split("&");

  query.forEach((item) => {
    const temp = item.split("=");
    obj[temp[0]] = temp[1];
  });
  return obj;
};

//组装json数据的style样式
const styleUtil = (styleJson) => {
  var json = styleJson
  var sty1 = ''
  for (var key in json) {
    console.log(key + ':' + json[key])
    sty1 = key + ':' + json[key] + ';' + sty1
  }
  return sty1;
};

//客态变主态
const changeStates = () => {
  apis1.changeState(data => {
    console.log(data, '客态 客变主111')
    if (data.resp_code == 0) {
      if (data.data.joinCodeInfo.joinCode == '1001') {
        // callback && callback('success');
        // this.$router.push({ path: '/index', query: { activityType: this.activityType, templateId: this.templateId, activityId: store.state.activityId, shareUserId: this.shareUserId1 } });
      } else if (data.data.joinCodeInfo.joinCode == '1002') {
        // callback && callback(data.data);
        // joinVipService.create(datas, submit => {
        //     console.log("121212")
        // })
        let comCreate = './comCreate.js'
        console.log(comCreate, '客态 客变主222')
      } else if (data.data.joinCodeInfo.joinCode == '1003') {

        console.log(joinVipService, '客态 客变主333')
        // callback && callback(data.data);
        // joinVipService.create(datas, submit => {
        //     console.log("121212")
        // })
      }

    } else {
      Notify(data.resp_msg);
    }
  })
};

//开卡
const goToOpenCard = url => {
  window.halfScreenCallback = function(result) {
  let resultObj = JSON.parse(result)
  if(window.navigator.userAgent.indexOf('Android') > -1){
    let datas = JSON.parse(resultObj.data)
    resultObj.data = datas
  }
  if (resultObj.status == '0') {
    if(resultObj.data.type == 'onLayerReady'){
      // alert('半屏弹窗资源加载完毕')
    }
    if(resultObj.data.type == 'layerShowSucces'){
      // alert('成功获取弹窗id：'+resultObj.data.layerId)
    }
    if(resultObj.data.type == 'onLayerLoading'){
      // alert('开始加载弹窗回调')
    }
    if(resultObj.data.type == 'clickClose'){
      alert('点击了关闭弹窗按钮')
    }
    if(resultObj.data.type == 'layerClose'){
      // alert('已经关闭了半屏弹窗')
      // location.href = JSON.parse(sessionStorage.getItem('joinInfo')).actUrl
      location.href = sessionStorage.getItem('oldUrl')
    }
  } else if (resultObj.status == '-1') {
    console.log("错误,错误信息:"+ resultObj.msg)
  } else if (resultObj.status == '-2') {
    console.log("方法不存在")
  }
}
  // console.log(url, '开卡链接')
  // let urlHerf = sessionStorage.getItem('oldUrl')
  // console.log(urlHerf, '开卡链接')
  // if (url.indexOf('shopmember') != -1) {
  //   location.href = url + '&returnUrl=' + encodeURIComponent(urlHerf) + '&shareUuid=' + store.state.shareUserId;
  // } else {
  //   location.href = url + '&rn_returnUrl=' + encodeURIComponent(urlHerf) + '&shareUuid=' + store.state.shareUserId;
  // }
  
  //京东app版本号大于13.6.3才支持使用半屏弹窗
  const inJdApp = jmfe.isApp('jd') 
  const currentVersion = jmfe.getAppVersion('jd')
  const compareResult = jmfe.versionCompare(currentVersion, '13.6.2')
  const hasNewOpenCardUrl =  JSON.parse(sessionStorage.getItem('joinInfo')).joinInfo.newOpenCardUrl
  if(!jmfe || !jmfe.isApp || !jmfe.getAppVersion || !jmfe.versionCompare || !window.XWebView || !window.XWebView.callNative){
    console.log(jmfe,'请检查jdsdk是否被正确引用，请检查系统版本是否为鸿蒙。')
    //版本号不满足要求，使用默认的入会跳转方式
    let urlHerf = sessionStorage.getItem('oldUrl')
    if (url.indexOf('shopmember') != -1) {
      location.href = url + '&returnUrl=' + encodeURIComponent(urlHerf) + '&shareUuid=' + store.state.shareUserId + '&activityId=' + sessionStorage.getItem('activityId');
    } else {
      location.href = url + '&rn_returnUrl=' + encodeURIComponent(urlHerf) + '&shareUuid=' + store.state.shareUserId + '&activityId=' + sessionStorage.getItem('activityId');
    }
    return
  }
  if(!inJdApp || compareResult != 1 || !hasNewOpenCardUrl){
    //版本号不满足要求，使用默认的入会跳转方式
    let urlHerf = sessionStorage.getItem('oldUrl')
    console.log(urlHerf, '开卡链接')
    if (url.indexOf('shopmember') != -1) {
      location.href = url + '&returnUrl=' + encodeURIComponent(urlHerf) + '&shareUuid=' + store.state.shareUserId + '&activityId=' + sessionStorage.getItem('activityId');
    } else {
      location.href = url + '&rn_returnUrl=' + encodeURIComponent(urlHerf) + '&shareUuid=' + store.state.shareUserId + '&activityId=' + sessionStorage.getItem('activityId');
    }
  }else{
    let cardUrl = JSON.parse(sessionStorage.getItem('joinInfo')).joinInfo.newOpenCardUrl + '&memberSceneType=xview&closeBtn=0' + '&activityId=' + sessionStorage.getItem('activityId')
    let params = {
        url:encodeURIComponent(cardUrl),
        targetType:2,
        heightRateFromContainer:0.7,
        layoutType:1,
        backgroundColor:'0000009b',
        pageMultiTimes:1,
        blankCls:1,
        needAutoClose:1,
        hideNativeCloseBtn:0,
        // targetName:JSON.parse(sessionStorage.getItem('joinInfo')).actUrl,
      }
      window.XWebView && window.XWebView.callNative(
        "JDXViewPlugin",//默认参数，固定值JDXViewPlugin
        "showXView2",//默认参数，固定值showXView2
        JSON.stringify(params),//上面的参数params转成JSON字符串
        "halfScreenCallback",//上面定义好的回调函数
        "1"//默认参数，固定值1
      )
  }
};



// 跳转店铺方法
const goToShopPage = shopId => {
  if (shopId) {
    // trackLog(shopId);
    // writePersonInfo(4);
    // reportClick("v_shop", shopId);
    if (store.state.clientType == "WeChat") {
      if (store.state.isMiniProgram) {
        wx.miniProgram.navigateTo({
          url: "/pages/shop/index/index?shopId=" + shopId
        });
      } else {
        if(sessionStorage.getItem('shopCps')){
          // location.href = sessionStorage.getItem('shopCps')
          location.href = "https://wq.jd.com/mshop/gethomepage?shopId=" + shopId;
        }else{
          location.href = "https://wq.jd.com/mshop/gethomepage?shopId=" + shopId;
        }
      }
    } else {
      if(sessionStorage.getItem('shopCps')){
        // location.href = sessionStorage.getItem('shopCps')
        location.href = "https://shop.m.jd.com/?shopId=" + shopId;
      }else{
        location.href = "https://shop.m.jd.com/?shopId=" + shopId;
      }
    }
  }
};


// 跳转商品方法
const goToSkuPage = skuId => {
  console.log('*****', skuId)
  if (skuId) {
    // trackLog(skuId);
    // writePersonInfo(5);
    // reportClick("v_sku", store.state.shopId, skuId);
    if (store.state.clientType == "WeChat") {
      if (store.state.isMiniProgram ) {
        wx.miniProgram.navigateTo({
          url: "/pages/item/detail/detail?sku=" + skuId
        });
      } else {
        location.href = "https://wq.jd.com/item/view?sku=" + skuId;
      }
    } else {
      location.href =
        "https://item.m.jd.com/product/" +
        skuId +
        ".html?wjfrom=ISV_2180A2AFA5B2452F9061C01C053C4756_WX&wjwxpubid=wxd9fd3549c5fdb283&wjunionid=&wjopenid=";

      let a = "https://item.m.jd.com/product/" +
        skuId +
        ".html?wjfrom=ISV_2180A2AFA5B2452F9061C01C053C4756_WX&wjwxpubid=wxd9fd3549c5fdb283&wjunionid=&wjopenid=";
      console.log(a, 'a')
    }
  }
};
// 跳转商品新方法
const newToSkuPage = row => {
  console.log('*****', row)
  if(row.skuId){
    if (store.state.clientType == "WeChat") {
      if (store.state.isMiniProgram ) {
        wx.miniProgram.navigateTo({
          url: "/pages/item/detail/detail?sku=" + row.skuId
        });
      } else {
        if(row.cpsUrl){
          // location.href = row.cpsUrl
          location.href = "https://wq.jd.com/item/view?sku=" + row.skuId;
        }else{
          location.href = "https://wq.jd.com/item/view?sku=" + row.skuId;
        }
      }
    }else{
      if(row.cpsUrl){
        // location.href = row.cpsUrl
        location.href =
        "https://item.m.jd.com/product/" +
        row.skuId +
        ".html?wjfrom=ISV_2180A2AFA5B2452F9061C01C053C4756_WX&wjwxpubid=wxd9fd3549c5fdb283&wjunionid=&wjopenid=";
      }else{
        console.log('okokok')
        location.href =
        "https://item.m.jd.com/product/" +
        row.skuId +
        ".html?wjfrom=ISV_2180A2AFA5B2452F9061C01C053C4756_WX&wjwxpubid=wxd9fd3549c5fdb283&wjunionid=&wjopenid=";
      }
    }
  }
}
// 跳转到通天塔，会场方法
const goToActive = url => {
  let tempUrl = url;

  if (url) {
    // reportClick("v_channel", store.state.shopId);
    if (store.state.clientType == "WeChat") {
      if (store.state.isMiniProgram) {
        tempUrl = tempUrl.replace("/mall", "/mini");
        tempUrl = tempUrl.replace("/wq", "/mini");
        tempUrl = tempUrl + "?wxAppName=jd";

        wx.miniProgram.navigateTo({
          url: "/pages/h5/index?encode_url=" + encodeURIComponent(tempUrl)
        });
      } else {
        location.href = url;
      }
    } else {
      location.href = url;
    }
  }
};


//埋点初始化
const initBuriedPoint = loginData => {
  console.log(loginData,'登陆后的初始化埋点数据');

  if (store.state.clientType == '01') {
    var channel = 'app'
  } else if (store.state.clientType == '02') {
    var channel = 'wechat'
  } else if (store.state.clientType == '03') {
    var channel = 'qq'
  }
  let cur_url = location.href;
  var templatePage = getUrlQueryValueByKey("templatePage", cur_url);
  var activityType = getUrlQueryValueByKey("activityType", cur_url);
  var nodeId = getUrlQueryValueByKey("nodeId", cur_url);

  console.log(activityType,'activityType登陆后的初始化埋点数据');


  if (templatePage) {
    this.isTemplatePage = true;
  } else {
    this.isTemplatePage = false;
  }
  if (this.isTemplatePage) {

  } else {

    setTimeout(() => {
      LzEvent.setBaseInfo({
        shopId: loginData.shopId, // 店铺标识，不可以为空
        customerId: loginData.customerId, // C端用户唯一身份标识customerId，不可以为空
        nickName: loginData.nickName, // 用户昵称，不可以为空
        // 以下信息京东数据回流的时候需要使用
        luze: {
          version: '', // 版本号，可以为空
          versionName: '', // 版本名称，可以为空
          nodeId: nodeId //store.state.nodeId // 页面的节点ID，参见：https://lucidata.yuque.com/staff-qvc012/yyknyp/ougm8i#Og6s
        },
        jd: {
          pin: loginData.userPin,
          activityId: loginData.jdActivityId,
          activityType:activityType, //sessionStorage.getItem('jdActType'),
          channel: 8,
          shareUserId: loginData.shareUserPin
        }
      })
    }, 300)
  }

}

//手机号校验
const phoneCheck = (value) => {
  const reg = /^[1][3-9][0-9]{9}$/;
  if (value == '' || value == undefined || value == null) {
    callback();
  } else {
    if ((!reg.test(value)) && value != '') {
      // callback(new Error('请输入正确的电话号码'));
      return false;
    } else {
      return true;
    }
  }
}

// 邮箱校验
const emailCheck = (value) => {
  const reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,8})$/;
  if (value == '' || value == undefined || value == null) {
    callback();
  } else {
    if ((!reg.test(value)) && value != '') {
      return false;
    } else {
      return true;
    }
  }
}

//特殊字符和表情符校验
const checkEmoj = (substring) => {
  console.log(substring, 'substring')
  var reg = /[\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/;
  // var reg_mark = /[`~!@#$%^&*()+=|{}':;',/\/\[\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]/
  if (reg.test(substring)) { //|| reg_mark.test(substring)
    // alert("输入框内有特殊表情，请删除重新输入")
    return false;
  } else {
    return true;
    // alert("验证通过")
  }
}



const checkInput = (str) => {

  var reg = /[\u4E00-\u9FA5a-zA-Z0-9-\d_,—,-,_,(,),(),（）]/;

  var count = 0
  for (var i = 0; i < str.length; i++) {
    if (reg.test(str[i])) {
      count = count + 1
    }
  }
  if (count == str.length) {
    return true
  } else {
    return false
  }

}

const checkQuestionAnswerInput = (str) => {
  if (str === undefined || str === null) {
    return true
  }

  var reg = /(\ud83c[\udc00-\udfff])|(\ud83d[\udc00-\udfff])|(\ud83e[\udc00-\udfff])|[\u00a9\u00ae\u203c\u2049\u2122\u2139\u2194-\u21aa\u231a-\u231b\u2328\u23cf\u23e9-\u23f3\u23f8-\u23fa\u24c2\u25aa-\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614-\u2615\u2618\u261d\u2620\u2622-\u2623\u2626\u262a\u262e-\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665-\u2666\u2668\u267b\u267e-\u267f\u2692-\u2697\u2699\u269b-\u269c\u26a0-\u26a1\u26aa-\u26ab\u26b0-\u26b1\u26bd-\u26be\u26c4-\u26c5\u26c8\u26ce-\u26cf\u26d1\u26d3-\u26d4\u26e9-\u26ea\u26f0-\u26f5\u26f7-\u26fa\u26fd\u2702\u2705\u2708-\u270d\u270f\u2712\u2714\u2716\u271d\u2721\u2728\u2733-\u2734\u2744\u2747\u274c\u274e\u2753-\u2755\u2757\u2763-\u2764\u2795-\u2797\u27a1\u27b0\u27bf\u2934-\u2935\u2b05-\u2b07\u2b1b-\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299]\ufe0f|[0-9#*]\ufe0f?\u20e3/;
  return !reg.test(String(str))
}

//兑换plus会员卡和爱奇艺会员卡
const exchangePrize = () => {
  location.href = 'http://asset-m.jd.com/'
}

//活动提醒
const acReminder = (remindOption, callback) => {
  // console.log('122222222')
  let remindOption1 = {
    // url: '3.cn/100ZCR-4w',
    url: location.href,
    tag: store.state.actName,
    title: store.state.actName,
    type: 'HUODONG',
    // time: remindOption.acRemindTime,
    time: remindOption.acRemindTime,
    id: remindOption.acRemindTime
  }

  jdReminder.add(remindOption1).then((resData) => {
    callback(resData)
  }).catch((err) => {
    console.log(err, 'err')
    let errData = {
      appointed: false
    }
    callback(errData)
  })

  // jdReminder(remindOption1).then((resData) => {
  //   callback(resData)
  // }).catch((err) => {
  //   console.log(err, 'err')
  //   let errData = {
  //     appointed: false
  //   }
  //   callback(errData)
  // })

}

//去官方的待评价订单页面
const getJdPingJia = () => {
  console.log('去官方的待评价订单页面')
  if (store.state.clientType == '01') {
    var channel = 'app'
  } else if (store.state.clientType == '02') {
    var channel = 'wechat'
  } else if (store.state.clientType == '03') {
    var channel = 'qq'
  }
  if (channel == 'app') {
    var params = {
      category: "jump",
      des: "commentCenter"
    }
    params = JSON.stringify(params)
    var linkUrl = "openjd://virtual?params=" + params;
    window.location.replace(linkUrl);
  } else {
    window.location.replace("https://wqs.jd.com/order/orderlist_merge_old.shtml?tab=4")
  }
}

//去京东优惠券页面
const goUseCoupon = () => {
  var params = {
    category: 'jump',
    des: 'mycoupon'
  };
  params = JSON.stringify(params);
  var linkUrl = 'openjd://virtual?params=' + params;
  window.location.href = linkUrl;
}


//更多优惠
const moreCoupon = () => {
  let queryData = {
    activityType: sessionStorage.getItem('activityType'),
    templateId: sessionStorage.getItem('templateId'),
    activityId: sessionStorage.getItem('activityId'),
    nodeId: sessionStorage.getItem('nodeId'),
    giftType: sessionStorage.getItem('giftType'),
    isGiftTrue: sessionStorage.getItem('isGiftTrue'),
    prd: sessionStorage.getItem('prd'),
    gameDraw: sessionStorage.getItem('gameDraw')
  };

  for (let i in queryData) {
    if (!queryData[i] || queryData[i] == 'null') {

      delete queryData[i];
    }
  }

  // this.$router.replace({
  //   path: "/index",
  //   query: queryData,
  // });

  var aa = '';
  var lastkey = '';
  for (let i in queryData) {
    lastkey = i;
  }
  for (let i in queryData) {
    if (lastkey == i) {
      aa = aa + `${i}=${queryData[i]}`;
    } else {
      aa = aa + `${i}=${queryData[i]}&`;
    }
  }

  let tokenUrl = process.env.ACTIVITY_HOST + '/?' + aa;
  // console.log(tokenUrl, 'tokenUrl')

  window.location.replace(tokenUrl)
}

// 根据奖品类型判断奖品名字
const prizeTypeCheck = (prizeType) => {
  console.log('zxccccccccccccccccccccc11111111')
  let prizeTypeName = ''
  if (prizeType == 1) {
    prizeTypeName = '京豆';
  } else if (prizeType == 2) {
    prizeTypeName = '优惠券';
  } else if (prizeType == 3) {
    prizeTypeName = '实物';
  } else if (prizeType == 4) {
    prizeTypeName = '积分';
  } else if (prizeType == 5) {
    prizeTypeName = '专享价';
  } else if (prizeType == 6) {
    prizeTypeName = '红包';
  } else if (prizeType == 7) {
    prizeTypeName = '礼品卡';
  } else if (prizeType == 8) {
    prizeTypeName = '京东E卡';
  } else if (prizeType == 9) {
    prizeTypeName = '京东plus会员卡';
  } else if (prizeType == 10) {
    prizeTypeName = '爱奇艺会员卡';
  } else if (prizeType == 12) {
    prizeTypeName = '京元宝权益';
  } else if (prizeType == 13) {
    prizeTypeName = '促销令牌';
  } else if (prizeType == 101) {
    prizeTypeName = '京券';
  } else if (prizeType == 102) {
    prizeTypeName = '东券';
  }
  console.log(prizeTypeName,'prizeTypeNameprizeTypeName')
  return prizeTypeName;
};

// 根据奖品类型判断doFrontBuryPoint埋点code
const prizeTypeCheckPonit = (prizeType) => {
  let ponitCode = ''
  if (prizeType == 1) {
    ponitCode = 'ljq-jd';
  } else if (prizeType == 2) {
    ponitCode = 'ljq-yhq';
  } else if (prizeType == 3) {
    ponitCode = 'ljq-sw';
  } else if (prizeType == 4) {
    ponitCode = 'ljq-jf';
  } else if (prizeType == 5) {
    ponitCode = '';
  } else if (prizeType == 6) {
    ponitCode = 'ljq-hb';
  } else if (prizeType == 7) {
    ponitCode = 'ljq-lpk';
  } else if (prizeType == 8) {
    ponitCode = 'ljq-ek';
  } else if (prizeType == 9) {
    ponitCode = 'ljq-plus';
  } else if (prizeType == 10) {
    ponitCode = 'ljq-aqi';
  } else if (prizeType == 12) {
    ponitCode = 'ljq-jyb';
  } else if (prizeType == 13) {
    ponitCode = '';
  } else if (prizeType == 101) {
    ponitCode = '';
  } else if (prizeType == 102) {
    ponitCode = '';
  }
  return ponitCode;
};
// 根据奖品类型判断doFrontBuryPoint埋点code
const taskTypeCheckPonit = (taskType) => {
  let ponitCode = ''
  if (taskType == 5) {
    ponitCode = 'tc-gzsprw';
  } else if (taskType == 8 || taskType == 22) {
    ponitCode = 'tc-gmsprw';
  } else if (taskType == 9) {
    ponitCode = 'tc-fxsprw';
  } else if (taskType == 10) {
    ponitCode = 'tc-fxdprw';
  } else if (taskType == 12) {
    ponitCode = 'tc-fxhdrw';
  } else if (taskType == 7) {
    ponitCode = 'tc-jgsprw';
  }
  return ponitCode;
};


export {
  getCookie,
  getUrlQueryValueByKey,
  goToShopPage,
  goToSkuPage,
  goToActive,
  getQueryObject,
  goToOpenCard,
  initBuriedPoint,
  phoneCheck,
  checkEmoj,
  checkInput,
  checkQuestionAnswerInput,
  changeStates,
  exchangePrize,
  acReminder,
  emailCheck,
  getJdPingJia,
  goUseCoupon,
  moreCoupon,
  prizeTypeCheck,
  removeUrlShareUserId,
  prizeTypeCheckPonit,
  taskTypeCheckPonit,
  newToSkuPage
};
