<template>
  <div class="root" :style="{backgroundColor:comp.props.bgColor.val}">
    <!-- 防伪组件，查询防伪信息并展示  :style="{backgroundColor:comp.props.bgColor.val}"-->
    <div v-if="!antifakeInfo.Result" class="fake">
      <img :src="comp.props.bgImg.val" alt />
    </div>

    <div v-if="!showInput" class="result bg-color">
      <mt-cell title="查验结果" class="bg-color" style>
        <img slot="icon" :src="icons.query" width="16" height="16" />
        <div @click="continueSearch()" v-if="comp.props.visible.val==1">
          <span style="margin-right: 24px">继续查询</span>
          <i class="mint-cell-allow-right"></i>
        </div>
      </mt-cell>
      <div
        class="bg-color div-break"
        :class="{'reply-true':antifakeInfo.Result,'reply-false':!antifakeInfo.Result}"
        v-html="antifakeInfo.Content"
      ></div>
	  <!-- <div class="num-color cl">
			<div class="code-item">
				<div class="num">8</div>
				<div class="color">红</div>
			</div>
	  </div> -->
	  <!-- <div>
			<div class="qrcode-box">
				<span class="c1"></span>
				<span class="c2"></span>
				<span class="c3"></span>
				<span class="c4"></span>
				<div id="qrcode"></div>
			</div>
	  </div> -->
    </div>

    <!-- <div v-if="showInput" class="result">
      <div class="input-code">
        <img
          class="img-search"
          src="http://image.supercarrier8.com/antifaketemplae/%E8%BE%93%E5%85%A5%E9%98%B2%E4%BC%AA%E7%A0%81%E5%9B%BE%E6%A0%87.png"
        >
        <input type="text" v-model="code" name id placeholder="请输入防伪码">
        <img
          class="img-ok"
          src="http://image.supercarrier8.com/antifaketemplae/%E7%A1%AE%E5%AE%9A%E6%8C%89%E9%92%AE.png"
          @click="search()"
          :disable="true"
        >
      </div>
    </div>-->
  </div>
</template>

