import { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { Button, Image, Table, Tooltip } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import qs from 'query-string';
import { InterListType, InterReqType } from '~/api/interface';
import { rentOrderListType } from '~/api/interface/orderManageType';
import { OrderManageAPI } from '~/api';
import ShipmentsOrder from './comp/shipmentsOrder';
import ConfirmReturn from './comp/confirmReturn';
import TableItem from '~/components/order/selfTableItem';
import './index.scss';
import { filterObjAttr } from '~/utils';
import dayjs from 'dayjs';
import { CommentOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';

// 表格数据类型
type TableType = InterListType<rentOrderListType>;
// 请求数据的类型
type ReqType = InterReqType<rentOrderListType>;
// 搜索表单的数据
let query: ReqType = {};

function EquipmentOrderView() {
  // 路由钩子
  const navigate = useNavigate();
  const { userInfo } = useSelector((state: any) => state.UserInfo);
  // 发货弹窗是否显示
  const [deliverVisible, setDeliverVisible] = useState<boolean>(false);
  // 确认归还
  const [confirmReturnShow, setConfirmReturnShow] = useState<boolean>(false);
  // 当前选择的是第几个按钮
  const [statusCodeButtonIndex, setStatusCodeButtonIndex] = useState<number>(0);
  // 订单状态搜索列表
  const [tranStatusList, setTranStatusList] = useState<
    { value: string | undefined; label: string }[]
  >([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 需要编辑的数据
  const [currentOrderItem, setCurrentOrderItem] = useState<TableType[0]>();
  // 加载列表
  const getTableList = (value = {}) => {
    // 只需要修改这个地方的接口即可
    OrderManageAPI.getRentOrderList({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    }).then(({ result }) => {
      const { list, pageNo, totalCount, pageSize, totalPage } = result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list);
    });
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize });
  };
  // 表单提交
  const onFinish = (data: ReqType) => {
    pagination.current = 1;
    query = filterObjAttr(data, ['rangeTime']);
    getTableList(query);
  };
  // 订单状态筛选
  const statusChangeEvent = (i: number) => {
    if (i === statusCodeButtonIndex) {
      setStatusCodeButtonIndex(0);
    } else {
      setStatusCodeButtonIndex(i);
    }
    query = { ...query, statusCode: Number(tranStatusList[i].value) };
    getTableList();
  };
  // 跳转订单详情
  const handleDetail = (record: TableType[0]) => {
    const search = { id: record.id, orderNo: record.orderNo };
    navigate(`/orderManage/equipmentOrder/detail?${qs.stringify(search)}`);
  };
  // 获取订单状态
  const getOrderStatus = () => {
    OrderManageAPI.getRentOrderDict().then(({ result }) => {
      const arr = result.map((item) => ({ value: item.status, label: item.waiting }));
      setTranStatusList([{ value: undefined, label: '全部订单' }, ...arr]);
    });
  };
  // 获取租赁订单详情
  const getRentDetail = (id: number) => {
    OrderManageAPI.getRentOrderDetail({ id }).then(({ result }) => {
      if (result) {
        setCurrentOrderItem(result);
      }
    });
  };

  // componentDidMount
  useEffect(() => {
    query = {};
    getOrderStatus();
    getTableList();
  }, []);

  // 操作按钮列表
  const operateBtnList = [
    {
      label: '发货',
      status: 200,
      onClick: (item: TableType[0]) => {
        getRentDetail(item.id);
        setDeliverVisible(true);
      },
    },
    {
      label: '确认归还',
      status: 500,
      onClick: (item: TableType[0]) => {
        getRentDetail(item.id);
        setConfirmReturnShow(true);
      },
    },
    {
      label: '确认退款',
      status: 800,
      onClick: (item: TableType[0]) => {
        getRentDetail(item.id);
        setConfirmReturnShow(true);
      },
    },
  ];
  // 获取当前按钮对象
  const getOperateBtnItem = (code: number) => {
    return operateBtnList.find((i) => i.status === code);
  };
  // 发货
  const shipmentsOrderOk = () => {
    setDeliverVisible(false);
    getTableList(query);
  };
  const shipmentsOrderCancel = () => {
    setDeliverVisible(false);
  };
  //确认归还
  const confirmReturnCancel = () => {
    setConfirmReturnShow(false);
  };
  const confirmReturnOk = () => {
    setConfirmReturnShow(false);
    getTableList(query);
  };

  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '商品',
      align: 'center',
      width: '300px',
      fixed: 'left',
      render: (_text, record) => (
        <TableItem
          tr={
            <div className='mall-sku-item'>
              <Image src={record.skuImg} className='sku-img' />
              <div className='sku-info'>
                <div className='info-name'>{record.orderName}</div>
                <div className='info-spec'>
                  {Object.entries(JSON.parse(record.sku)).map((v, index) => (
                    <span key={index}>{v.join('：')}</span>
                  ))}
                </div>
              </div>
            </div>
          }
          td={
            <div>
              <span>订单编号：</span>
              <span>{record.orderNo}</span>
            </div>
          }
        />
      ),
    },
    {
      title: '租期',
      align: 'center',
      width: '200px',
      render: (_text, record) => (
        <TableItem
          tr={
            <div>
              <div>{`${record.startDate}至${record.endDate}`}</div>
              <div>({dayjs(record.endDate).diff(dayjs(record.startDate), 'day')}天)</div>
            </div>
          }
          td={<div>{`创建时间:${record.createTime}`}</div>}
        />
      ),
    },
    {
      title: '数量',
      align: 'center',
      dataIndex: 'wareNum',
      width: 100,
      render: (text) => <TableItem tr={text} />,
    },
    {
      title: '单价',
      width: 200,
      align: 'center',
      dataIndex: 'unitPrice',
      render: (text) => <TableItem tr={<span>¥{text?.toLocaleString()}</span>} />,
    },
    {
      title: '买家',
      align: 'center',
      width: '130px',
      render: (_text, record) => (
        <TableItem
          tr={
            <div>
              <div>
                {record.userName || record.nickname}({record.userAccountId})
              </div>
              <div>{record.phoneNum}</div>
              {record.userRemark ? (
                <div>
                  <Tooltip placement='top' title={record.userRemark}>
                    <Button icon={<CommentOutlined />}></Button>
                  </Tooltip>
                </div>
              ) : (
                ''
              )}
            </div>
          }
        />
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'statusCode',
      align: 'center',
      width: '100px',
      render: (text: number) => (
        <TableItem tr={tranStatusList.find((v) => v.value === String(text))?.label} />
      ),
    },
    {
      title: '押金',
      dataIndex: 'deposit',
      align: 'center',
      width: '200px',
      render: (text: number, record) => (
        <TableItem
          tr={
            <div>
              <div>￥{(text * record.wareNum).toLocaleString()}</div>
              <div>
                {record.shareCashPledge ? (
                  <span>云享金抵扣：￥{record.shareCashPledge.toLocaleString()}</span>
                ) : (
                  ''
                )}
                {record.salaryCashPledge ? (
                  <span>余额抵扣：￥{record.salaryCashPledge.toLocaleString()}</span>
                ) : (
                  ''
                )}
              </div>
            </div>
          }
        />
      ),
    },
    {
      title: '实付款',
      dataIndex: 'orderTotalAmount',
      align: 'center',
      width: '200px',
      render: (text, record) => (
        <TableItem
          tr={
            <div>
              <div>￥{text.toLocaleString()}</div>
              <div>
                {record.shareAmount ? (
                  <span>云享金抵扣：￥{record.shareAmount.toLocaleString()}</span>
                ) : (
                  ''
                )}
                {record.salaryAmount ? (
                  <span>余额抵扣：￥{record.salaryAmount.toLocaleString()}</span>
                ) : (
                  ''
                )}
              </div>
            </div>
          }
        />
      ),
    },
    {
      title: '推荐人',
      dataIndex: 'userName',
      align: 'center',
      width: 200,
      render: (_text, _record) => <TableItem tr={''} />,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
      ellipsis: true,
      width: '100px',
      render: (text) => <TableItem tr={text} />,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: '130px',
      onHeaderCell: () => ({
        style: {
          textAlign: 'center',
        },
      }),
      onCell: () => ({
        style: {
          textAlign: 'right',
        },
      }),
      render: (_text, record) => (
        <TableItem
          tr={
            <>
              {getOperateBtnItem(record.statusCode) ? (
                <Button
                  type='link'
                  onClick={() => getOperateBtnItem(record.statusCode)?.onClick(record)}
                  disabled={!!userInfo.roleInfo.superAdmin}
                >
                  {getOperateBtnItem(record.statusCode)?.label}
                </Button>
              ) : (
                ''
              )}
              <Button type='link' onClick={() => handleDetail(record)}>
                详情
              </Button>
            </>
          }
        />
      ),
    },
  ];
  return (
    <div className='equipment-order'>
      <SearchBox
        search={[
          {
            label: '关键字',
            name: 'keyword',
            type: 'input',
            placeholder: '请输入订单编号',
          },
          {
            label: '时间',
            name: 'rangeTime',
            type: 'rangePicker',
            placeholder: '请选择创建时间',
          },
        ]}
        searchData={onFinish}
        sufFixBtn={
          <>
            {tranStatusList?.map((i, j) => {
              return (
                <Button
                  key={j}
                  type={j === statusCodeButtonIndex ? 'primary' : 'default'}
                  onClick={() => statusChangeEvent(j)}
                  style={{ marginTop: '5px', marginBottom: '5px' }}
                >
                  {i.label}
                </Button>
              );
            })}
          </>
        }
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1200 }}
        pagination={{
          total: pagination.total,
          pageSize: pagination.pageSize,
          current: pagination.current,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
        // rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
      />
      {/*发货*/}
      <ShipmentsOrder
        open={deliverVisible}
        currentOrderItem={currentOrderItem}
        onCancel={shipmentsOrderCancel}
        onOk={shipmentsOrderOk}
      />
      {/*确认归还*/}
      <ConfirmReturn
        open={confirmReturnShow}
        onOk={confirmReturnOk}
        onCancel={confirmReturnCancel}
        currentOrderItem={currentOrderItem}
        modalTitle={currentOrderItem?.statusCode === 500 ? '确认归还' : '确认退款'}
      />
    </div>
  );
}

export default EquipmentOrderView;
