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 productType = [
  {
    value: 1,
    title: '自营',
  },
  {
    value: 2,
    title: '京东开普勒',
  },
  {
    value: 3,
    title: '京东联盟',
  },
  {
    value: 4,
    title: '众联',
  },
  {
    value: 5,
    title: '企业购',
  },
  {
    value: 6,
    title: '企业购直连',
  },
];

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: 'SKU编码',
      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,
                  }}
                >
                  虚拟
                </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: 'SKU商品名称',
      width: 135,
      align: 'center',
      dataIndex: 'skuName',
    },

    {
      title: '供应商价格',
      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>市场价：{(row.marketPrice || 0).toFixed(2)}</p>
        </div>
      ),
    },
    {
      title: '库存',
      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>当前库存：{stockView}</p>
            <p>可售库存：{_}</p>
            {row.type === 1 && row.productStockWarning > 0 && (
              <p>预警值：{row.productStockWarning}</p>
            )}
          </>
        );
      },
    },
    {
      title: '不支持配送区域',
      dataIndex: 'areaTemplateName',
      key: 'areaTemplateName',
      width: 200,
      align: 'center',
    },
    {
      title: '上下架状态',
      dataIndex: 'stateDesc', // 5:未上架 ,6 :上架,7:下架
      width: 200,
      align: 'center',
      render: (_, row) => (
        <div>
          {row.type === 4 && row.state >= 5 ? (
            <>
              <Switch
                checkedChildren="已上架"
                checked={row.state === 6}
                unCheckedChildren="已下架"
                onClick={() => onChangeState(row)}
                defaultChecked
              />
            </>
          ) : (
            '-'
          )}
        </div>
      ),
    },
    {
      title: '审核状态',
      dataIndex: 'stateDesc',
      width: 200,
      align: 'center',
      render: (_, row) => (
        <div>
          <p>{row.state >= 5 ? '审核通过' : _}</p>
          <div>
            {row.updateState ? (
              <Button onClick={() => onShowAudit(row)} type="link">
                {row.updateStateDesc}
              </Button>
            ) : (
              '--'
            )}
          </div>
        </div>
      ),
    },
    {
      title: '操作',
      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);
              }}
            >
              修改
            </Button>
          )}
          <Button
            key="viewP"
            type="primary"
            size="small"
            className={styles.button}
            onClick={() => this.audit(row.skuId)}
          >
            预览
          </Button>
          <Button
            key="log"
            size="small"
            type="primary"
            className={styles.button}
            onClick={() => this.viewLog(row)}
          >
            查看日志
          </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('处理成功！');
        }
      },
    });
  };
  const DragHandle = SortableHandle(() => (
    <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />
  ));

  return [
    {
      title: '排序',
      dataIndex: 'sort',
      align: 'center',
      width: 70,
      className: [styles['drag-visible']],
      render: () => <DragHandle />,
    },
    {
      title: 'SKU编码',
      dataIndex: 'skuId',
      width: 180,
      align: 'center',
    },
    {
      title: 'SKU商品名称',
      // width: 200,
      align: 'center',
      dataIndex: 'skuName',
    },
    {
      title: '售卖价格(元)',
      dataIndex: 'salePrice',
      width: 150,
      align: 'center',
    },
    {
      title: '库存',
      width: 120,
      dataIndex: 'stock',
      align: 'center',
    },
    {
      title: '上下架状态',
      dataIndex: 'stateDesc', // 5:未上架 ,6 :上架,7:下架
      width: 200,
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 400,
      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)}
            >
              编辑
            </Button>
          )}
          <Button
            key="viewP"
            type="primary"
            className={styles.button}
            onClick={() => onChangeState(row)}
          >
            {+row.state === 6 ? '下架' : '上架'}
          </Button>
          <Button
            key="log"
            type="primary"
            className={styles.button}
            onClick={() => actions.onShowStockModal(row)}
          >
            修改库存
          </Button>
          {index > 0 && (
            <Button key="top" className={styles.button} onClick={() => actions.toTop(index)}>
              置顶
            </Button>
          )}
        </div>
      ),
    },
  ];
}

// 外卖商品批量操作
export const batchAction = event => [
  {
    key: 'up',
    type: '2',
    label: (
      <a type="text" onClick={() => event.onChangeState('up')}>
        上架
      </a>
    ),
  },
  {
    key: 'down',
    type: '2',
    label: (
      <a type="text" onClick={() => event.onChangeState('down')}>
        下架
      </a>
    ),
  },
  {
    key: 'stock',
    type: '7',
    label: (
      <a type="text" onClick={() => event.onChangeState('stock')}>
        修改库存
      </a>
    ),
  },
  {
    key: 'time',
    type: '4',
    label: (
      <a type="text" onClick={() => event.onChangeState('time')}>
        修改可售时间
      </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')}>
        设置单点不送
      </a>
    ),
  },
  {
    key: 'buy',
    type: '5',
    label: (
      <a type="text" onClick={() => event.onChangeState('buy')}>
        修改最少购买数量
      </a>
    ),
  },
];
// 外卖商品可售星期
export const saleWeeks = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 },
];

export const disSelectStatus = [2, 5];
export const stateList = [
  { value: 3, label: '待审核' },
  { value: 4, label: '驳回' },
  { value: 5, label: '审核通过' },
];

// AUDITING(3, "待审核"),REJECTED(4, "驳回"),WAIT_SELL(5, "未上架"),ON_SELL(6, "已上架"),OFF_SHELVES(7, "已下架")）
export const productTypeList = [
  { value: 1, label: '实体商品' },
  { value: 2, label: '虚拟充值' },
  { value: 3, label: '虚拟卡券', 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;
};

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