import React, { useState, useEffect, useCallback } from 'react';
import { Table, Pagination, Button, Dialog } from '@alifd/next';
import IceContainer from '@icedesign/container';
import PageHead from '@/components/page-head';
import getCustomHeader from '@/components/token-header';
import Tools, { ajax } from '@/utils';
import Filter from './filter';
import styles from './index.module.scss';

const DefaultPageSize = 20;
export default function GoodsTable() {
  const currentPage = parseInt(Tools.getUrlParam('pageNum'), 10) || 1;
  const currentItemId = Tools.getUrlParam('itemId') || '';
  const currentKeyWord = Tools.getUrlParam('keyWord') || '';
  const currentStatus = parseInt(Tools.getUrlParam('status'), 10) || 1;
  const currentCategoryId = Tools.getUrlParam('categoryId') || '';
  const currentStoreId = Tools.getUrlParam('storeId') || '';
  // const [current, setCurrent] = useState(currentPage);
  const [isLoading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [totalPage, setTotalPage] = useState(0);

  useEffect(() => {
    fetchData({
      status: currentStatus,
      categoryId: currentCategoryId,
      storeId: currentStoreId,
      keyWord: currentKeyWord,
      itemId: currentItemId
    });
  }, []);

  const fetchData = useCallback(async data => {
    await setLoading(true);
    const queryData = {
      ...data,
      pageNum: currentPage,
      pageSize: DefaultPageSize
    };
    try {
      const responseData = await ajax({
        api: 'productList',
        method: 'post', //TODO:get
        type: 'json',
        data: JSON.stringify(queryData),
        contentType: 'application/json',
        headers: getCustomHeader()
      });

      await setLoading(false);
      if (responseData.success) {
        await setData(responseData.model.searchResult);
        await setTotalPage(responseData.model.total);
      } else {
        Dialog.alert({
          title: '请求失败！',
          content: responseData.errorMsg || `系统错误请稍后再试~`
        });
      }
    } catch (e) {
      await setLoading(false);
    }
  });

  const handlePaginationChange = async destPage => {
    const stateData = {
      status: currentStatus,
      categoryId: currentCategoryId,
      itemId: currentItemId,
      storeId: currentStoreId,
      keyWord: currentKeyWord
    };
    const url =
      location.protocol +
      '//' +
      location.host +
      location.pathname +
      '?' +
      objToUrl({ ...stateData, pageNum: destPage, pageSize: DefaultPageSize });
    location.href = url;
    // await setCurrent(currentPage);
    // fetchData();
  };
  const objToUrl = obj => {
    let arr = [];
    for (let i in obj) {
      if (obj.hasOwnProperty(i) && obj[i] !== '') {
        arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]));
      }
    }
    return arr.join('&');
  };

  const handleSubmit = data => {
    const url =
      location.protocol +
      '//' +
      location.host +
      location.pathname +
      '?' +
      objToUrl({ ...data, pageNum: currentPage, pageSize: DefaultPageSize });
    location.href = url;
  };

  const handleClick = () => {
    location.href = '/portal/item/manage/itemPublishPage';
  };
  const handleEdit = record => {
    location.href =
      '/portal/item/manage/itemPublishPage?itemId=' + record.itemId;
  };
  const handleUpShelf = async record => {
    try {
      const responseData = await ajax({
        api: 'productOnline',
        method: 'post',
        type: 'json',
        contentType: 'application/json',
        data: JSON.stringify({
          operateItemId: record.itemId
          // operateSkuIdList: []
        }),
        headers: getCustomHeader()
      });

      if (responseData.success) {
        fetchData({
          status: currentStatus,
          categoryId: currentCategoryId,
          storeId: currentStoreId,
          keyWord: currentKeyWord,
          itemId: currentItemId
        });
      } else {
        Dialog.alert({
          title: '操作失败！',
          content: responseData.errorMsg || `系统错误请稍后再试~`
        });
      }
    } catch (e) {
      Dialog.alert({
        title: '操作失败！',
        content: `系统错误请稍后再试~`
      });
    }
  };

  const handleDownShelf = async record => {
    try {
      const responseData = await ajax({
        api: 'productOffline',
        method: 'post',
        type: 'json',
        contentType: 'application/json',
        data: JSON.stringify({
          operateItemId: record.itemId
          // operateSkuIdList: []
        }),
        headers: getCustomHeader()
      });

      if (responseData.success) {
        fetchData({
          status: currentStatus,
          categoryId: currentCategoryId,
          storeId: currentStoreId,
          keyWord: currentKeyWord,
          itemId: currentItemId
        });
      } else {
        Dialog.alert({
          title: '操作失败！',
          content: responseData.errorMsg || `系统错误请稍后再试~`
        });
      }
    } catch (e) {
      Dialog.alert({
        title: '操作失败！',
        content: `系统错误请稍后再试~`
      });
    }
  };
  const handleDelete = record => {
    Dialog.confirm({
      title: '提示',
      content: '确认删除商品' + record.title + '吗？',
      onOk: async () => {
        try {
          const responseData = await ajax({
            api: 'productDelete',
            method: 'post',
            type: 'json',
            contentType: 'application/json',
            data: JSON.stringify({
              operateItemId: record.itemId
              // operateSkuIdList: []
            }),
            headers: getCustomHeader()
          });

          if (responseData.success) {
            fetchData({
              status: currentStatus,
              categoryId: currentCategoryId,
              storeId: currentStoreId,
              keyWord: currentKeyWord,
              itemId: currentItemId
            });
          } else {
            Dialog.alert({
              title: '操作失败！',
              content: responseData.errorMsg || `系统错误请稍后再试~`
            });
          }
        } catch (e) {
          Dialog.alert({
            title: '操作失败！',
            content: `系统错误请稍后再试~`
          });
        }
      }
    });
  };
  const renderOper = (value, index, record) => {
    return (
      <div>
        {record.status !== -1 ? (
          <Button
            type="primary"
            className={styles.btn}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
        ) : null}
        {record.status === -2 ? (
          <Button className={styles.btn} onClick={() => handleUpShelf(record)}>
            上架
          </Button>
        ) : null}
        {record.status === 1 ? (
          <Button
            className={styles.btn}
            onClick={() => handleDownShelf(record)}
          >
            下架
          </Button>
        ) : null}
        {record.status === -2 ? (
          <Button type="normal" warning onClick={() => handleDelete(record)}>
            删除
          </Button>
        ) : null}
      </div>
    );
  };
  const renderStatus = (value, index, record) => {
    if (value === 1) return <span className={styles.greenStatus}>已上架</span>;
    if (value === -1) return <span className={styles.greenStatus}>已删除</span>;
    if (value === -2) return <span className={styles.greenStatus}>已下架</span>;
    return null;
  };
  return (
    <div className={styles.container}>
      <PageHead title="商品管理" buttonText="添加商品" onClick={handleClick} />
      <IceContainer>
        <Filter
          onSubmit={handleSubmit}
          defaultData={{
            status: currentStatus,
            categoryId: currentCategoryId,
            itemId: currentItemId,
            storeId: currentStoreId,
            keyWord: currentKeyWord
          }}
        />
      </IceContainer>
      <IceContainer>
        <Table loading={isLoading} dataSource={data} hasBorder={false}>
          <Table.Column title="商品ID" dataIndex="itemId" width={180} />
          <Table.Column title="商品名称" dataIndex="title" />
          <Table.Column
            title="类目名称"
            dataIndex="leafCategoryName"
            width={100}
          />
          <Table.Column
            title="创建时间"
            dataIndex="gmtCreateText"
            width={100}
          />
          <Table.Column title="门店名称" dataIndex="storeName" width={100} />
          <Table.Column
            title="状态"
            dataIndex="status"
            cell={renderStatus}
            width={100}
          />
          <Table.Column
            title="操作"
            width={250}
            dataIndex="oper"
            cell={renderOper}
          />
        </Table>
        {totalPage > 0 ? (
          <Pagination
            className={styles.pagination}
            current={currentPage}
            pageSize={DefaultPageSize}
            total={totalPage}
            onChange={handlePaginationChange}
          />
        ) : null}
      </IceContainer>
    </div>
  );
}