<script>
//import $ from "jquery";
import apiHelper from "../assets/js/apiHelper.js";
import eventBus from "../assets/js/eventBus.js";
import define from "../assets/js/define.js";
import _stringResource from "../assets/js/stringResource.js";
import { Toast } from "mint-ui";
import QRCode from 'qrcodejs2';
export default {
  name: "CompAntiFake",
  props: ["comp", "cfg", "selectedPage"],
  data() {
    return {
      title: "",
      code: "",
      showInput: false,
      icons: {
        query:
          "http://image.supercarrier8.com/antifaketemplae/%E9%98%B2%E4%BC%AA%E7%BB%93%E6%9E%9C.png"
      },
      antifakeInfo: {
        Result: true,
        Content: "正在查询，请稍后..."
	  },
	  language:"ZH-CN",
	  codeColor:{},
	  logicColorList:[],
	  fourQuadrantList:[],
	  url:"",
	  codeColorType:0,
	  afInfo:""//防伪信息缓存
    };
  },
  methods: {
    search() {
      var that = this;
      var reg = /^[0-9]{16}$/;
      if (!reg.test(that.code)) {
        Toast("请输入正确的防伪码");
        return;
      }

      // 由于逻辑的修改 再次输入码时，重新走一次正常的查询逻辑 2018年9月5日 15点51分 幻视
      var url = "{0}?1{1}{2}".format(
        location.origin,
        that.code,
        _.random(100000, 999999)
      );
      window.location.href = url;

      //this.showInput = false;

      // apiHelper.decode(
      //   that.code,
      //   that.sup8.codeInfo.EnterpriseNo,
      //   function(res) {
      //     if (!res.flag || !res.data) {
      //       that.sup8.msg = res.msg;
      //       that.$router.push("/error");
      //       return;
      //     } else {
      //       that.showInput = false;

      //       // 先解码，再查防伪
      //       that.searchAntifake(res.data);
      //     }
      //   },
      //   function() {
      //     that.sup8.msg = "出错啦,请稍后重试。";
      //     that.$router.push("/error");
      //   }
      // );
    },
    continueSearch() {
      // this.showInput = true;
      // 进入数码输入页面
      let newPage = _.find(this.cfg.pages, { type: "8" });
      if (newPage) {
        this.$emit("changeData", {
          selectedPage: newPage
        });
      }
    },

    //调接口、查防伪
    searchAntifake(codeInfo) {
      var that = this;
      if (!codeInfo) {
      } else {
        that.sup8.codeInfo = codeInfo;
        let antifakeCodeLen = 16; // 防伪码的长度
        // 如果不是合法的防伪码，不查防伪
        // if (!codeInfo.Code || codeInfo.Code.length !== antifakeCodeLen) {
        if (!codeInfo.Code) {
          that.showInput = true;
          return;
        }

        // 表示查询的是不是一个新的产品
        var isNewProduct = that.sup8.codeInfo.ProductId !== codeInfo.ProductId;

        function todo() {
          apiHelper.getAntifakeInfo(
            codeInfo.EnterpriseNo ||
              that.sup8.context.enterpriseno ||
              that.sup8.context.eno,
            //'',
            codeInfo.ProductId,
            codeInfo.Code,
            // "20",
            that.sup8.context.channel,
            that.sup8.context.decodestatus,
            that.sup8.codeInfo.LabelNo,
            that.sup8.codeInfo.SkuLogisticCode || "123",
            function(res) {
              if (res.flag === true && that.antifakeInfo.Result === true) {
                that.afInfo = res.data;
                // that.sup8.antifakeInfo = res.data;

                eventBus.publish("event_enable_comp", "防伪查询正确数码");

                if (isNewProduct) {
                  eventBus.publish(eventBus.eventKey.pruductChange);
                }

                eventBus.publish(eventBus.eventKey.antifakeTrue, {
                  isNewProduct: isNewProduct,
                  msg: "防伪查询正确数码"
				});
				if(!!that.sup8.context.logiccolor){
					that.getLogicColorConvertInfo();
				}else{
					that.antifakeInfo.Content = that.afInfo.Content.replace(new RegExp("\\$logicColor\\$", "g"), "").replace(new RegExp("\\$fourQuadrant\\$", "g"), "");
				}
              } else {
                that.antifakeInfo = {
                  Result: true,
                  Content: res.msg || "未查询到该码的信息，谨防假冒"
                };
              }
            },
            function(res) {
              that.antifakeInfo = {
                Result: true,
                Content: res.msg || "未查询到该码的信息，谨防假冒"
              };
              // eventBus.subscribe("event_disable_comp", "防伪查询不正确数码");
              // eventBus.subscribe(
              //   eventBus.eventKey.antifakeFalse,
              //   "防伪查询不正确数码"
              // );
            },that.language
          );
        }
		if(this.sup8.h5Template.IsGPS==1){
			if (this.sup8.context.geo) {
				todo();
			} else {
				eventBus.subscribe("gpsDone", data => {
					todo();
				});
			}
		}else{
			todo();
		}
      }
	},
	// 获取数码颜色
	getLogicColorConvertInfo(){
		let protocol = location.protocol.substring(0,location.protocol.length-1);
		let domain = location.host;
		apiHelper.getLogicColorConvertInfo(this.sup8.context.eno, this.sup8.context.code, protocol, domain,this.sup8.context.logiccolor,(res)=>{
			if(res.flag){
				this.logicColorList = res.data.LogicColor;
				this.fourQuadrantList = res.data.FourQuadrant;
				this.url = res.data.Url;
				if(res.data.AntifakeType==1){
					this.codeColorType = 1;
					this.creatCodeColor();
				}else if(res.data.AntifakeType==2){
					this.codeColorType = 2;
					this.creatCodeColor();
					this.creatQuadrant();
				}else{
					this.antifakeInfo.Content = this.afInfo.Content.replace(new RegExp("\\$logicColor\\$", "g"), "").replace(new RegExp("\\$fourQuadrant\\$", "g"), "");
				}
			}
		},(e)=>{
			
		});
	},
	//鉴码辩色
	creatCodeColor(){
		if(this.codeColorType == 1){
			this.afInfo.Content = this.afInfo.Content.replace(new RegExp("\\$fourQuadrant\\$", "g"), "");
		}
		if(this.afInfo.Content.indexOf('$logicColor$') == -1){
			this.antifakeInfo.Content = this.afInfo.Content;
			return;
		}
		let html = "";
		let str = "";
		this.logicColorList.forEach(v => {
			let className = "";
			switch (v.Color) {
				case "红色":
					className = "num-red";
					break;
				case "蓝色":
					className = "num-blue";
					break;
				case "绿色":
					className = "num-green";
					break;
				case "黑色":
					className = "num-black";
					break;
				default:
					className = "num-black";
					break;
			}
			html +=`<div class="code-item ${className}">
						<div class="num">${v.Num}</div>
						<div class="color">${this.codeColor[v.Color]}</div>
					</div>`;
		});
		str = '<div class="num-color cl">'+html+'</div>';
		if(this.codeColorType == 1){
			this.antifakeInfo.Content = this.afInfo.Content.replace(new RegExp("\\$logicColor\\$", "g"), str);
		}else{
			this.afInfo.Content = this.afInfo.Content.replace(new RegExp("\\$logicColor\\$", "g"), str);
		}
	},
	// 四象限
	creatQuadrant(){
		if(this.afInfo.Content.indexOf('$fourQuadrant$') == -1){
			this.antifakeInfo.Content = this.afInfo.Content;
			return;
		}
		let that = this;
		let html = "";
		let str = "";
		let index = 1;
		this.fourQuadrantList.forEach(v => {
			let className = "";
			switch (v.Color) {
				case "红色":
					className = "bg-red";
					break;
				case "蓝色":
					className = "bg-blue";
					break;
				case "绿色":
					className = "bg-green";
					break;
				case "黑色":
					className = "bg-black";
					break;
				default:
					className = "bg-black";
					break;
			}
			if(index==2){
				html = `<span class="${className}"></span>`+html;
			}else{
				html +=`<span class="${className}"></span>`;
			}
			index = index + 1;
		});
		let timestr = new Date().getTime();
		str = '<div class="four-quadrant"><div class="qrcode-box">'+html+'<div class="qrcode" id="qrcode'+timestr+'"></div></div></div>';
		this.antifakeInfo.Content = this.afInfo.Content.replace(new RegExp("\\$fourQuadrant\\$", "g"), str);
		this.$nextTick(()=>{
			let qrcode = new QRCode(document.getElementById("qrcode"+timestr), {
				text: that.url,
				width: 200,
				height: 200,
				colorDark : "transparent",
				colorLight : "#fff",
				correctLevel : QRCode.CorrectLevel.H
			});
		});
	},
	// 获取系统语言
	getOSlanguage(){
		let language = (navigator.browserLanguage || navigator.language).toLowerCase();
		if(language.indexOf('zh')>-1){
			// 中文
			this.language = "ZH-CN";
			this.codeColor = define.codeColor[this.language];
		}else if(language.indexOf('en')>-1){
			// 英文
			this.language = "EN-US";
			this.codeColor = define.codeColor[this.language];
		}else if(language.indexOf('ja')>-1){
			// 日文
			this.language = "JA-JP";
			this.codeColor = define.codeColor[this.language];
		}else if(language.indexOf('ko')>-1){
			// 韩文
			this.language = "KO-KR";
			this.codeColor = define.codeColor[this.language];
		}else if(language.indexOf('fr')>-1){
			// 法文
			this.language = "FR-FR";
			this.codeColor = define.codeColor[this.language];
		}else if(language.indexOf('de')>-1){
			// 德文
			this.language = "DE-DE";
			this.codeColor = define.codeColor[this.language];
		}else if(language.indexOf('ru')>-1){
			// 俄文
			this.language = "RU-RU";
			this.codeColor = define.codeColor[this.language];
		}else if(language.indexOf('ar')>-1){
			// 阿拉伯文
			this.language = "AR-SA";
			this.codeColor = define.codeColor[this.language];
		}else if(language.indexOf('es')>-1){
			// 西班牙文
			this.language = "ES-ES";
			this.codeColor = define.codeColor[this.language];
		}else if(language.indexOf('hi')>-1){
			// 印度文
			this.language = "HI-IN";
			this.codeColor = define.codeColor[this.language];
		}else{
			this.language = "ZH-CN";
			this.codeColor = define.codeColor[this.language];
		}
	}
  },

  /*在此处对数据进行初始化*/
  created: function() {
    let that = this;
    that.mergeCompProps(that.comp);

    that.title =
      that.sup8.productInfo && that.sup8.productInfo.name
        ? `${that.sup8.productInfo.name} ${that.sup8.productInfo.code}`
        : "商品名称";
	that.getOSlanguage();
	
    // 如果缓存中已经有了防伪信息，则不再查询
    switch (that.sup8.env) {
      case that.sup8._def.env.design: // 设计器模式
      case that.sup8._def.env.preview: // 预览模式
        that.antifakeInfo = {
          Result: true,
          Content:
            "该商品已被查询2次<br>感谢您购买由xxxxxx公司正品授权商品，谨防假冒！"
        };
        break;
	  case that.sup8._def.env.run: // 运行模式
        if (that.sup8.antifakeInfo && !that.sup8.context.isNewCode) {
          that.antifakeInfo = that.sup8.antifakeInfo;
        } else {
          that.searchAntifake(that.sup8.codeInfo);
          that.sup8.context.isNewCode = false;
        }
        break;
      default:
        break;
    }
  },

	mounted() {
		console.log("123456");
	}
};
</script>

