import React from 'react';
import { Button, Badge, Switch, Modal, message } from 'antd';
import { SortableHandle } from 'react-sortable-hoc';
import { ExclamationCircleOutlined, MenuOutlined } from '@ant-design/icons';
import styles from './style.less';
import { resetTime } from '../../utils/utils';
import { apiChangeStateGoods, apiGoodsActionBatch } from './service';

const { confirm } = Modal;

export const NormalProduct = 1;
export const ServiceProduct = 4;
export const TakeawayProduct = 5;
export const GoodTypes = {
  [NormalProduct]: $t('physical.goods'),
  [ServiceProduct]: $t('service.products'),
  [TakeawayProduct]: $t('delivery.products'),
};

export const productType = [
  {
    value: 1,
    title: $t('selfoperated'),
  },
  {
    value: 2,
    title: $t('jd.kepler'),
  },
  {
    value: 3,
    title: $t('jd.union'),
  },
  {
    value: 4,
    title: $t('zhonglian'),
  },
  {
    value: 5,
    title: $t('enterprise.purchase'),
  },
  {
    value: 6,
    title: $t('direct.enterprise.purchase'),
  },
];

export function column() {
  const onChangeState = async ({ skuId, state }) => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: `确认${+state === 6 ? '下架' : '上架'}商品？`,
      onOk: async () => {
        const res = await apiChangeStateGoods({
          ids: skuId,
          productState: +state === 6 ? 7 : 6, // 6：上架，7:下架
        });
        if (res.businessCode === '0000' && res.code === '0000') {
          this.handleSearch();
        }
      },
    });
  };
  const onShowAudit = row => {
    this.setState({
      auditRow: row,
      visibleAuditModal: true,
    });
  };

  return [
    {
      title: $t('sku.code'),
      dataIndex: 'skuId',
      width: 125,
      align: 'center',
      render: (_, row) => {
        if (row.type === 2) {
          return (
            <Badge
              count={
                <div
                  style={{
                    color: '#fff',
                    borderRadius: '3px',
                    background: '#f5222d',
                    padding: '2px',
                    fontSize: '10px',
                    opacity: 0.7,
                  }}
                >{$t('virtual')}</div>
              }
            >
              <div
                style={{
                  background: '#fbfbfb',
                  borderRadius: '3px',
                  padding: '2px',
                }}
              >
                {row.skuId}
              </div>
            </Badge>
          );
        }
        return (
          <div
            style={{
              background: '#fbfbfb',
              borderRadius: '3px',
              padding: '2px',
            }}
          >
            {row.skuId}
          </div>
        );
      },
    },
    {
      title: $t('sku.product.name'),
      width: 135,
      align: 'center',
      dataIndex: 'skuName',
    },

    {
      title: $t('supplier.price'),
      dataIndex: 'marketPrice',
      width: 150,
      align: 'center',
      sorter: (a, b) => a.supplyPrice - b.supplyPrice,
      render: (_, row) => (
        <div className={styles.price}>
          {/* <p>供货价：{(row.supplyPrice || 0).toFixed(2)}</p> */}
          <p>{$t('market.price')}{(row.marketPrice || 0).toFixed(2)}</p>
        </div>
      ),
    },
    {
      title: $t('inventory'),
      width: 120,
      dataIndex: 'stock',
      align: 'center',
      sorter: (a, b) => a.stock - b.stock,
      render: (_, row) => {
        // const stockView = row.productStock;
        const stockView = (
          <Button type="link" onClick={() => this.onShowStockModal(row)} style={{ padding: 0 }}>
            {row.productStock}
          </Button>
        );
        return (
          <>
            <p>{$t('current.stock')}{stockView}</p>
            <p>{$t('available.stock')}{_}</p>
            {row.type === 1 && row.productStockWarning > 0 && (
              <p>{$t('alert.threshold')}{row.productStockWarning}</p>
            )}
          </>
        );
      },
    },
    {
      title: $t('delivery.area.not.supported'),
      dataIndex: 'areaTemplateName',
      key: 'areaTemplateName',
      width: 200,
      align: 'center',
    },
    {
      title: $t('listing.status'),
      dataIndex: 'stateDesc', // 5:未上架 ,6 :上架,7:下架
      width: 200,
      align: 'center',
      render: (_, row) => (
        <div>
          {row.type === 4 && row.state >= 5 ? (
            <>
              <Switch
                checkedChildren={$t('listed')}
                checked={row.state === 6}
                unCheckedChildren={$t('delisted')}
                onClick={() => onChangeState(row)}
                defaultChecked
              />
            </>
          ) : (
            '-'
          )}
        </div>
      ),
    },
    {
      title: $t('review.status'),
      dataIndex: 'stateDesc',
      width: 200,
      align: 'center',
      render: (_, row) => (
        <div>
          <p>{row.state >= 5 ? $t('review.passed') : _}</p>
          <div>
            {row.updateState ? (
              <Button onClick={() => onShowAudit(row)} type="link">
                {row.updateStateDesc}
              </Button>
            ) : (
              '--'
            )}
          </div>
        </div>
      ),
    },
    {
      title: $t('actions'),
      dataIndex: 'action',
      width: 120,
      align: 'center',
      render: (_, row) => (
        <div className={styles.actionBtn}>
          {this.canEditable && (row.state === 4 || (row.state >= 5 && row.updateState !== 1)) && (
            <Button
              key="edit"
              type="primary"
              size="small"
              className={styles.button}
              onClick={() => {
                this.serviceVisbleChange(row);
              }}
            >{$t('edit')}</Button>
          )}
          <Button
            key="viewP"
            type="primary"
            size="small"
            className={styles.button}
            onClick={() => this.audit(row.skuId)}
          >{$t('preview')}</Button>
          <Button
            key="log"
            size="small"
            type="primary"
            className={styles.button}
            onClick={() => this.viewLog(row)}
          >{$t('view.logs')}</Button>
        </div>
      ),
    },
  ];
}

