<template>
  <div>
    <div class="user">
      <Myheader></Myheader>
      <div class="rc-top"></div>
      <tabs :crumbs="crumbs"></tabs>
      <div class="online rc-margin--none" id="fixed-catbar-seperator"></div>
      <div class="rc-top"></div>
      <div
        class="
          rc-usermain
          ts-product-detail
          rc-max-width--xl
          rc-layout-container rc-two-column rc-border-bottom
          rc-border-colour--brand4
        "
      >
        <div class="rc-column">
          <div data-js-carousel="" data-image-gallery="true">
            <div
              class="rc-carousel rc-carousel__gallery-image"
              data-zoom-container="328b2e5f-6904-4cac-9709-51ed18d2500f"
              data-zoom-factor="2"
            >
              <!-- Big images-->
              <div v-for="(item, index) in productAttachmentList" :key="index">
                <div>
                  <img v-if="(item.attachmentPath.indexOf('mp4')<0)" :src="item.attachmentPath" />
				  <video v-if="(item.attachmentPath.indexOf('mp4')>0)" preload="meta" controls="controls">
					<source :src= item.attachmentPath type="video/mp4">
				  </video>
                </div>
              </div>

              <!-- <div>
			  <div>
				  <img src="https://cdn.royalcanin-weshare-online.io/m2kia2QBG95Xk-RBC8jn/v1/medium-maxi-giant-pos-2012-packshots-ma-ad-shn-packshot?w=420&fm=jpg&auto=compress" alt="Product alt text" />
			  </div>
			</div> -->
              <!-- Big images end-->
            </div>
            <div class="rc-carousel__gallery-thumbnails-wrapper">
              <div class="rc-carousel rc-carousel__gallery-thumbnails">
                <!-- Thunb images-->
                <div
                  class="
                    rc-carousel__gallery-thumbnail
                    tns-item tns-slide-active
                  "
                  v-for="(item, index) in productAttachmentList"
                  :key="index"
                >
                  <div class="rc-img--square">
                    <img :src="item.attachmentPath" v-if="(item.attachmentPath.indexOf('mp4')<0)" />
					<img src="/images/default.jpg" class="ts-video-btn" v-if="(item.attachmentPath.indexOf('mp4')>0)" />
                  </div>
                </div>
                <!-- <div class="rc-carousel__gallery-thumbnail">
                  <figure
                    class="rc-img--square"
                    style="
                      background-image: url('https://cdn.royalcanin-weshare-online.io/m2kia2QBG95Xk-RBC8jn/v1/medium-maxi-giant-pos-2012-packshots-ma-ad-shn-packshot?w=64&fm=jpg&auto=compress');
                    "
                  >
                    <figcaption class="rc-screen-reader-text">
                      Product caption text
                    </figcaption>
                  </figure>
                </div>
                <div class="rc-carousel__gallery-thumbnail">
                  <figure
                    class="rc-img--square"
                    style="
                      background-image: url('https://cdn.royalcanin-weshare-online.io/UCEUa2QBaxEApS7L_-Xz/v2/fbn-2013-graphiccodes-packshots-siam-ad-int-fbn-packshot?w=64&fm=jpg&auto=compress');
                    "
                  >
                    <figcaption class="rc-screen-reader-text">
                      Product caption text
                    </figcaption>
                  </figure>
                </div> -->
                <!-- Thunb images end-->
              </div>
            </div>
          </div>
        </div>

        <div
          class="ts-product-header rc-column"
          id="328b2e5f-6904-4cac-9709-51ed18d2500f"
        >
          <div class="usermain">
            <div class="online bold rc-md-down"></div>
            <div class="rc-main">
              <div class="rc-title">
                <h2>{{ curItem.brandName + " " + curItem.productName }}</h2>
              </div>
            </div>
            <div class="online rc-md-down"></div>
            <div class="rc-main">
              <div class="productdetails">
				  <div class="rc-productdetail" v-if="!userbuy">
				    <i class="ts-row-title">适用年龄：</i>
				    <span>{{ curItem.tagUsedAge }}</span>
				  </div>
				  <div class="rc-productdetail" v-if="!userbuy">
				    <i class="ts-row-title">所属分类：</i>
				    <span>{{ curItem.categoryName }}</span>
              
				  </div>
				<div class="rc-button" v-if="!userbuy && curItem.goodUrl && curItem.goodUrl.length>5">
					<a :href="curItem.goodUrl" target='_blank' class="ts-standard-btn">立即购买</a>
				</div>
         
          
                <div class="rc-productdetail" v-if="userbuy">
                  <i class="ts-row-title">商品价格：</i>
                  <span class="ts-realprice">￥{{ curItem.ecPrice }}</span>
                  <span class="ts-remove ts-ecprice" v-if="curItem.ecPrice<curItem.rsp"
                    >￥{{ curItem.rsp }}
                  </span>
                    <span class="ts-record" v-if="curItem.basePoint!==0">
                    购买该商品你将获得{{curItem.basePoint}}积分
                  </span>
                  
                  <!-- <span class="rc-title">购买该商品你将得到22积分</span> -->
                </div>
                <div class="rc-productdetai" v-if="userbuy">
                  <div>
                    <i class="ts-row-title">活动促销：</i>
                    <span>全场商品限时优惠</span>
                  </div>
                  <em class="ts-right-arr" @click="userget()">立即领取</em>
                </div>
              </div>
            </div>
            <div class="online bold rc-md-down"></div>
            <div class="rc-main rc-md-up" v-if="userbuy">
              <div class="online"></div>
            </div>

            <div class="rc-productdeta" v-if="userbuy">
              <div class="rc-main">
                <div class="rc-prodtop">
                  <div>
                    <i class="ts-row-title">商品规格：</i>
                  </div>
					<div class="ts-tag-list">
						<em v-for="(item, index) in newlist" :key="index"  @click="selectsearch(item, index)" :class="[(activeIndexa==index && item.leftAllotment>0)?'active':'unactive',item.leftAllotment>0?'':'disabled']">
							{{ item.specifications }}
						</em>
					</div>
				<!-- 一个标品有多个商品, 每个商品有不同的价格
				<em class="active">
					{{ item.specifications }}
				</em>
				-->
                </div>
              </div>
              <div class="rc-main">
                <div class="rc-produnnum" v-if="(userbuy && curItem.leftAllotment>0)">
                  <div><i class="ts-row-title">商品数量：</i></div>
                  <img
                    src="../../assets/image/userjian.png"
                    alt=""
                    @click="sub()"
                  />
                  <strong>{{ sales_num }}</strong>
                  <img
                    src="../../assets/image/userjia.png"
                    alt=""
                    @click="plus()"
                  />
                </div>
              </div>
              <div class="rc-main rc-md-up" v-if="userbuy">
                <div class="online"></div>
              </div>
              <div class="online rc-md-down"></div>
              <div class="rc-main">
                <div class="certification">
                  <ul>
                    <li>
                      <span
                        ><i class="ts-row-title">服务说明：</i
                        ><i
                          >当天14点前完成付款即日安排发货;当天14点后完成付款次日安排发货(周日及国家法定节假日顺延至下一个工作日发货,活动期间发货或有延迟敬请理解)</i
                        ></span
                      >
                    </li>
                    <li>
                      <span
                        ><i class="ts-row-title">商品运费：</i
                        ><i>全场包邮(港澳除外)</i></span
                      >
                    </li>

                    <li>
                      <span
                        ><i class="ts-row-title">商品编号：</i
                        ><i>{{ curItem.productCode }}</i></span
                      >
                    </li>
                  </ul>
                </div>
                <div class="rc-button"  v-if="(userbuy && curItem.leftAllotment>0)">
                  <span @click="usertanchu(curItem, 0)">加入购物车</span>
                  <span @click="usertanchu(curItem, 1)">立即购买</span>
                </div>
                 
              </div>
              <div class="online bold rc-md-down"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="rc-footimage rc-padding--sm rc-max-width--lg">
        <img :src="curItem.showImgFile" alt="" />
      </div>
      <FixRight></FixRight>
      <Myfooter v-on:litentop="showmesg"></Myfooter>
  
    </div>
    <el-dialog :visible.sync="dialogInfo1" @close="userclose" class="pop_coupon" :close-on-click-modal="false">
		<div class="ts-no-data" v-if="usernewlist.length<=0">目前还没有可用的优惠券</div>
      <div class="rs-dis">
        <div
          class="rc-discount"
          v-for="(item, index) in usernewlist"
          :key="index"
        >
          <img :src="userimage" alt="" />
		  <div class="rc-contair">
		    <div class="rc-left">
		  	<div>
		  		<i v-if="(item.couponTypeId!='4' && item.couponAmount>0)">
		  			￥
		  		</i>
		  		<span>
		  			{{ item.couponAmount?item.couponAmount:(parseInt((1-item.discount)*10)+'折') }}
		  		</span>
		  	</div>
		  	<strong>{{ item.couponName }}</strong>
		    </div>
		    <div class="rc-right">
		  	<i>
		  	  {{ item.couponName }}
		  	</i>
		  	<div class="rc-userfont" :style="(item.validTo?'visibility:visible':'visibility:hidden')">
		  		<strong>有效期</strong>
		  	  <span>{{item.validFrom}}至</span>
		  	  <em>{{item.validTo}}</em>
		  	</div>
		  	<div class="rc-footer">
		  	  <span @click="usergetconf(item)">立即领取</span>
		  	</div>
		    </div>
		  </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogInfo2" @close="userclose" :close-on-click-modal="false">
      <div class="rc-headera">
        <div class="rc-title">
          <img src="../../assets/error.png" alt="" />
        </div>
        <div class="rc-logmain">
          <h3>温馨提示</h3>
          <span>请先点击下方进行登录/注册</span>
        </div>
        <nuxt-link :to="`/userlogin/login/`">
          <div class="userer">
            <span>立即登录</span>
          </div>
        </nuxt-link>
      </div>
    </el-dialog>
    <div class="rc-button rc-md-down" v-if="(userbuy && curItem.leftAllotment>0)">
      <span @click="usertanchu(curItem, 0)">加入购物车</span>
      <span @click="usertanchu(curItem, 1)">立即购买</span>
    </div>
	<div class="rc-button rc-md-down " v-if="!userbuy && curItem.goodUrl && curItem.goodUrl.length>5">
		<a :href="curItem.goodUrl" target='_blank' class="ts-standard-btn">立即购买</a>
	</div>
    
  </div>
