import Toast from 'tdesign-miniprogram/toast/index';
import {
  goodsList
} from "~/model/goods";
import {
  fetchGood
} from '~/services/good/fetchGood';
import {
  addOrUpdateCart
} from '~/services/cart/addOrUpdateCart';

Component({
  externalClasses: ['wr-class'],

  properties: {
    goodsList: {
      type: Array,
      value: [],
    },
    id: {
      type: String,
      value: '',
      observer: (id) => {
        this.genIndependentID(id);
      },
    },
    thresholds: {
      type: Array,
      value: [],
    },
    type: {
      type: String,
      value: "card"
    }
  },

  data: {
    independentID: '',
    isSpuSelectPopupShow: false,
    details: {},
    specImg: "",
    primaryImage: "",
    skuArray: [],
    selectSkuQuantity: 0,
    isStock: false,
    isAllSelectedSku: false,
    selectSkuSellsPrice: 0,
    selectSkuLinePrice: 0,
    selectedSkuId: 0,
    maxLinePrice: 0,
    minSalePrice: 0,
    maxSalePrice: 0,
    details: {},
    buyNum: 1,
  },

  lifetimes: {
    ready() {
      this.init();
    },
  },

  methods: {
    onClickGoods(e) {
      const {
        index
      } = e.currentTarget.dataset;
      this.triggerEvent('click', {
        ...e.detail,
        index
      });
    },

    onAddCart(e) {
      const {
        index
      } = e.currentTarget.dataset;
      this.setData({
        isSpuSelectPopupShow: true
      })

      // 请求商品详情接口
      this.getDetail(e.detail.goods.spuId)
    },

    changeNum(e) {
      this.setData({
        buyNum: e.detail.buyNum,
      });
    },

    addCartFun() {
      const {
        isAllSelectedSku,
        buyNum,
        selectedSkuId
      } = this.data;
      const {
        specList,
        shopGuid,
        spuId,
      } = this.data.details;
      let data = {
        shopGuid: shopGuid,
        goodsGuid: spuId,
        goodsSkuId: selectedSkuId,
        cartGoodsNum: buyNum
      }
      // console.log(data, '加入购物车的数据');

      // 添加购物车接口
      addOrUpdateCart(data).then((res) => {
        if (res.code == 200) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: res.data,
            icon: '',
            duration: 1000,
          });
          this.setData({
            isSpuSelectPopupShow: false,
          });
        }
      })
    },

    selectSpecsName(selectSpecsName) {
      if (selectSpecsName) {
        this.setData({
          selectedAttrStr: selectSpecsName,
        });
      } else {
        this.setData({
          selectedAttrStr: '',
        });
      }
    },

    normalizeSkuTree(skuTree) {
      const normalizedTree = {};
      skuTree.forEach((treeItem) => {
        normalizedTree[treeItem.specId] = treeItem.specValueList;
      });
      return normalizedTree;
    },

    // 获取已选择的sku名称
    getSelectedSkuValues(skuTree, selectedSku) {
      const normalizedTree = this.normalizeSkuTree(skuTree);
      return Object.keys(selectedSku).reduce((selectedValues, skuKeyStr) => {
        const skuValues = normalizedTree[skuKeyStr];
        const skuValueId = selectedSku[skuKeyStr];
        if (skuValueId !== '') {
          const skuValue = skuValues.filter((value) => {
            return value.specValueId === skuValueId;
          })[0];
          skuValue && selectedValues.push(skuValue);
        }
        return selectedValues;
      }, []);
    },

    getSkuItem(specList, selectedSku) {
      const {
        skuArray,
        primaryImage
      } = this.data;
      const selectedSkuValues = this.getSelectedSkuValues(specList, selectedSku);
      let selectedAttrStr = ` 件  `;
      selectedSkuValues.forEach((item) => {
        selectedAttrStr += `，${item.specValue}  `;
      });
      // eslint-disable-next-line array-callback-return
      const skuItem = skuArray.filter((item) => {
        let status = true;
        (item.specInfo || []).forEach((subItem) => {
          if (
            !selectedSku[subItem.specId] ||
            selectedSku[subItem.specId] !== subItem.specValueId
          ) {
            status = false;
          }
        });
        if (status) return item;
      });
      this.selectSpecsName(selectedSkuValues.length > 0 ? selectedAttrStr : '');
      if (skuItem) {
        console.log(skuItem[0], '选中的item');
        console.log(skuItem[0]?.priceInfo[0]?.price, '选中的item');
        console.log(skuItem[0]?.priceInfo[1]?.price, '选中的item');
        this.setData({
          selectedSkuId: skuItem[0]?.skuId,
          selectItem: skuItem,
          selectSkuSellsPrice: skuItem[0]?.priceInfo[0]?.price || 0,
          selectSkuLinePrice: skuItem[0]?.priceInfo[1]?.price || 0,
          selectSkuQuantity: skuItem[0]?.quantity
        });
      } else {
        this.setData({
          selectItem: null,
          selectSkuSellsPrice: 0,
          selectSkuLinePrice: 0,
        });
      }
      this.setData({
        specImg: skuItem && skuItem[0]?.skuImage ? skuItem[0]?.skuImage : primaryImage,
      });
    },

    chooseSpecItem(e) {
      console.log(e);
      const {
        specList
      } = this.data.details;
      const {
        selectedSku,
        isAllSelectedSku
      } = e.detail;
      if (!isAllSelectedSku) {
        this.setData({
          selectSkuSellsPrice: 0,
        });
      }
      this.setData({
        isAllSelectedSku,
      });
      this.getSkuItem(specList, selectedSku);
    },

    /** 加入购物车 */
    addCart() {
      const {
        isAllSelectedSku,
      } = this.data;
      const {
        specList,
      } = this.data.details;

      if (specList.length != 0) {
        if (isAllSelectedSku) {
          this.addCartFun()
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请选择规格',
            icon: '',
            duration: 1000,
          });
        }
      } else {
        this.addCartFun()
      }
    },

    onClickGoodsThumb(e) {
      const {
        index
      } = e.currentTarget.dataset;
      this.triggerEvent('thumb', {
        ...e.detail,
        index
      });
    },

    init() {
      console.log(this.properties.goodsList);
      this.genIndependentID(this.id || '');
      this.setData({
        type: this.properties.type
      });
    },

    genIndependentID(id) {
      if (id) {
        this.setData({
          independentID: id
        });
      } else {
        this.setData({
          independentID: `goods-list-${~~(Math.random() * 10 ** 8)}`,
        });
      }
    },

    // 商品规格js方法（搬运商品详情页的相关方法）
    getDetail(spuId) {
      Promise.all([fetchGood(spuId)]).then((res) => {
        const [details] = res;
        const skuArray = [];
        const {
          skuList,
          primaryImage,
        } = details;

        // details.desc = details.desc.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ');
        // details.desc = details.desc.replace(/<img[^>]*style\s*=\s*(['"])[^'"]*\1[^>]*>/gi, '<img style="max-width:100%;height:auto;" ');
        // details.desc = details.desc.replace(/<img[^>]*>/gi, '<img style="max-3999999996width:100%;height:auto;" >');

        skuList.forEach((item) => {
          skuArray.push({
            skuId: item.skuId,
            quantity: item.quantity ? item.quantity : 0,
            specInfo: item.specInfo,
            priceInfo: item.priceInfo,
            skuImage: item.skuImage,
          });
        });

        this.setData({
          details,
          isStock: details.spuStockQuantity > 0,
          skuArray: skuArray,
          primaryImage,
        });
      });
    },

    handlePopupHide() {
      this.setData({
        isSpuSelectPopupShow: false,
      });
    },
  },
});