export function takeawayColumn(actions) {
  const onChangeState = async ({ skuId, state }) => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: `确认${+state === 6 ? '下架' : '上架'}商品？`,
      onOk: async () => {
        const res = await apiGoodsActionBatch({
          skuIds: [skuId],
          shopId: actions.shopId,
          productStatus: +state === 6 ? 0 : 1, // 6：上架，7:下架
          type: 2,
        });
        if (res.businessCode === '0000' && res.code === '0000') {
          actions.getDataList();
          message.success($t('processed.successfully'));
        }
      },
    });
  };
  const DragHandle = SortableHandle(() => (
    <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />
  ));

  return [
    {
      title: $t('sort'),
      dataIndex: 'sort',
      align: 'center',
      width: 70,
      className: [styles['drag-visible']],
      render: () => <DragHandle />,
    },
    {
      title: $t('sku.code'),
      dataIndex: 'skuId',
      width: 180,
      align: 'center',
    },
    {
      title: $t('sku.product.name'),
      // width: 200,
      align: 'center',
      dataIndex: 'skuName',
    },
    {
      title: $t('selling.price'),
      dataIndex: 'salePrice',
      width: 120,
      align: 'center',
    },
    {
      title: $t('inventory'),
      width: 100,
      dataIndex: 'stock',
      align: 'center',
    },
    {
      title: $t('listing.status'),
      dataIndex: 'stateDesc', // 5:未上架 ,6 :上架,7:下架
      width: 110,
      align: 'center',
    },
    {
      title: $t('actions'),
      dataIndex: 'action',
      width: 390,
      align: 'center',
      render: (_, row, index) => (
        <div className={styles.actionBtn}>
          {(row.state === 4 || (row.state >= 5 && row.updateState !== 1)) && (
            <Button
              key="edit"
              type="primary"
              className={styles.button}
              onClick={() => actions.onEdit(row)}
            >{$t('edit')}</Button>
          )}
          <Button
            key="viewP"
            type="primary"
            className={styles.button}
            onClick={() => onChangeState(row)}
          >
            {+row.state === 6 ? $t('unshelf') : $t('shelf')}
          </Button>
          <Button
            key="log"
            type="primary"
            className={styles.button}
            onClick={() => actions.onShowStockModal(row)}
          >{$t('edit.inventory')}</Button>
          {(index > 0 || actions.pageNo > 1) && (
            <Button key="top" className={styles.button} onClick={() => actions.toTop(row)}>{$t('pin')}</Button>
          )}
        </div>
      ),
    },
  ];
}

