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) => {
  const { infoMation, infoImageData, attributeApplyList } = params;
  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: infoMation.categoryId[2],
    afterAddressId: infoMation.afterAddressId,
    detailImageList: infoImageData.detailImageList,
    commonImageList,
  };
  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) => {
  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({ type: 1 }, info, e));
  }
};
