import { message } from 'antd';
import { sortBy } from 'lodash';
import UUID from '../../utils/uuid';
import localStorage from '@/utils/localStorage';
import { debounce, getObjectType, isClass } from '@/utils/utils';

export const clearCurrent = currentList => currentList.filter(item => item.current);

export const filterSpecId = (input, option) =>
  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;

export const cleanArray = actual => {
  const newArray = [];
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
};

export const filterCoverItemList = (list, key) => (list || []).map(item => ({ [key]: item[key] }));

const createInitProduct = (skuItem, isCreate) => {
  if (isCreate && Object.keys(skuItem).length > 5) {
    return skuItem;
  }
  return {
    weight: null,
    productStockWarning: null,
    marketPrice: null,
    supplyPrice: null,
    stock: null,
    thirdSkuNo: null,
    skuLink: null,
    name: null,
    uuid: UUID.createUUID(),
  };
};

export const isUrl = path => {
  // eslint-disable-next-line no-useless-escape
  const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
  return reg.test(path);
};

export const batchTableSourceData = ({ batchItem, tableData, bacthSecon, bacthFirst }) => {
  const batchItemKey = Object.keys(batchItem);
  return tableData.map((item, index) => {
    if (!bacthFirst && !bacthSecon) {
      batchItemKey.forEach(key => {
        item[key] = batchItem[key] || null;
      });
    }
    if (bacthFirst && !bacthSecon) {
      batchItemKey.forEach(key => {
        if (item.firstSpecValue === bacthFirst) {
          item[key] = batchItem[key] || null;
        }
      });
    }
    if (!bacthFirst && bacthSecon) {
      batchItemKey.forEach(key => {
        if (item.secondSpecValue === bacthSecon) {
          item[key] = batchItem[key] || null;
        }
      });
    }
    if (bacthFirst && bacthSecon) {
      batchItemKey.forEach(key => {
        if (item.firstSpecValue === bacthFirst && item.secondSpecValue === bacthSecon) {
          item[key] = batchItem[key] || null;
        }
      });
    }
    return item;
  });
};

const filterItems = (type, props) => {
  const { infoSpecData, serviceItem, infoImageData, infoMation, settlementItem } = props;
  const { imageList = {}, commonImageList, cardImageList } = infoImageData;
  const { setMealContent } = infoSpecData;
  return infoSpecData.items.map((item, i) => {
    if (type === 4) {
      // 如果为服务类商品，默认取cardImageList，cardImageList为必选项目
      item.imageList = [...commonImageList, ...cardImageList];
    } else {
      // 如果为虚拟或实体商品，默认取自己{}中对应的的，没有则取公共图
      const imgList = imageList[item.firstSpecValue] || [];
      item.imageList = imgList.length ? imgList : commonImageList;
    }
    item.firstSpecId = infoSpecData.firstSpecId;
    item.secondSpecId = infoSpecData.secondSpecId || null;
    console.log('setMealContent :>> ', setMealContent);
    if (type === 4) {
      item.serviceItem = {
        ...serviceItem,
        ...settlementItem,
        description: infoMation.description || '',
      };
      if (setMealContent && setMealContent[i] && setMealContent[i].setMealContent) {
        item.serviceItem.setMealContent = setMealContent[i].setMealContent;
      }
    }
    return item;
  });
};

export const filterSendData = (type, params) => {
  // takeawayItem 外卖商品
  const { infoMation, infoImageData, attributeApplyList, takeawayItem } = params;
  // 外卖商品
  if (type === 5) {
    const temp = Object.assign({}, takeawayItem?.intactData, infoMation);
    const deepTemp = JSON.parse(JSON.stringify(temp));
    deepTemp.categoryId =
      Array.isArray(deepTemp.categoryId) &&
      deepTemp.categoryId?.slice(deepTemp.categoryId?.length - 1)?.toString();
    deepTemp.productRefShopId = deepTemp.productRefShopId.toString();
    const tempWeightName = JSON.parse(sessionStorage.getItem('weightUnits'));
    deepTemp.items.forEach(item => {
      item.autoStock = item.autoStock ? 1 : 0;
      item.serviceItem.autoStock = item?.serviceItem?.autoStock ? 1 : 0;
      item.productStock = item?.serviceItem?.productStock;
      item.list = deepTemp.list;
      // 新增sku 去掉id  没有改变的sku赋值之前的id
      if (deepTemp?.initMultiSpu?.length) {
        const index = deepTemp.initMultiSpu.findIndex(itm => item.unique === itm.unique);
        if (index > -1) {
          item.id = deepTemp?.initMultiSpu[index].id;
        } else {
          delete item.id;
        }
      }
      if (item?.specs?.length) {
        item.specs.forEach(itm => {
          if (itm?.unit && tempWeightName.includes(itm?.unit)) {
            itm.quantity =
              `${itm?.quantity}`.indexOf('约') > -1 ? itm?.quantity : `约${itm?.quantity}`;
          }
        });
      }
    });
    deepTemp.specList &&
      deepTemp.specList.forEach(item => {
        if (item?.specs?.length) {
          item.specs.forEach(itm => {
            if (itm?.unit) {
              itm.unit =
                (Array.isArray(itm?.unit) &&
                  itm?.unit?.length >= 2 &&
                  itm?.unit?.splice(itm?.unit?.length - 1)[0]) ||
                itm?.unit;
            }
            if (itm?.unit && tempWeightName.includes(itm?.unit)) {
              itm.quantity =
                `${itm?.quantity}`.indexOf('约') > -1 ? itm?.quantity : `约${itm?.quantity}`;
            }
          });
        }
      });
    console.log(deepTemp, takeawayItem, '222222222');
    return deepTemp;
  }
  const items = filterItems(type, params);
  const commonImageList = type === 4 ? [] : infoImageData.commonImageList;
  const obj = {
    type,
    items,
    name: infoMation.name,
    specs: infoMation.specs || [],
    supplierId: infoMation.supplierId,
    brandId: infoMation.brandId || null,
    character: infoMation.character,
    categoryId: Array.isArray(infoMation.categoryId)
      ? infoMation.categoryId.length &&
        infoMation.categoryId.slice(infoMation.categoryId.length - 1)?.toString()
      : infoMation.categoryId?.toString(),
    afterAddressId: infoMation.afterAddressId,
    detailImageList: infoImageData.detailImageList,
    commonImageList,
  };
  console.log('obj', obj);
  if (attributeApplyList && attributeApplyList.attributeApplyList) {
    obj.attributeApplyList = attributeApplyList.attributeApplyList;
  }

  return obj;
};