// 外卖商品批量操作
export const batchAction = event => [
  {
    key: 'up',
    type: '2',
    label: (
      <a type="text" onClick={() => event.onChangeState('up')}>{$t('shelf')}</a>
    ),
  },
  {
    key: 'down',
    type: '2',
    label: (
      <a type="text" onClick={() => event.onChangeState('down')}>{$t('unshelf')}</a>
    ),
  },
  {
    key: 'stock',
    type: '7',
    label: (
      <a type="text" onClick={() => event.onChangeState('stock')}>{$t('edit.inventory')}</a>
    ),
  },
  {
    key: 'time',
    type: '4',
    label: (
      <a type="text" onClick={() => event.onChangeState('time')}>{$t('edit.sale.period')}</a>
    ),
  },
  // {
  //   key: 'group',
  //   type: '3',
  //   label: (
  //     <a type="text" onClick={() => event.onChangeState('group')}>
  //       修改分组
  //     </a>
  //   ),
  // },
  {
    key: 'send',
    type: '6',
    label: (
      <a type="text" onClick={() => event.onChangeState('send')}>{$t('set.as.nondeliverable')}</a>
    ),
  },
  {
    key: 'buy',
    type: '5',
    label: (
      <a type="text" onClick={() => event.onChangeState('buy')}>{$t('edit.minimum.purchase')}</a>
    ),
  },
];
// 外卖商品可售星期
export const saleWeeks = [
  { label: $t('monday'), value: 1 },
  { label: $t('tuesday'), value: 2 },
  { label: $t('wednesday'), value: 3 },
  { label: $t('thursday'), value: 4 },
  { label: $t('friday'), value: 5 },
  { label: $t('saturday'), value: 6 },
  { label: $t('sunday'), value: 7 },
];

export const disSelectStatus = [2, 5];
export const stateList = [
  { value: 3, label: $t('pending.review') },
  { value: 4, label: $t('reject') },
  { value: 5, label: $t('review.passed') },
];

// AUDITING(3, "待审核"),REJECTED(4, "驳回"),WAIT_SELL(5, "未上架"),ON_SELL(6, "已上架"),OFF_SHELVES(7, "已下架")）
export const productTypeList = [
  { value: 1, label: $t('physical.goods') },
  { value: 2, label: $t('virtual.recharge') },
  { value: 3, label: $t('evoucher'), disabled: true },
];

export const JDSHOPID = [3, 5, 6];

/** ********************************************************************************* */
/** ********************************************************************************* */
/** ********************************************************************************* */
// 编辑回显示时只获取用到的数据
const filterItem = skuItem => {
  const { serviceItem, ...argsItem } = skuItem;
  argsItem.disabled = true;
  return argsItem;
};

const filterSpecData = skuList =>
  skuList.reduce(
    (orgin, skuItem) => {
      const item = filterItem(skuItem);
      const { firstSpecValue, secondSpecValue, id } = item;
      if (firstSpecValue && !orgin.firstDuplicate.includes(firstSpecValue)) {
        orgin.firstSpecValue.push(item);
        orgin.firstDuplicate.push(firstSpecValue);
      }
      if (secondSpecValue && !orgin.secondDuplicate.includes(secondSpecValue)) {
        orgin.secondSpecValue.push(item);
        orgin.secondDuplicate.push(secondSpecValue);
      }
      // origin.skuItemResultList.push(item);
      return orgin;
    },
    {
      firstSpecValue: [],
      secondSpecValue: [],
      firstDuplicate: [],
      secondDuplicate: [],
      skuItemResultList: [],
    },
  );

