import { TabsProps, Tabs, Row, Col, Image, Space, Button, Pagination, Empty, Spin } from 'antd';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import errImg from '~/assets/errImg';
import LayoutView from '~/components/layout';
import Sider from '../components/sider';
import styles from './index.module.scss';
import api, { LeasingList, ListTranStatusResp } from './api';
import moment from 'moment';
import PayModal from './components/payModal';
import RefundModal from './components/refundModal';
import Moment from 'moment';

const items: TabsProps['items'] = [
  {
    key: '',
    label: `全部`,
  },
  {
    key: '100',
    label: `待付款`,
  },
  {
    key: '200',
    label: `待发货`,
  },
  {
    key: '400',
    label: `租赁中`,
  },
  {
    key: '500',
    label: `归还中`,
  },
  {
    key: '600',
    label: `已完成`,
  },
  {
    key: '700',
    label: `退款/售后`,
  },
  {
    key: '999',
    label: `已关闭`,
  },
];

export default function LeasingOrders() {
  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<LeasingList[]>([]);
  const [loading, setLoading] = useState(false);
  const [tranStatusMap, setTranStatusMap] = useState<ListTranStatusResp[]>([]); //订单状态字典
  const [openPayModal, setOpenPayModal] = useState(false); //支付弹窗
  const [openRefundModal, setOpenRefundModal] = useState(false); //退款弹窗
  const [orderNo, setOrderNo] = useState<string | undefined>();

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

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

  //商品列表请求
  useEffect(() => {
    if (!abort) {
      return;
    }
    setLoading(true);
    api
      .listPageWechatOrder(
        {
          ...pageParams,
          tranStatus: 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);
  };

  // 交易状态对应的按钮渲染
  const statusBtn = function (item: LeasingList) {
    switch (item.tranStatus) {
      case '100':
        return (
          <Button
            className={styles.btn2}
            type='primary'
            onClick={() => {
              setOrderNo(item.orderNo);
              setOpenPayModal(true);
            }}
          >
            立即付款
          </Button>
        );

      case '200':
        return (
          <Button
            className={styles.btn1}
            onClick={() => {
              setOrderNo(item.orderNo);
              setOpenRefundModal(true);
            }}
          >
            申请退款
          </Button>
        );

      case '300':
        return (
          <Space size={0} direction='vertical' align='center'>
            <Button className={styles.btn2} type='primary'>
              确认收货
            </Button>
            <Button type='link' style={{ fontSize: 10 }}>
              查看物流
            </Button>
          </Space>
        );

      case '400':
        return (
          <Space size={0} direction='vertical' align='center'>
            <Button className={styles.btn2} type='primary'>
              商品归还
            </Button>
            <Button type='link' style={{ fontSize: 10 }}>
              查看物流
            </Button>
          </Space>
        );

      case '500':
        <Button type='link' style={{ marginTop: 10 }}>
          查看物流
        </Button>;

      case '600':
        return <Button className={styles.btn1}>再来一单</Button>;
    }
  };

  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>
                            {Moment(item.startDate).format('YYYY-MM-DD')} 至{' '}
                            {Moment(item.endDate).format('YYYY-MM-DD')}
                          </div>
                          <div>订单编号: {item.orderNo}</div>
                        </Space>{' '}
                      </div>
                      <div className={styles.font3}>
                        {tranStatusMap.find((sItem) => sItem.status === item.tranStatus)?.waiting}
                      </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.wareImg}
                            ></Image>
                          </div>

                          <div style={{ marginTop: 12 }}>
                            <div className={`ellipsis1 ${styles.font4}`}>{item.wareTitle}</div>
                            <div
                              className={`${styles.font5} ${styles.ellipse2}`}
                              style={{ marginTop: 5 }}
                            >
                              {item.wareDescription}
                            </div>
                          </div>
                        </Row>
                      </Col>
                      <Col
                        style={{
                          width: 270,
                          borderLeft: '1px solid #D0EAF5',
                          borderRight: '1px solid #D0EAF5',
                        }}
                      >
                        <Row justify={'center'} align='middle' style={{ height: '100%' }}>
                          <div style={{ textAlign: 'center' }}>
                            <div className={styles.font7} style={{ marginBottom: 7 }}>
                              ¥{item.shouldPay}
                            </div>
                            <div className={styles.font6}>
                              租期: {moment(item.endDate).diff(item.startDate, 'days')}天
                            </div>
                            <div className={styles.font6}>数量: {item.wareNum}件</div>
                          </div>
                        </Row>
                      </Col>
                      <Col flex={'auto'} style={{}}>
                        <Space
                          size={7}
                          style={{
                            float: 'right',
                            marginTop: 20,
                            marginRight: 24,
                          }}
                        >
                          {statusBtn(item)}
                        </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>
      <PayModal
        open={openPayModal}
        onCancel={() => setOpenPayModal(false)}
        orderNo={orderNo}
      ></PayModal>
      <RefundModal
        open={openRefundModal}
        onCancel={() => setOpenRefundModal(false)}
        orderNo={orderNo}
      ></RefundModal>
    </>
  );
}
