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/order/productOrder/sureOrder';
import ApprovalOrder from '~/components/order/productOrder/approvalOrder';
import ShipmentsOrder from '~/components/order/productOrder/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';
import { useSelector } from 'react-redux';
import dayjs from 'dayjs';

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

function ProductOrderView() {
  // 路由钩子
  const navigate = useNavigate();
  const { userInfo } = useSelector((state: any) => state.UserInfo);

  // 订单状态搜索列表
  const [tranStatusList, setTranStatusList] = useState<
    { value: number | undefined; label: string }[]
  >([]);
  // 订单操作按钮列表
  const operateBtnList = [
    {
      getBtnStr: () => (userInfo.companyInfoVO.companyType === 0 ? '确认订单' : ''),
      status: 200,
      btnClick: (record: TableType[0]) => {
        setCurrentOrderItem({ ...record });
        setSureOrderShow(true);
      },
    },
    {
      getBtnStr: (record: TableType[0]) => (record.orderType ? '' : '发货'),
      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 = (item: { label: string; value: number | undefined }, i: number) => {
    pagination.current = 1;
    pagination.pageSize = 10;
    setStatusCodeButtonIndex(i);
    query = { ...query, statusCode: item.value };
    getTableList();
  };
  // 跳转订单详情
  const handleDetail = (record: TableType[0]) => {
    navigate(`/mallManage/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 },
          ...(userInfo.companyInfoVO.companyType === 0
            ? list
            : list.filter((v) => ![200, 300, 420].includes(v.value as number))),
        ]);
      }
    });
  };
  // 确认订单
  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',
      width: 280,
      render: (text, record) => (
        <TableItem
          td={
            <div>
              <span>创建时间:</span>
              <span>{record.createTime}</span>
            </div>
          }
          tr={<div className='goods-text'>￥{text?.toLocaleString()}</div>}
        />
      ),
    },
    {
      title: '数量',
      align: 'center',
      width: '100px',
      render: (_text, record) => (
        <TableItem
          tr={record.skuDTOList.map((v) => (
            <div key={v.id} className='goods-text'>
              {v.orderNum}
            </div>
          ))}
        />
      ),
    },
    {
      title: '单价',
      align: 'center',
      width: '200px',
      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',
      width: '100px',
      render: (text) => (
        <TableItem tr={<div className='goods-text'>{text ? '意向订单' : '正常订单'}</div>} />
      ),
    },
    {
      title: '实际支付',
      width: '200px',
      dataIndex: 'otherAmount',
      align: 'center',
      render: (text) => (
        <TableItem tr={<div className='goods-text'>¥{text?.toLocaleString()}</div>} />
      ),
    },
    {
      title: '抵扣云享金',
      width: '200px',
      dataIndex: 'shareAmount',
      align: 'center',
      render: (text) => (
        <TableItem tr={<div className='goods-text'>¥{text?.toLocaleString()}</div>} />
      ),
    },
    {
      title: '抵扣佣金',
      width: '200px',
      dataIndex: 'salaryAmount',
      align: 'center',
      render: (text) => (
        <TableItem tr={<div className='goods-text'>¥{text?.toLocaleString()}</div>} />
      ),
    },
    {
      title: '买家',
      dataIndex: 'uid',
      align: 'center',
      width: '200px',
      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',
      width: '100px',
      render: (text) => (
        <TableItem tr={<div>{orderStatusList.find((i) => i.value === text)?.label || text}</div>} />
      ),
    },
    {
      title: '推荐人',
      dataIndex: 'userName',
      width: '100px',
      align: 'center',
      render: (_text) => <TableItem tr={<div className='goods-text'>--</div>} />,
    },
    {
      title: '订单交期',
      width: '100px',
      dataIndex: 'deliveryTime',
      align: 'center',
      render: (text: string) => (
        <TableItem tr={<div> {text ? dayjs(text).format('YYYY-MM-DD') : '--'}</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: '150px',
      onHeaderCell: () => ({
        style: {
          textAlign: 'center',
        },
      }),
      onCell: () => ({
        style: {
          textAlign: 'right',
        },
      }),
      render: (_text, record) => (
        <TableItem
          tr={
            <>
              {getCurrentOperateBtn(record.statusCode)?.getBtnStr(record) ? (
                <Button
                  type={'link'}
                  onClick={() => getCurrentOperateBtn(record.statusCode)?.btnClick(record)}
                >
                  {getCurrentOperateBtn(record.statusCode)?.getBtnStr(record)}
                </Button>
              ) : (
                ''
              )}
              {([420].includes(record.statusCode) || isContinueApprove(record)) &&
              userInfo.companyInfoVO.companyType === 0 ? (
                <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(i, 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}
        orderItem={currentOrderItem}
        type={1}
      />
      {/*凭证审批*/}
      <ApprovalOrder
        open={approvalOrderShow}
        onCancel={approvalOrderCancel}
        onOk={approvalOrderOk}
        mallOrderItem={currentOrderItem}
        type={1}
      />
      {/*发货*/}
      <ShipmentsOrder
        open={shipmentsOrderShow}
        onCancel={shipmentsOrderCancel}
        onOk={shipmentsOrderOk}
        currentOrderItem={currentOrderItem}
        type={1}
      />
      {/*卖家备注*/}
      <RemarkModal
        open={remarkModalShow}
        onOk={remarkModalOk}
        onCancel={remarkModalCancel}
        mallOrderItem={currentOrderItem}
      />
    </div>
  );
}

export default ProductOrderView;
