<template>
  <div @click="toGoodDetail" :class="{
    'good-cell': true,
    'no-border': noBorder
  }">
    <div class="good-img" v-if="skuName && skuName.img">
      <img :src="$filters.urlToHttps(skuName.img)" alt="加载中..." class="good-img-size"/>
    </div>
    <div class="good-info">
      <!-- style="width: 412rpx;" 193px-->
      <!-- width:fit-content -->
      <div class="good-name" :style="{'width':titleWidth}">{{skuName.name}}</div>
      
      <div class="countTime-wrap" v-if="skuName.actType===5 &&skuName.actPrice!==0 &&skuName.trendType !==0 && timeTen  && waitShow">
        <div class="countTime" >{{skuName.trendType===2 ? '降价' :'升价'}}还剩 {{msg}}</div>
      </div>
      <div class="act-type-wrapper">
        <div class="act-type" v-if="skuName.actType">{{actTypeArr[skuName.actType]}}</div>
      </div>
      <!-- v-if="isShowShop" -->
      <div class="good-price">
        <div class="price">
          <good-price :price="skuName.curPrice"></good-price>
          <div class="ori-price" v-if="skuName && skuName.oriPrice && !isMaterial">{{$filters.toFixed2(skuName.oriPrice)}}</div>
        </div>

        <div class="add-cart" @click.stop="addCart" v-if="skuName.count===0 && isShowShop">加入购物车</div>
        <!-- #ifdef MP-TOUTIAO || APP-PLUS -->
        <!--  @click.stop="addCart" v-if="skuName.count===0" -->
        <div class="add-cart" v-if="!isShowShop">查看详情</div>
        <!-- #endif -->
        
        <!-- v-if="skuName.count!==0 && isShowShop" -->
        <template  v-if="skuName.count!==0 && isShowShop">
          <div class="handle-shopcar" @click.stop="clickStop" v-if="skuName.id !== 6031118" >
            <plus-minus type="input" :skuName="skuName" :count="skuName.count" @clickPlus="handlePlus" @clickMinus="handleMinus" @countChange="countChange"></plus-minus>
          </div>
        </template> 
        <!-- <div v-if="!isShowShop" class="lookDetail" style="border:1rpx solid red">查看详情</div> -->
      </div>
      

      <!-- 购物车活动商品普通商品分层 -->
      <div class="cart-act-count" v-if="type === 'cart' && skuName.actType && skuName.count > 1">
        <div class="act-count-show">
          <span>{{$filters.toFixed2(skuName.curPrice)}}</span>
          <span>x1</span>
        </div>
        <div class="act-count-show">
          <span>{{$filters.toFixed2(skuName.oriPrice)}}</span>
          <span>x{{skuName.count - 1}}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import { toast, modal, errToast,jumpPage } from "@/utils/uniapi.js";
import PlusMinus from "@/components/goodCmp/plus-minus/plus-minus";
import { actTypeArr } from "@/config";

