import lodash from 'lodash';
import { reactive } from 'vue';
import * as goodsCategoryApi from '/@/api/product/goodsCategoryApi';
import { useUserStore } from '/@/store/modules/user';
import * as CartApi from '/@/api/order/cartApi';

const userStore = useUserStore();

const pagination = {
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total) => `共 ${total} 条数据`,
  getData: () => {},
  onChange: (page) => {},
  onShowSizeChange: (current, size) => {},
  size: 'small',
  showSizeChanger: true,
  pageSizeOptions: ['10', '50', '100'],
};

export const usePagination = (fun: () => void) => {
  const p = lodash.cloneDeep(pagination);
  p.getData = fun;
  p.onChange = (page) => {
    p.current = page;
    p.getData();
  };
  p.onShowSizeChange = (current, size) => {
    p.current = 1;
    p.pageSize = size;
    p.getData();
  };
  return reactive(p);
};

const getNavTree = (navList, init?: Function, str?: string) => {
  goodsCategoryApi.dealerTree({ parentId: 0 }).then((res) => {
    navList.value = res;
    userStore.setUserNavList(navList.value);
    if (init) {
      if (str === 'getGrandsonList') {
        init(navList.value);
      } else {
        init();
      }
    }
  });
};

const navTree = (navList, init?: Function, str?: string) => {
  const navListStore = userStore.getNavList;
  if (navListStore.length <= 0) {
    getNavTree(navList, init, str);
  } else {
    navList.value = navListStore;
    if (init) {
      if (str === 'getGrandsonList') {
        init(navList.value);
      } else {
        init();
      }
    }
  }
};

export const useNavTree = () => {
  return navTree;
};

const getCartList = (productList) => {
  CartApi.all().then((res) => {
    res.forEach((item) => {
      // uuid是唯一标识符
      item.uuid = item.goodsId + '';
      item.goodsType = item.goods.goodsType;

      item.cartProductDetailList.forEach((product) => {
        product.uuid = item.goodsId + '-' + product.id;
        product.type = item.goods.goodsType;
        if (item.goodsType === 'KIT') {
          product.basicQuantity = product.quantity / item.quantity;
        }
      });
    });
    productList.value = res;
  });
};

export const useCartList = () => {
  return getCartList;
};
