/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-03-01 19:00:03
 * @LastEditors: WorkerChen z874512298@163.com
 * @LastEditTime: 2022-05-11 09:18:47
 */
const {
  controlNumber,
  constructorDishUuid,
  publishShoppingCart,
} = require("../../_utils/dish");
const { debounce } = require("../../../utils/tool");
const { bus } = getApp();

const componentOptions = {
  // 组件选项
  options: {
    multipleSlots: true,
  },
  properties: {
    extraInfo: {
      type: Object,
      value: {},
      observer(v) {
        const { storeOperatingStatus } = v;
        console.log(storeOperatingStatus)
        this.setData({
          disabled: storeOperatingStatus === 2,
          type: storeOperatingStatus === 2 ? "closed" : "processing",
        });
      },
    },
  },
  // 组件数据
  data: {
    isPageHidden: false, // 页面是否处于隐藏状态
    // 弹出层样式
    customStyle: "background: transparent;overflow: visible;",
    // 是否展示弹窗
    show: false,
    // 菜品详情数据
    detail: {},
    // 菜品的详情大图
    images: [],
    // 当前菜品类型
    type: "processing",
    // 按钮文案
    typeText: {
      processing: "加入购物车",
      closed: "打烊中",
      sellerOut: "售罄",
    },
    // 是否不可点击
    disabled: false,
    // 购买信息
    buyInfo: {
      number: 1,
    },
    // 选中的属性值
    selectedAttr: {},
    attributeText: "",
    // 当前规格
    currSkuData: {},
  },
  // 数据监听器
  observers: {
    selectedAttr(v) {
      if (v) {
        this.compputedText();
      }
    },
  },
  // 组件方法
  methods: {
    // 处理由菜品展示组件传递过来的参数，用于控制菜品详情的展示
    handlerSubscription(e) {
      const { show, detail } = e;
      console.log(detail,'菜品详情')
      if (detail) {
        this.setData({
          show,
        });
        this.handlerDetail(detail);
      }
    },
    // 处理获取的菜品数据
    handlerDetail(data) {
      let detail = data;
      let {
        selectedAttr,
        extraInfo: { storeOperatingStatus },
      } = this.data;
      let {
        images,
        attribute,
        storeFoodSkuDtoList,
        oversell,
        sellerOut,
        startNum,
        number
      } = data;

      if (images && typeof images === "string") {
        images = images.split(",");
      }

      // 初始化属性
      try {
        attribute = JSON.parse(attribute);
        detail.attribute = attribute;
      } catch (err) {}
      if (Array.isArray(attribute)) {
        attribute.forEach((i) => {
          const { key, value } = i;
          if (Array.isArray(value) && value.length > 0) {
            selectedAttr[key] = value[0];
          }
        });
      }
      // 初始化属性

      // 初始化规格
      let currSkuData = null;
      if (storeFoodSkuDtoList && storeFoodSkuDtoList.length > 0) {
        for (let i = 0; i < storeFoodSkuDtoList.length; i++) {
          const { stock } = storeFoodSkuDtoList[i];
          if (stock > 0) {
            currSkuData = storeFoodSkuDtoList[i];
            break;
          }
        }
      }

      if (!currSkuData) currSkuData = storeFoodSkuDtoList[0];

      if (currSkuData.name) currSkuData.showSkuText = currSkuData.name;
      // 初始化规格

      let disabled = storeOperatingStatus === 2;
      let type = storeOperatingStatus === 2 ? "closed" : "processing";

      if (!disabled) {
        disabled = oversell || sellerOut;
        type = disabled ? "sellerOut" : "processing";
      }

      this.setData({
        detail,
        images,
        selectedAttr,
        currSkuData,
        disabled,
        type,
        "buyInfo.number": number || startNum,
      });
    },
    // 展示弹窗
    showPopup() {
      this.setData({ show: true });
    },
    // 关闭事件
    onClose() {
      this.reSetData();
    },
    // 菜品加/减
    // 普通菜品
    controlNumber({ currentTarget: { dataset } }) {
      if (this.data.disabled) return;

      const { isAdd = true } = dataset;
      let {
        buyInfo: { number: tempNumber },
        detail,
        currSkuData,
      } = this.data;

      const { miniImage, introduction, startNum } = detail;

      const number = controlNumber(
        {
          detail: Object.assign({}, currSkuData, {
            number: tempNumber,
            miniImage,
            introduction,
          }),
        },
        { ifBroadcast: false, isAdd }
      );

      this.setData({
        "buyInfo.number": number || startNum,
      });
    },
    // 隐藏的时候重置数据
    reSetData() {
      this.setData({
        // 是否展示弹窗
        show: false,
        // 菜品详情数据
        detail: {},
        // 菜品的详情大图
        images: [],
        // 当前菜品类型
        type: "processing",
        // 是否不可点击
        disabled: false,
        // 购买信息
        buyInfo: {
          number: 1,
        },
        // 选中的属性值
        selectedAttr: {},
        attributeText: "",
        // 当前规格
        currSkuData: {},
      });
    },
    // 选中一个属性
    selectAttrValue({ currentTarget: { dataset } }) {
      const { key, value } = dataset;
      let { selectedAttr } = this.data;

      selectedAttr[key] = value;

      this.setData({
        selectedAttr,
      });
    },
    // 计算属性值的文本
    compputedText() {
      const { selectedAttr } = this.data;
      let tempText = [];
      for (let i in selectedAttr) {
        tempText.push(selectedAttr[i]);
      }
      this.setData({
        attributeText: tempText.join("、"),
      });
    },
    // 选中一个规格
    selectSku({ currentTarget: { dataset } }) {
      let { value = {} } = dataset;
      const { stock } = value;
      if (stock < 1) return;
      value.showSkuText = value.name + "、";
      this.setData({
        currSkuData: value,
      });
    },
    // 加入购物车
    addToShoppingCart: debounce(function () {
      if (this.data.disabled) return;

      const {
        attributeText,
        currSkuData,
        buyInfo: { number: tempNumber },
      } = this.data;

      // 构建当前的key
      const key = constructorDishUuid(currSkuData, attributeText);
      const { cartDishes = {} } = getApp().globalData || {};
      const temp = cartDishes[key];
      // 新增添加购物车
      // const number = tempNumber + (temp ? temp.number || 0 : 0);
      
      // 是替换购物车
      const number = tempNumber


      // 计算必要的参数
      publishShoppingCart(
        key,
        Object.assign({}, currSkuData, { attributeText }),
        number,
        { type: "dish_detail" }
      );

      this.onClose();
    }),
  },
  // 组件生命周期
  lifetimes: {
    ready() {
      // 订阅
      bus.on("showDishDetail", this.handlerSubscription.bind(this));
    },
  },
  // 页面生命周期
  pageLifetimes: {
    // 页面被展示
    show() {
      const { isPageHidden } = this.data;

      // show事件发生前，页面不是处于隐藏状态时
      if (!isPageHidden) {
        return;
      }
    },
    // 页面被隐藏
    hide() {
      this.setData({
        isPageHidden: true,
      });

      // 清除定时器等操作
    },
  },
};

Component(componentOptions);