import GoodPrice from '@/components/goodCmp/good-price/good-price'
import orderPage from '@/apis/orderPage'
import { handleCreatePay } from '@/utils/uniapi.js'
export default {
  name: "goodCell",
  inject: {
    shopCar: {
      default: false,
    },
  },
  components: {
    PlusMinus,
    GoodPrice
  },
  props: {
    skuName: {
      type: Object,
      // default() {
      //   return {};
      // },
    },
    index: {
      type: Number,
    },
    noBorder: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: "",
    },
    waitShow: {
      type: Boolean,
      default: true,
    },
    titleWidth: {
      type: String,
      default:'390rpx'
    }
  },
  computed: {
    ...mapGetters({
      countTime: "countTime",
      storeID:"indexPage/storeID",
      defaultAddress: "addressVue/defaultAddress",
      isLogin:"login/isLogin",
      isShowShop: "isShowShop",
      isMaterial: "indexPage/isMaterial"
    }),
  },
  data() {
    return {
      actTypeArr,
      msg: "",
      modalShow: false,
      fromTime: null,
      toTime: null,
      num: null,
      price: null,
      beforeCreateData: {},
      timer: null,
      highPrice: null,
      lowPrice: null,
      timeTen: true,
      imgUrl:'https://image.jxc4.com/image/8a98a93946f9f70dd84960c06725f4fb.jpg'
    };
  },
  created() {
    // this.fromTime = new Date();
    // this.fromTime.setHours(8);
    // this.fromTime.setMinutes(0);
    // this.fromTime.setSeconds(1);
    // // console.log("8dian", this.fromTime);
    // this.toTime = new Date();
    // this.toTime.setHours(22);
    // this.toTime.setMinutes(0);
    // this.toTime.setSeconds(0);
    // this.timer = setInterval(() => {
    //   this.countDown(this.toTime);
    // }, 1000);
    // if (new Date().getHours() < 10 || new Date().getHours() > 22) {
    //   this.timeTen = false;
    //   clearInterval(this.timer);
    // }
    // if (!(this.skuName.actType === 5 && this.skuName.actPrice !== 0)) {
    //   clearInterval(this.timer);
    // }
    // let sku = this.skuName;
    // if (this.skuName.discountType == 1) {
    //   this.highPrice = (sku.oriPrice / 100).toFixed(2);
    //   this.lowPrice = (sku.discountValue2 / 100).toFixed(2);
    // } else {
    //   this.highPrice = (sku.oriPrice / 100).toFixed(2);
    //   this.lowPrice = ((sku.discountValue2 * sku.actPrice) / 100).toFixed(2);
    // }
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    // 设置图片信息
    // setImgInfo() {    // val
    //   this.imgUrl = this.skuName.img.includes('https')?this.skuName.img:this.skuName.img.replace('http','https')
    // },
    // 加入购物车
    addCart() {
      if (!this.isLogin) {
        errToast('请登录')
        jumpPage('switchTab', '/pages/mine/index', 800)
        return
      }
      this.handlePlus()
    },
    clickStop(){
      // console.log('阻止点击事件传递')
    },
    // ...mapActions({
    //   changeCar: "cartPage/changeCar",
    // }),
    waitPriceDown(x) {
      this.modalShow = true;
      console.log(x);
    },
    //守家确定调支付三步
    async comfirmWaitPrice(price, num, checked) {
      this.price = Number(price).toFixed(2);
      this.num = Number(num);
      this.checked = checked;
      console.log(this.price, this.num, this.checked);
      console.log("skuname", this.skuName);
      //预创建
      if (
        this.num > 0 &&
        this.num < this.skuName.stock &&
        Number(price) > this.lowPrice &&
        Number(price) <= this.highPrice
      ) {
        try {
          let obj1 = {
            jxOrder: JSON.stringify({
              storeID: this.storeID[0],
              expectedDeliveredTimestamp: null,
              skus: [
                {
                  skuID: this.skuName.id,
                  count: this.num,
                  defendPrice: Number(this.price * 100),
                },
              ],
              orderType: 3,
            }),
            addressID: this.defaultAddress[0].id,
            createType: 0,
            isDeliverySelf: false,
          };
          console.log(obj1)
          let res = await orderPage.createOrder(obj1)
          this.preCreateData = res;
        } catch (e) {
          if ("errKey" in e) {
            errToast(e.err);
          } else {
            throw e;
          }
        }
        try {
          let obj2 = {
            jxOrder: JSON.stringify({
              ...this.preCreateData,
              // expectedDeliveredTimestamp: 0,
              storeID: this.storeID[0],
              orderType: 3,
              isBuyNowPrice: this.checked ? 1 : 0,
              defendPrice: (this.price * 100).toFixed(2),
            }),
            addressID: this.defaultAddress[0].id,
            createType: 1,
            isDeliverySelf: false,
          };
          //第二步
          let orderInfo = await orderPage.createOrder(obj2)
          console.log(orderInfo);
          this.modalShow = false;
          let payInfo = await orderPage.pay4Order({
            vendorOrderID: orderInfo.orderID,
            payType: 2,
            vendorPayType: "W06",
            subAppID:"wx4b5930c13f8b1170",
          });
          console.log(payInfo);
          // return false
          await handleCreatePay(
            payInfo.vendorOrderID,
            payInfo.prepayID,
            JSON.parse(payInfo.codeURL)
          );
          toast("支付成功");
        } catch (e) {
          if ("errKey" in e) {
            errToast(e.err);
          } else {
            throw e;
          }
        }
      } else if (this.price < this.lowPrice || this.price > this.highPrice) {
        errToast("请输入守家范围内的价格");
      } else if (this.num === 0) {
        errToast("份数最少为一份");
      }
    },
    close() {
      this.modalShow = false;
    },
    //倒计时
    countDown(time1) {
      if (this.toTime > new Date()) {
        let res = ((new Date(time1) - new Date()) / (1000 * 60)) % 10;
        let minutes = Math.floor(res);
        let seconds = Math.floor((res * 60) % 60);
        //console.log(seconds.toString().length);
        if (seconds.toString().length < 2) {
          seconds = "0" + seconds;
        }
        this.msg = "0" + minutes + "分 : " + seconds + "秒";
      }
    },
    //销量
    stock() {
      let num = this.skuName.stock;
      if (num >= 1000) {
        return "库存:1000+";
      } else if (num < 1000 && num > 0) {
        return "库存:" + num;
      } else if (num === 0) {
        return "卖完了";
      }
    },
    async handlePlus() {
      this.$emit("handleSkuNamePlus", this.index)
    },
    async handleMinus() {
      this.$emit("handleSkuNameMinus", this.index)
    },
    async countChange(count) {
      this.$emit("handleSkuNameChange", {
          index: this.index,
          count,
        });
    },
    // 跳转到商品详情页
    toGoodDetail() {
      jumpPage('navigateTo',`/pagesGoods/good-detail/index?skuID=${this.skuName.id}&storeID=${this.skuName.storeID}`)
    },
  },
};
</script>

<style lang="scss">
@import "./good-cell.scss";
.red {
  flex: 1;
  color: #fe6263;
  margin: 10rpx 0;
}
.gray {
  flex: 1;
  color: #999;
  margin: 10rpx 0;
}
</style>