const filterCarouseList = (carouseList = []) =>
  carouseList.reduce((origin, itemImg) => {
    if (itemImg.skuSpecImageList.length) {
      origin[itemImg.specValue || 'NOT'] = itemImg.skuSpecImageList || [];
    }
    return origin;
  }, {});

const filterServiceItem = (type, serviceItem) => {
  if (type !== 4) {
    return {};
  }
  console.log(serviceItem);
  return {
    serviceItem: {
      useTime: [resetTime(serviceItem.useStartTime), resetTime(serviceItem.useEndTime)],
      purchaseTime: [
        resetTime(serviceItem.purchaseStartTime),
        resetTime(serviceItem.purchaseEndTime),
      ], // 购买开始时间
      validityPeriodType: serviceItem.validityPeriodType,
      validityPeriodDays: serviceItem.validityPeriodDays,
      shopIds: serviceItem.shopIds || [], // 适用门店列表
      unavailableDate: serviceItem.unavailableDate, // 不可用日期
      useTimeDescription: serviceItem.useTimeDescription, // 使用时间
      useMethod: serviceItem.useMethod, // 使用方法
      ruleDescription: serviceItem.ruleDescription, // 规则说明
      applyScope: serviceItem.applyScope, // 适用范围
      tips: serviceItem.tips, // 温馨提示
    },
    settlementItem: {
      settlementMethod: 1,
      limitPurchase: Boolean(serviceItem.limitPurchase), // 是否限购1:限购/0:不限购
      limitPurchaseType: serviceItem.limitPurchaseType, // 限购类型，如果限购必填1:长期限购/2:周期限购
      limitPurchaseCycle: serviceItem.limitPurchaseCycle, // 限购周期1：每天/7：7天/30：30天
      limitPurchaseQuantity: serviceItem.limitPurchaseQuantity, // 限购数量
      packageContent: serviceItem.packageContent,
      appointment: serviceItem.appointment, // 预约
      receptionVolume: serviceItem.receptionVolume, // 接待数量
    },
  };
};

export const ProcessEditData = (data, row) => {
  const [oneItem = {}] = data.skuList;
  const serviceItem = oneItem.serviceItem || {};
  const orginSpecItem = filterSpecData(data.skuList);
  const imageList = filterCarouseList(data.carouseList);
  const servesItemParams = filterServiceItem(data.productType, serviceItem);

  const specsParams = data.specs.reduce((origin, item) => {
    origin[item.specId] = item.specValues.map(child => child.value);
    return origin;
  }, {});

  let commonImageList = data.commonImageList || [];
  let cardImageList = [];
  if (data.productType === 4) {
    const [firstImg, ...towAfterImgList] = oneItem.imageList || [];
    cardImageList = towAfterImgList || [];
    commonImageList = [firstImg];
  }
  const SourceData = {
    state: row.state,
    id: data.id,
    productType: data.productType,
    pageProductType: row.productType,
    productAttributeApplyList: data.productAttributeApplyList,
    infoMation: {
      ...specsParams,
      brandId: data.brandId,
      supplierId: data.supplierId,
      character: data.character,
      name: data.name,
      categoryId: [data.firstCategoryId, data.secondCategoryId, data.thirdCategoryId],
      description: serviceItem.description || null,
      afterAddressId: data.afterAddressId || null,
    },
    infoSpecData: {
      firstSpec: oneItem.firstSpec,
      firstSpecId: oneItem.firstSpecId,
      firstSpecValue: orginSpecItem.firstSpecValue,
      secondSpec: oneItem.secondSpec,
      secondSpecId: oneItem.secondSpecId,
      secondSpecValue: orginSpecItem.secondSpecValue,
    },
    infoImageData: {
      imageList,
      cardImageList,
      commonImageList,
      detailImageList: data.detailImageList,
    },
    skuList: data.skuList,
    ...servesItemParams,
  };
  console.log('SourceData===============>', SourceData);
  return SourceData;
};

/** ********************************************************************************* */
/** ********************************************************************************* */
/** ********************************************************************************* */