<style scoped>
.root {
  padding-bottom: 10px;
}

.root .result {
  margin-top: 10px;
  /* border: 1px solid #d9d9d9; */
}

.root .fake img {
  width: 100%;
}

.mint-cell {
  background-color: unset;
}

.reply-true {
  color: green;
  text-align: left;
  font-size: 1rem;
  font-weight: 500;
  padding: 10px 12px;
}

.reply-false {
  color: red;
  text-align: left;
  font-size: 1rem;
  font-weight: 500;
  padding: 10px 12px;
}

.input-code {
  margin: 10px;
  border-radius: 4px;
  background: white;
  height: 50px;
  border: 1px solid #d9d9d9;
}

.input-code .mint-field-core {
  font-size: 1.5rem !important;
}

.input-code .img-search {
  margin: 10px 0 0 10px;
  float: left;
  width: 30px;
  height: 30px;
}

.input-code img {
  width: 48px;
  height: 48px;
  /* width: 10% */
}

.input-code .img-ok {
  position: relative;
  top: 3px;
  float: right;
}

.input-code input,
.input-code input:focus {
  border: 0;
  font-size: 18px;
  margin: 13px 0;
  float: left;
  width: 60%;
  outline: none;
  vertical-align: middle;
  line-height: 24px;
}
.root >>> .mint-cell-wrapper {
  background-image: none;
}
.div-break {
  word-break: break-all;
}
.root >>> .num-color{
	padding-top: 1rem;
	font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
             "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei",
             SimSun, sans-serif;
	width: 100%;
}
.root >>> .num-color .code-item{
	float: left;
	width: 16.666%;
	text-align: center;
	font-size: .875rem;
	/* margin-bottom: 1rem; */
	font-weight: normal;
}
.root >>> .num-color .code-item .num{
	margin-bottom: 3px;
}
.root >>> .num-color .code-item .color{
	height: 2.4rem;
	word-wrap: break-word;
}
.root >>> .num-red{
	color: #ed0d8e;
}
.root >>> .num-blue{
	color: #38bbf1;
}
.root >>> .num-green{
	color: #12a957;
}
.root >>> .num-black{
	color: #221e20;
}
.root >>> .four-quadrant{
	padding:.9rem;
}
.root >>> .qrcode-box{
	margin: 0 auto;
	position: relative;
	width: 200px;
	height: 200px;
	overflow: hidden;
}
.root >>> .qrcode-box span{
	float: left;
	width: 100px;
	height: 100px;
}
.root >>> .qrcode{
	position: absolute;
	left: 0;
	top: 0;
	width:200px; 
	height:200px;
}
.root >>> .bg-red{
	background-color: #ed0d8e;
}
.root >>> .bg-blue{
	background-color: #38bbf1;
}
.root >>> .bg-black{
	background-color: #221e20;
}
.root >>> .bg-green{
	background-color: #12a957;
}
</style>
