import { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { Button, Table, Image, Tooltip } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import { CommentOutlined } from '@ant-design/icons';
import { OrderManageAPI } from '~/api';
import { mallOrderListType } from '~/api/interface/orderManageType';
import { InterListType, InterReqType } from '~/api/interface';
import SureOrder from './components/sureOrder';
import ApprovalOrder from './components/approvalOrder';
import ShipmentsOrder from './components/shipmentsOrder';
import RemarkModal from '~/pages/orderManage/productOrder/orderList/components/remarkModal';
import TableItem from '~/components/order/selfTableItem';
import { filterObjAttr } from '~/utils';
import './index.scss';
import qs from 'query-string';

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

function ProductOrderView() {
  // 路由钩子
  const navigate = useNavigate();
  // 订单状态搜索列表
  const [tranStatusList, setTranStatusList] = useState<
    { value: number | undefined; label: string }[]
  >([]);
  // 订单操作按钮列表
  const operateBtnList = [
    {
      btnStr: '确认订单',
      status: 200,
      btnClick: (record: TableType[0]) => {
        setCurrentOrderItem({ ...record });
        setSureOrderShow(true);
      },
    },
    {
      btnStr: '发货',
      status: 500,
      btnClick: (record: TableType[0]) => {
        getMallOrderDetail(record.id);
        setShipmentsOrderShow(true);
      },
    },
  ];

  // 订单状态
  const [orderStatusList, setOrderStatusList] = useState<{ value: number; label: string }[]>([]);
  // 当前选择的是第几个按钮
  const [statusCodeButtonIndex, setStatusCodeButtonIndex] = useState<number>(0);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  const [currentOrderItem, setCurrentOrderItem] = useState<TableType[0]>();
  const [loading, setLoading] = useState<boolean>(false);

  // 订单流程操作
  const [sureOrderShow, setSureOrderShow] = useState<boolean>(false); //确认订单
  const [approvalOrderShow, setApprovalOrderShow] = useState<boolean>(false); //审核
  const [shipmentsOrderShow, setShipmentsOrderShow] = useState<boolean>(false); //发货
  const [remarkModalShow, setRemarkModalShow] = useState<boolean>(false);

  // 加载列表
  const getTableList = (value = {}) => {
    setLoading(true);
    // 只需要修改这个地方的接口即可
    OrderManageAPI.getMallOrderList({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      const { list, pageNo, totalCount, pageSize, totalPage } = result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list);
    });
  };
  // 获取订单详情
  const getMallOrderDetail = (id: number) => {
    OrderManageAPI.getMallOrderDetail({ id }).then(({ result }) => {
      setCurrentOrderItem(result);
    });
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize });
  };
  // 表单提交
  const onFinish = (data: ReqType) => {
    pagination.current = 1;
    query = {
      ...filterObjAttr(data, ['rangeTime']),
      statusCode: tranStatusList[statusCodeButtonIndex].value,
    };
    getTableList();
  };
  // 订单状态筛选
  const statusChangeEvent = (i: number) => {
    pagination.current = 1;
    pagination.pageSize = 10;
    setStatusCodeButtonIndex(i);
    query = { ...query, statusCode: tranStatusList[i].value };
    getTableList();
  };
  // 跳转订单详情
  const handleDetail = (record: TableType[0]) => {
    navigate(`/orderManage/productOrder/detail?${qs.stringify({ id: record.id })}`);
  };
  // 获取商城订单状态列表
  const getMallOrderStatusList = () => {
    OrderManageAPI.getMallOrderStatusList().then(({ result }) => {
      if (result) {
        const list = result.map((item) => ({ value: item.code, label: item.status }));
        setOrderStatusList(list);
        setTranStatusList([{ label: '全部', value: undefined }, ...list]);
      }
    });
  };
  // 确认订单
  const sureOrderCancel = () => {
    setSureOrderShow(false);
  };
  const sureOrderOk = () => {
    setSureOrderShow(false);
    getTableList(query);
  };
  // 凭证审批
  const showApprovalModalClick = (record: TableType[0]) => {
    getMallOrderDetail(record.id);
    setApprovalOrderShow(true);
  };
  const approvalOrderOk = () => {
    setApprovalOrderShow(false);
    getTableList(query);
  };
  const approvalOrderCancel = () => {
    setApprovalOrderShow(false);
  };
  // 发货
  const shipmentsOrderCancel = () => {
    setShipmentsOrderShow(false);
  };
  const shipmentsOrderOk = () => {
    setShipmentsOrderShow(false);
    getTableList(query);
  };
  // 卖家备注
  const showRemarkModalClick = (record: TableType[0]) => {
    setCurrentOrderItem({ ...record });
    setRemarkModalShow(true);
  };
  const remarkModalOk = () => {
    setRemarkModalShow(false);
    getTableList(query);
  };
  const remarkModalCancel = () => {
    setRemarkModalShow(false);
  };

  // 获取当前操作按钮
  const getCurrentOperateBtn = (status: number) => {
    return operateBtnList.find((v) => v.status === status);
  };
  // 判断是否还要审批付款凭证
  const isContinueApprove = (record: TableType[0]) => {
    return record.payDTOList?.some((v) => v.checkStatus === 0);
  };

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

  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '商品',
      dataIndex: 'userName',
      align: 'center',
      width: 280,
      fixed: 'left',
      render: (_text, record) => (
        <TableItem
          td={
            <div>
              <span>订单编号：</span>
              <span>{record.orderNo}</span>
            </div>
          }
          tr={record.skuDTOList.map((v) => (
            <div key={v.id} className='mall-sku-item'>
              <Image src={v.skuImage} className='sku-img' />
              <div className='sku-info'>
                <div className='info-name'>{v.tradeName}</div>
                <div className='info-spec'>
                  {Object.entries(JSON.parse(v.productSpec)).map((v, index) => (
                    <span key={index}>{v.join('：')}</span>
                  ))}
                </div>
              </div>
            </div>
          ))}
        />
      ),
    },
    {
      title: '订单金额(元)',
      dataIndex: 'orderTotalAmount',
      align: 'center',
      render: (text) => (
        <TableItem tr={<div className='goods-text'>￥{text?.toLocaleString()}</div>} />
      ),
    },
    {
      title: '数量',
      align: 'center',
      width: '15%',
      render: (_text, record) => (
        <TableItem
          td={
            <div>
              <span>创建时间:</span>
              <span>{record.createTime}</span>
            </div>
          }
          tr={record.skuDTOList.map((v) => (
            <div key={v.id} className='goods-text'>
              {v.orderNum}
            </div>
          ))}
        />
      ),
    },
    {
      title: '单价',
      align: 'center',
      render: (_text, record) => (
        <TableItem
          tr={record.skuDTOList.map((v) => (
            <div key={v.id} className='goods-text'>
              ¥{v.unitPrice?.toLocaleString()}
            </div>
          ))}
        />
      ),
    },
    {
      title: '订单类型',
      align: 'center',
      dataIndex: 'orderType',
      render: (text) => (
        <TableItem tr={<div className='goods-text'>{text ? '意向订单' : '正常订单'}</div>} />
      ),
    },
    {
      title: '实际支付',
      dataIndex: 'otherAmount',
      align: 'center',
      render: (text) => (
        <TableItem tr={<div className='goods-text'>¥{text?.toLocaleString()}</div>} />
      ),
    },
    {
      title: '抵扣云享金',
      dataIndex: 'shareAmount',
      align: 'center',
      render: (text) => (
        <TableItem tr={<div className='goods-text'>¥{text?.toLocaleString()}</div>} />
      ),
    },
    {
      title: '抵扣佣金',
      dataIndex: 'salaryAmount',
      align: 'center',
      render: (text) => (
        <TableItem tr={<div className='goods-text'>¥{text?.toLocaleString()}</div>} />
      ),
    },
    {
      title: '买家',
      dataIndex: 'uid',
      align: 'center',
      width: '10%',
      render: (_text: any, 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',
      render: (text) => (
        <TableItem
          tr={
            <div className='goods-text'>
              {orderStatusList.find((i) => i.value === text)?.label || text}
            </div>
          }
        />
      ),
    },
    {
      title: '推荐人',
      dataIndex: 'userName',
      align: 'center',
      render: (_text) => <TableItem tr={<div className='goods-text'>--</div>} />,
    },
    {
      title: '订单交期',
      dataIndex: 'deliveryTime',
      align: 'center',
      render: (text: string) => <TableItem tr={<div className='goods-text'>{text}</div>} />,
    },
    {
      title: '备注',
      dataIndex: 'sellerRemark',
      align: 'center',
      width: 150,
      ellipsis: true,
      render: (text, record) => (
        <TableItem
          tr={
            <div
              onClick={() => showRemarkModalClick(record)}
              className='goods-text mall-order-remark'
            >
              {text || '--'}
            </div>
          }
        />
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      // align: 'right',
      fixed: 'right',
      width: '10%',
      onHeaderCell: () => ({
        style: {
          textAlign: 'center',
        },
      }),
      onCell: () => ({
        style: {
          textAlign: 'right',
        },
      }),
      render: (_text, record) => (
        <TableItem
          tr={
            <>
              {getCurrentOperateBtn ? (
                <Button
                  type={'link'}
                  onClick={() => getCurrentOperateBtn(record.statusCode)?.btnClick(record)}
                >
                  {getCurrentOperateBtn(record.statusCode)?.btnStr}
                </Button>
              ) : (
                ''
              )}
              {[420].includes(record.statusCode) || isContinueApprove(record) ? (
                <Button type='link' onClick={() => showApprovalModalClick(record)}>
                  凭证审批
                </Button>
              ) : (
                ''
              )}
              <Button type={'link'} onClick={() => handleDetail(record)}>
                详情
              </Button>
            </>
          }
        />
      ),
    },
  ];
  return (
    <div className='product-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' }}
                >
                  {i.label}
                </Button>
              );
            })}
          </>
        }
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1200 }}
        loading={loading}
        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} 条数据`,
        }}
      />
      {/*确认订单*/}
      <SureOrder
        open={sureOrderShow}
        onCancel={sureOrderCancel}
        onOk={sureOrderOk}
        mallOrderItem={currentOrderItem}
      />
      {/*凭证审批*/}
      <ApprovalOrder
        open={approvalOrderShow}
        onCancel={approvalOrderCancel}
        onOk={approvalOrderOk}
        mallOrderItem={currentOrderItem}
      />
      {/*发货*/}
      <ShipmentsOrder
        open={shipmentsOrderShow}
        onCancel={shipmentsOrderCancel}
        onOk={shipmentsOrderOk}
        currentOrderItem={currentOrderItem}
      />
      {/*卖家备注*/}
      <RemarkModal
        open={remarkModalShow}
        onOk={remarkModalOk}
        onCancel={remarkModalCancel}
        mallOrderItem={currentOrderItem}
      />
    </div>
  );
}

export default ProductOrderView;