</template>

<script>
import Myheader from "~/components/header.vue";
import tabs from "@/components/tabs.vue";
import FixRight from "~/components/fixed-right.vue";
import unlogin from "~/components/unlogin.vue";
import Myfooter from "~/components/rc-footer.vue";
import { mapMutations } from "vuex";
const settings = require("@/config");
import {
  goodsmessage,
  getConfig,
  postCourseId,
  getdraw,
  alldiscount,
  oncequery,
  biaomessage
} from "../../ajax/getData";

export default {
	async asyncData (context) {
		let isRxGoods = context.route.query.isRxGoods;
		let userbuy = true;
		let newlist = [];
		let curItem = {};
		let videolist=[];
		let productAttachmentList = [];
		let userlistmenu = [];
		isRxGoods = (isRxGoods == '1'?true:false);
		let mainProductCode = context.route.query.mainProductCode;
		let productCode = context.route.query.productCode;
		let activeIndexa = 0;
		if(!productCode || productCode.length<=0)
			throw new Error('Empty product code');
		productCode = productCode.split(",");
		if(isRxGoods){
			let data = await oncequery(mainProductCode);
			let outputObj = {};
			if (data) {
				outputObj = data;
				outputObj.productName = data.name;
				newlist = [outputObj];
				curItem = outputObj;
			}
			let insertTmpObj = {id:1, attachmentType:1, sort:1, attachmentPath:newlist[0].picture};
			productAttachmentList = [insertTmpObj];
			userbuy = false;
		} else {
			let stopLeftAllotmentChecking = false;
			let stopIndex = 0;
			for(let singleCode of productCode) {
				let data = await goodsmessage(singleCode);
				if (data && data.data.length>0) {
					newlist.push(data.data[0]);

					if(data.data[0].leftAllotment>0 && !stopLeftAllotmentChecking) {
						activeIndexa = stopIndex;
						curItem = data.data[0];
						stopLeftAllotmentChecking=true;
					}
					stopIndex++;
				}
			}
			if(curItem.productAttachmentList != undefined)
				productAttachmentList = curItem.productAttachmentList;
			let list=[];
			if(curItem.productName == undefined)
				curItem = newlist[0];
			userbuy = true;
		}
		if(!curItem || curItem.productName == undefined)
			throw new Error("商品信息错误");
		let crumbs = [
			{
				path:'/productdetails/productlist/',
			},
			{
				title: curItem.productName,
			}
		];
		return {
			crumbs,
			activeIndexa,
			curItem,
			newlist,
			videolist,
			productAttachmentList,
			userbuy,
			isRxGoods
		}
	},
   data() {
    return {
      tableLabelTest: [],
      userimage: require("../../assets/image/unused.png"),
      gotop: false,
      dialogInfo1: false,
      videolist:[],
      videoimg:'',
      name: [],
      userlist: [],
      drawlist: [], //用户可以领取的优惠券
      alldraw: [],
      userlistmenu: [],
      msg: [""],
      parent_msg: [""],
      usermessage: [],
      dialogInfo2: false,
      productCode: "", //商品code
      productlist: [],
      userbuy: true,
      sales_num: 1,

      productAttachmentList: [],
      usernewlist: [
        {
          price: "30",
          pricestype: "新客优惠券",
          special: "全场每满299-30",
          period: "有效期",
          starttime: "2021.11.29-2022.01.28",
          catimage: require("../../assets/image/unused.png"),
        },
        {
          price: "30",
          pricestype: "新客优惠券",
          special: "全场每满299-30",
          period: "有效期",
          starttime: "2021.11.29-2022.01.28",
          catimage: require("../../assets/image/unused.png"),
        },
      ],

      newlist: [
        {
          price: "167.00",
          pricestype: "英国短毛猫成猫全价湿粮",
          special: "限时折扣全场商品8折",
          period: "今晚20:00前付款，明日12:00前发货",
          starttime: "商品未满199元  快递费:9.00元",
          shangbianhao: "6212263798102432",
          catimage: require("../../assets/image/rc-new.png"),
        },
      ],
      stype: [
        {
          title: "3kg",
        },
        {
          title: "5kg",
        },
      ],
    };
  },

  components: {
    Myheader,
    tabs,
    unlogin,
    Myfooter,
	FixRight
  },
  //  middleware: 'metaTitle',
  //   // middleware: 'metaTitle',
  // meta: {title: '产品详情'},
 
  mounted() {
	this.checkIsLogin();
  // console.log(this.curItem);
    if (this.usermessage !== "" || this.usermessage.data !== undefined) {
		this.usermessage = this.$store.state.userInfo;
		this.productCode = this.$route.query.productCode;
		_hmt.push([
		    "_trackCustomEvent",
		    "product_visit",
		    {
				"product_id_":this.curItem.productCode,
				"product_category_":this.curItem.categoryName,
		        "product_name_": this.curItem.productName,
		    }
		])
    }
  },
  methods: {
    ...mapMutations(["changemessage","checkIsLogin"]),
    showmesg() {
      this.toTop();
    },
    //领取优惠券
    usergetconf(item) {
		_hmt.push([
		    "_trackCustomEvent",
		    "get_coupon",
		    {
				"product_id_":this.curItem.productCode,
				"product_category_":this.curItem.categoryName,
				"product_name_": this.curItem.productName,
				"product_quantity_" : this.sales_num,
				"product_amount_" : this.sales_num*this.curItem.ecPrice,
		    }
		])
		if (this.usermessage.data !== "" || this.usermessage.data !== undefined) {
			this.getconf(this.usermessage.data.id, item.couponId);
		}
    },

    //获取用户领取的优惠券
    async getconf(memberId, couponId) {
      let data = await getConfig(memberId, couponId);
	  let msg = '领取成功';
	  let msgType = 'success';
      if (data) {
		if(data.code!='0') {
			msgType = 'warning';
			msg = data.msg;
		}
		this.$message({
			type: msgType,
			message: msg,
		});
      }
    },
    userclose() {
      this.userlist = [];
	  this.dialogInfo1=false;
    },
    async userquery() {
      let data = await goodsmessage(this.productCode);
      if (data) {
          console.log(data)
          debugger
        this.newlist = data.data;
      }
      this.productAttachmentList = this.newlist[0].productAttachmentList;
      this.userlistmenu = this.newlist[0].productAttachmentList;
      let changemess = JSON.stringify(this.userlistmenu);
      this.changemessage({ data: changemess });
      this.parent_msg = this.userlistmenu;
    },
	async rxquery() {
	  let data = await oncequery(this.productCode);
	  let outputObj = {};
	  if (data) {
		outputObj = data;
		outputObj.productName = data.name;
	    this.newlist = [outputObj];
	  }
	  let picture = this.newlist[0].picture.split(",");
	  this.productAttachmentList = picture;
	},

    //获取用户领取的优惠券
    async userdraw(mobile) {
      let data = await getdraw(mobile);
      if (data) {
        this.drawlist = data.data;
      }
    },

    //获取所有的优惠券
    async alldrawlist(memberId) {
      let data = await alldiscount(memberId);
      let userlist = [];
      let menulsit = [];
      if (data) {
        this.alldraw = data;
        // console.log(this.alldraw.data);
        let alllist = [];
        this.userlist = this.alldraw.data;
        this.userlist.forEach((element, index) => {
          if (typeof element.productCodes == "string" || !element.productCodes) {
            userlist.push(element);
            //  let s=element.productCodes.split(',');
            //     console.log(s.indexOf(this.productCode) != -1 )
            //  console.log('这是字符串')
          }
        });
        let menualist = [];
        userlist.filter((item) => {
			let valDateFromTime=0;
			let valDateToTime=0;
			let curTime = new Date().getTime();
			let dateChecked=true;
			if(item.fValidFrom) {
				valDateFromTime = new Date(item.fValidFrom).getTime();
			}
			if(item.fValidTo) {
				valDateToTime = new Date(item.fValidTo).getTime();
			}
			if(valDateFromTime && curTime < valDateFromTime) {
				dateChecked=false;
			}
			if(valDateToTime && curTime > valDateToTime) {
				dateChecked=false;
			}
			if(dateChecked && item.activityId!=10) {
				if(!item.productCodes) {
					menualist.push(item);
				} else {
					item.productCodes = item.productCodes.split(",");
					item.productCodes.forEach((element) => {
						if (element == this.curItem.productCode) {
							menualist.push(item);
						}
					});
				}
			} else {
				//Expired coupons
			}
        });
        this.usernewlist = menualist;
      }
    },

    plus(num, index) {
		if(this.sales_num >= this.curItem.leftAllotment) {
			this.$message({
				type: "warning",
				message: '已达到本品最大购买上限',
			});
		} else {
			this.sales_num = parseInt(this.sales_num) + 1;
		}
    },
    // 数量减方法
    sub(num, index) {
      if (this.sales_num <= 1) {
        this.sales_num = 1;
      } else {
        this.sales_num = parseInt(this.sales_num) - 1;
      }
    },

    async courseId(item) {
      // let userid=JSON.parse(location.getItem('userInfo'));
      // let mobile=JSON.parse(location.getItem('userInfo'));
      // console.log(userid,mobile);
	  let basePoint = item.basePoint;
	  basePoint = basePoint?basePoint:0;
      let data = await postCourseId(
        item.productCode,
        this.sales_num,
        this.usermessage.data.id,
        this.usermessage.data.mobile,
        item.picFile,
        item.productName,
        item.ecPrice,
        item.specifications,
        item.leftAllotment,
		basePoint
      );
      if (data) {
        this.productlist = data;
      }
    },
    usertanchu(item, orderm) {
      let user = this.$store.state.userInfo;
      if (!user) {
        this.dialogInfo2 = true;
        return;
      } else {
        this.courseId(item);
        if (orderm == 0) {
          this.$message({
            type: "warning",
            message: "加入购物车成功",
          });
		  _hmt.push([
		      "_trackCustomEvent",
		      "add_to_cart",
		      {
		  		"product_id_":this.curItem.productCode,
		  		"product_category_":this.curItem.categoryName,
		        "product_name_": this.curItem.productName,
				"product_quantity_" : this.sales_num,
				"product_amount_" : this.sales_num*this.curItem.ecPrice,
		      }
		  ])
        }
        if (orderm == 1) {
          let list = [
            {
              id: item.id,
              productCode: item.productCode,
              productPrice: item.ecPrice,
              productName: item.productName,
              productImg: item.picFile,
              specifications: item.specifications,
			  leftAllotment: item.leftAllotment,
			  basePoint: item.basePoint,
              buyCount: this.sales_num,
              memberId: "",
              mobile: "",
              checked: true,
            },
          ];
		  _hmt.push([
		      "_trackCustomEvent",
		      "add_to_cart",
		      {
		  		"product_id_":this.curItem.productCode,
		  		"product_category_":this.curItem.categoryName,
		        "product_name_": this.curItem.productName,
		  				"product_quantity_" : this.sales_num,
		  				"product_amount_" : this.sales_num*this.curItem.ecPrice,
		      }
		  ])

          this.$router.push({
            path: "/personal/settlement",
            query: {
              list: JSON.stringify(list),
            },
          });
        }
      }
    },
    userget() {
      let user = localStorage.getItem("userInfo");
      if (user == undefined || user == null || user == "") {
        this.dialogInfo2 = true;
        return;
      } else {
        //this.userdraw(this.usermessage.data.mobile);
        this.alldrawlist(this.usermessage.data.id);
        this.dialogInfo1 = true;
      }
    },
    selectsearch(item, index) {
		if(!item.leftAllotment || item.leftAllotment<=0)
			return;
      this.activeIndexa = index;
	  this.curItem = item;
	  this.productAttachmentList = item.productAttachmentList;
	  this.crumbs.pop();
	  this.crumbs.push({title: item.productName});
    },
  },

  onceproduct() {},
};
</script>

<style lang="less" scoped>
@import url("../../assets/css/producted.less");
</style>