import { useEffect, useState } from 'react';

import { TabsProps, Tabs, Row, Col, Image, Space, Button, Spin, Pagination, Empty } from 'antd';
import { useRouter } from 'next/router';

import errImg from '~/assets/errImg';
import LayoutView from '~/components/layout';

import api, { OrderList, ListStatusResp } from './api';
import styles from './index.module.scss';
import Sider from '../components/sider';

const items: TabsProps['items'] = [
  {
    key: '',
    label: `全部`,
  },
  {
    key: '0',
    label: `意向沟通`,
  },
  {
    key: '1',
    label: `签约付款`,
  },
  {
    key: '2',
    label: `待发货`,
  },
  {
    key: '3',
    label: `待收货`,
  },
];

export default function LeasingOrder() {
  const router = useRouter();
  const [pageParams, setPageParams] = useState({
    pageNo: 1,
    pageSize: 5,
  }); // 分页器对象
  const [total, setTotal] = useState(0); // 总数
  const [abort, setAbort] = useState<AbortController | null>(null); // 请求中断对你
  const [tabKey, setTabKey] = useState('');
  const [orderList, setOrderList] = useState<OrderList[]>([]);
  const [loading, setLoading] = useState(false);
  const [orderNo, setOrderNo] = useState<string | undefined>();
  const [tranStatusMap, setTranStatusMap] = useState<ListStatusResp[]>([]); // 订单状态字典

  // 获取订单状态字典
  useEffect(() => {
    api.listStatus().then((res) => {
      setTranStatusMap(res.result || []);
    });
  }, []);

  useEffect(() => {
    // 中断前一次列表请求
    abort?.abort();
    setAbort(new AbortController());
  }, [pageParams]);

  // 商品列表请求
  useEffect(() => {
    if (!abort) {
      return;
    }
    setLoading(true);
    api
      .listPage(
        {
          ...pageParams,
          showType: Number(tabKey),
        },
        {
          signal: abort?.signal,
        },
      )
      .then((res) => {
        setOrderList(res.result?.list || []);
        setTotal(res.result?.totalCount || 0);
        setLoading(false);
      });
  }, [abort]);

  const onPageChange = (page: number, pageSize: number) => {
    setPageParams({
      ...pageParams,
      pageNo: page,
    });
  };

  const onTabsChange = (key: string) => {
    setTabKey(key);
    setPageParams({
      ...pageParams,
      pageNo: 1,
    });
    setTotal(0);
  };

  return (
    <>
      <LayoutView
        layoutStyle={{ backgroundColor: '#fff' }}
        contentStyle={{ width: 1000, marginLeft: 526 }}
        headerStyle={{ borderBottom: '1px solid #e2e2e2' }}
      >
        <Sider
          style={{
            position: 'absolute',
            left: -37,
            top: 15,
            transform: 'translateX(-100%)',
          }}
          selectedKeys={[router.pathname]}
        ></Sider>
        <div style={{ paddingTop: 19 }}>
          <div className={styles.font1}>商城订单</div>
          <Tabs activeKey={tabKey} items={items} onChange={onTabsChange} />
          <Spin spinning={loading} delay={500}>
            <ul className={styles.orderList} style={{ minHeight: 650 }}>
              {orderList.map((item) => {
                return (
                  <li key={item.id} className={styles.orderItem}>
                    <Row
                      justify='space-between'
                      align='middle'
                      style={{
                        height: 30,
                        padding: '0 26px 0 16px',
                        background: '#EBF8FF',
                      }}
                    >
                      <div className={styles.font2}>
                        <Space size={10}>
                          <div>{item.createTime}</div>
                          <div>订单编号: {item.orderNo}</div>
                        </Space>
                      </div>
                      <div className={styles.font3}>
                        {tranStatusMap.find((status) => status.code === item.statusCode)?.status}
                      </div>
                    </Row>
                    <Row style={{ minHeight: 100, border: '1px solid #D0EAF5' }}>
                      <Col style={{ width: 380 }}>
                        <Row>
                          <div style={{ margin: '10px 10px 0 16px' }}>
                            <Image
                              width={80}
                              height={80}
                              preview={false}
                              fallback={errImg}
                              src={item.orderMainImg}
                            ></Image>
                          </div>

                          <div style={{ marginTop: 12 }}>
                            <div className={`ellipsis1 ${styles.font4}`}>{item.orderName}</div>
                            {item.mallOrderProdListDTOList.map((spec) => {
                              return (
                                <div
                                  key={spec.id}
                                  className={styles.font5}
                                  style={{ marginTop: 5 }}
                                >
                                  {spec.prodSkuSpecName}: {spec.productName}
                                </div>
                              );
                            })}
                          </div>
                        </Row>
                      </Col>
                      <Col
                        style={{
                          width: 270,
                          borderLeft: '1px solid #D0EAF5',
                          borderRight: '1px solid #D0EAF5',
                        }}
                      >
                        <Row justify={'center'} align='middle' style={{ height: '100%' }}>
                          数量: {item.totalBuyNum}件
                        </Row>
                      </Col>
                      <Col flex={'auto'} style={{}}>
                        <Space
                          size={7}
                          style={{
                            float: 'right',
                            marginTop: 20,
                            marginRight: 24,
                          }}
                        >
                          <Button className={styles.btn1}>取消订单</Button>
                          <Button className={styles.btn2} type='primary'>
                            查看合同
                          </Button>
                        </Space>
                      </Col>
                    </Row>
                  </li>
                );
              })}
              {orderList.length === 0 && (
                <Empty
                  style={{
                    paddingTop: 20,
                    width: '100%',
                    textAlign: 'center',
                  }}
                ></Empty>
              )}
            </ul>
          </Spin>
          <Pagination
            current={pageParams.pageNo}
            showSizeChanger={false}
            showQuickJumper
            total={total}
            pageSize={pageParams.pageSize}
            onChange={onPageChange}
            hideOnSinglePage={true}
            style={{ marginTop: 20 }}
          ></Pagination>
        </div>
      </LayoutView>
    </>
  );
}