export const fliterSkuListSortData = list => {
  if (!list || !list.length) return;

  const fristSkuList = sortBy(list, item => item.firstSpecValue).reduce((origin, item) => {
    if (!origin[item.firstSpecValue]) {
      origin[item.firstSpecValue] = [item];
    } else {
      origin[item.firstSpecValue].push(item);
    }
    return origin;
  }, {});
  let finialList = [];
  // eslint-disable-next-line no-restricted-syntax, guard-for-in
  for (const skuKey in fristSkuList) {
    const skuFirst = fristSkuList[skuKey];
    skuFirst.forEach((sku, ind) => {
      if (!ind) {
        sku.rowSpanCount = skuFirst.length;
      }
    });
    finialList = [...finialList, ...skuFirst];
  }
  // eslint-disable-next-line consistent-return
  return finialList;
};

export const filterSkuNotIdList = list =>
  (list || []).reduce(
    (origin, item) => {
      if (item.id) {
        origin.inIdList.push(item);
      } else {
        origin.noIdList.push(item);
      }
      return origin;
    },
    {
      inIdList: [],
      noIdList: [],
    },
  );

const createInitSkuItems = () => ({
  weight: null,
  productStockWarning: null,
  marketPrice: null,
  supplyPrice: null,
  stock: null,
  thirdSkuNo: null,
  skuLink: null,
  name: null,
});

const getSecordValue = (firstSpecValue, sec, skuList = []) =>
  skuList.find(
    sku =>
      sku.firstSpecValue === firstSpecValue &&
      (!sku.secondSpecValue || sku.secondSpecValue === sec.secondSpecValue),
  );

export const createSkuListData = (first, second, firstSpecId, secondSpecId, skuList) => {
  const list = [];
  const skuItem = createInitSkuItems();

  if (first && first.length) {
    // 一级规格有值时，生成的编辑表格
    first.forEach(fir => {
      let copy = { ...skuItem };
      copy.firstSpecId = firstSpecId;
      copy.firstSpecValue = fir.firstSpecValue;
      if (second.length) {
        second.forEach(sec => {
          const v = getSecordValue(fir.firstSpecValue, sec, skuList);
          const copySec = v || { ...copy };
          copySec.secondSpecId = secondSpecId;
          copySec.secondSpecValue = sec.secondSpecValue;
          delete copySec.rowSpanCount;
          list.push(copySec);
        });
        return;
      }
      const v = getSecordValue(`${fir.firstSpecValue}`, {}, skuList);
      if (v) {
        copy = { ...v };
      }
      list.push(copy);
    });
  } else if (second && second.length) {
    // 缺少一级规格值，只有二级规格值时，生成的编辑表格
    second.forEach(sec => {
      const copy = { ...skuItem };
      copy.secondSpecId = secondSpecId;
      copy.secondSpecValue = sec.secondSpecValue;
      list.push(copy);
    });
  } else if (skuList && skuList.length) {
    list.push(...skuList);
  } else {
    // 缺少一级和二级规格时生成的编辑表格
    list.push(skuItem);
  }
  return list;
};

export const createProductData = (props, isEdit, skuList) => {
  const {
    firstSpecId,
    secondSpecId,
    fisrtNoIdList,
    secndNoIdList,
    fisrtInIdList,
    secndInIdList,
  } = props;
  let list = [];
  if (isEdit) {
    const newFirstList = fisrtNoIdList.concat(fisrtInIdList || []);
    const newSecondList = secndInIdList.concat(secndNoIdList || []);
    list = createSkuListData(newFirstList, newSecondList, firstSpecId, secondSpecId, skuList);
  } else {
    list = createSkuListData(fisrtNoIdList, secndNoIdList, firstSpecId, secondSpecId, skuList);
  }
  return list;
};

export const localAutoSaveKey = 'good-info-auto-save';

export const onAutoSaveValue = (e, isClear) => {
  // 暂时去掉外卖类型
  // if (e && e.type === 5) {
  //   localStorage.remove(localAutoSaveKey);
  //   return;
  // }
  const keys = Object.keys(e);
  if (
    e &&
    isClass(e) === 'Object' &&
    keys.length === 1 &&
    isClass(e[keys[0]]) === 'Object' &&
    Object.keys(e[keys[0]]) < 1
  ) {
    return;
  }
  if (isClear) {
    localStorage.set(localAutoSaveKey, Object.assign({}, e));
  } else {
    const info = localStorage.get(localAutoSaveKey) || {};
    localStorage.set(localAutoSaveKey, Object.assign({}, info, e));
  }
};

export const calcDescartes = array => {
  console.log(array, 'array');
  if (array.length < 2) return array[0] || [];

  return [].reduce.call(array, (col, set) => {
    const res = [];

    col.forEach(c => {
      set.forEach(s => {
        const t = [].concat(Array.isArray(c) ? c : [c]);
        t.push(s);
        res.push(t);
      });
    });

    return res;
  });
};
