import SearchBox from '~/components/search-box';
import { Button, Image, Table, Tooltip } from 'antd';
import { useEffect, useState } from 'react';
import { FddInterfaceAPI, OrderManageAPI } from '~/api';
import { ColumnsType } from 'antd/es/table/InternalTable';
import { useNavigate } from 'react-router-dom';
import { InterListType, InterReqListType, PaginationProps } from '~/api/interface';
import { listPurchaseOrderType } from '~/api/interface/orderManageType';
import TableItem from '~/components/order/selfTableItem';
import SureOrder from '~/components/order/productOrder/sureOrder';
import './index.scss';
import { filterObjAttr } from '~/utils';
import dayjs from 'dayjs';
import qs from 'query-string';
import IframeModal from '~/components/modal/iframeModal';
import { decode } from 'js-base64';
import UploadPayment from '~/pages/orderManage/procurementOrder/orderList/components/uploadPayment';
import ApprovalOrder from '~/components/order/productOrder/approvalOrder';
import ShipmentsOrder from '~/components/order/productOrder/shipmentsOrder';
import RemarkModal from './components/remarkModal';

import { useSelector } from 'react-redux';
import { CommentOutlined } from '@ant-design/icons';

// 采购订单列表返回类型
type procurementOrderListType = InterListType<listPurchaseOrderType>;
// 采购订单列表请求类型
type procurementOrderParamsType = InterReqListType<listPurchaseOrderType>;

const ProcurementOrderList = () => {
  const navigate = useNavigate();
  const { userInfo } = useSelector((state: any) => state.UserInfo);

  // 订单操作按钮列表
  const operateBtnList = [
    {
      btnStr: userInfo.companyInfoVO.companyType === 0 ? '确认订单' : '',
      status: 200,
      btnClick: (record: procurementOrderListType[0]) => {
        setCurrentOrderItem({ ...record });
        setSureOrderShow(true);
      },
    },
    {
      btnStr: userInfo.companyInfoVO.companyType !== 0 ? '签署合同' : '',
      status: 300,
      btnClick: (record: procurementOrderListType[0]) => {
        setCurrentOrderItem({ ...record });
        getPurchaseOrderDetail(record.id).then((result: procurementOrderListType[0]) => {
          if (result.contractInfoDTO) {
            contractSign(result.contractInfoDTO?.contractNo);
          }
        });
      },
    },
    {
      btnStr: userInfo.companyInfoVO.companyType === 0 ? '上传付款凭证' : '',
      status: 400,
      btnClick: (record: procurementOrderListType[0]) => {
        setCurrentOrderItem({ ...record });
        setUploadPaymentShow(true);
      },
    },
    {
      btnStr: userInfo.companyInfoVO.companyType !== 0 ? '发货' : '',
      status: 500,
      btnClick: (record: procurementOrderListType[0]) => {
        getPurchaseOrderDetail(record.id).then((result: procurementOrderListType[0]) => {
          if (result) {
            setCurrentOrderItem({ ...result });
            setShipmentsOrderShow(true);
          }
        });
      },
    },
  ];
  // 订单状态
  const [orderStatusList, setOrderStatusList] = useState<{ value: number; label: string }[]>([]);
  // 订单状态搜索列表
  const [tranStatusList, setTranStatusList] = useState<
    { value: number | undefined; label: string }[]
  >([]);
  // 当前选择的是第几个按钮
  const [statusCodeButtonIndex, setStatusCodeButtonIndex] = useState<number>(0);
  // 表格数据
  const [tableData, setTableData] = useState<procurementOrderListType>([]);
  const [currentOrderItem, setCurrentOrderItem] = useState<procurementOrderListType[0]>();
  const [query, setQuery] = useState<procurementOrderParamsType>();
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [loading, setLoading] = useState<boolean>(false);
  const tableColumns: ColumnsType<procurementOrderListType[0]> = [
    {
      title: '商品',
      dataIndex: 'userName',
      width: 280,
      align: 'center',
      fixed: 'left',
      render: (_text, record) => (
        <TableItem
          td={
            <div>
              <span>订单编号：</span>
              <span>{record.uavOrderNo}</span>
            </div>
          }
          tr={record?.skuDTOList?.map((v) => (
            <div key={v.id} className='procurement-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: 'orderAmount',
      align: 'center',
      render: (text, record) => (
        <TableItem
          tr={<div className='goods-text'>￥{text?.toLocaleString()}</div>}
          td={
            <div>
              <span>创建时间:</span>
              <span>{dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
            </div>
          }
        />
      ),
    },
    {
      title: () => (userInfo.companyInfoVO.companyType === 0 ? '供应商信息' : '采购商信息'),
      align: 'center',
      render: (_text: any, record) => (
        <TableItem
          tr={
            <div>
              <div>
                {userInfo.companyInfoVO.companyType === 0
                  ? record.companyName
                  : record.buyCompanyName}
              </div>
              <div>
                {userInfo.companyInfoVO.companyType === 0 ? record.thirdPhoneNum : record.phoneNum}
              </div>
              {getCurrenRemark(record) ? (
                <div>
                  <Tooltip placement='top' title={getCurrenRemark(record)}>
                    <Button icon={<CommentOutlined />}></Button>
                  </Tooltip>
                </div>
              ) : (
                ''
              )}
            </div>
          }
        />
      ),
    },
    {
      title: '订单状态',
      align: 'center',
      dataIndex: 'statusCode',
      render: (text) => (
        <TableItem
          tr={
            <div className='goods-text'>
              {orderStatusList.find((i) => i.value === text)?.label || text}
            </div>
          }
        />
      ),
    },
    {
      title: '备注',
      align: 'center',
      render: (_text: any, record) => (
        <TableItem
          tr={
            <Button type='link' onClick={() => remarkModalShowClick(record)}>
              {userInfo.companyInfoVO.companyType === 0
                ? record.userRemark || '--'
                : record.sellerRemark || '--'}
            </Button>
          }
        />
      ),
    },
    {
      title: '操作',
      onHeaderCell: () => ({
        style: {
          textAlign: 'center',
        },
      }),
      onCell: () => ({
        style: {
          textAlign: 'right',
        },
      }),
      render: (_text: any, record) => (
        <TableItem
          tr={
            <>
              {getCurrentOperateBtn(record.statusCode)?.btnStr ? (
                <Button
                  type={'link'}
                  onClick={() => getCurrentOperateBtn(record.statusCode)?.btnClick(record)}
                >
                  {getCurrentOperateBtn(record.statusCode)?.btnStr}
                </Button>
              ) : (
                ''
              )}
              {isAgainUploadPaymentShow(record) ? (
                <Button type='link' onClick={() => againUploadPayment(record)}>
                  再次上传付款凭证
                </Button>
              ) : (
                ''
              )}

              {isApprovePaymentShow(record) ? (
                <Button type='link' onClick={() => approvePaymentClick(record)}>
                  凭证审批
                </Button>
              ) : (
                ''
              )}
              <Button type='link' onClick={() => toProcurementOrderDetail(record)}>
                详情
              </Button>
            </>
          }
        />
      ),
    },
  ];
  // 订单流程操作
  const [sureOrderShow, setSureOrderShow] = useState<boolean>(false);
  const [iframeModalShow, setIframeModalShow] = useState<boolean>(false);
  const [uploadPaymentShow, setUploadPaymentShow] = useState<boolean>(false);
  const [approvalOrderShow, setApprovalOrderShow] = useState<boolean>(false);
  const [shipmentsOrderShow, setShipmentsOrderShow] = useState<boolean>(false);
  const [remarkModalShow, setRemarkModalShow] = useState<boolean>(false);

  // 合同地址
  const [contractUrl, setContractUrl] = useState<string>('');

  // 获取当前操作按钮
  const getCurrentOperateBtn = (status: number) => {
    return operateBtnList.find((v) => v.status === status);
  };
  // 获取订单状态
  const getOrderStatusList = () => {
    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 getListPurchaseOrder = (query?: procurementOrderParamsType) => {
    setLoading(true);
    OrderManageAPI.getListPurchaseOrder({
      pageSize: pagination.pageSize,
      pageNo: pagination.pageNo,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      pagination.totalCount = result.totalCount;
      setPagination({ ...pagination });
      setTableData(result.list || []);
    });
  };
  // 获取采购订单详情
  const getPurchaseOrderDetail = async (id: number) => {
    const { result } = await OrderManageAPI.getPurchaseOrderDetail({ id });
    return Promise.resolve(result);
  };
  // 分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getListPurchaseOrder(query);
  };
  // 订单状态筛选
  const statusChangeEvent = (i: number) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setStatusCodeButtonIndex(i);
    const req = { ...query, statusCode: tranStatusList[i].value };
    setQuery(req);
    getListPurchaseOrder(req);
  };
  // 筛选
  const searchSuccess = (value: any) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    const reqData = {
      ...filterObjAttr(value, ['rangeTime']),
      statusCode: tranStatusList[statusCodeButtonIndex].value,
    };
    setQuery({ ...reqData });
    getListPurchaseOrder(reqData);
  };
  // 跳转采购订单详情
  const toProcurementOrderDetail = (record: procurementOrderListType[0]) => {
    navigate({
      pathname: '/orderManage/procurementOrder/detail',
      search: qs.stringify({ id: record.id }),
    });
  };

  // 确认订单
  const sureOrderOk = () => {
    getListPurchaseOrder(query);
    setSureOrderShow(false);
  };
  const sureOrderCancel = () => {
    setSureOrderShow(false);
  };
  // 签署合同
  const contractSign = (contractId: string) => {
    FddInterfaceAPI.signContract({ contractId, port: 1 })
      .then(({ result }) => {
        if (result) {
          setContractUrl(decode(result));
          setIframeModalShow(true);
        }
      })
      .catch(({ code }) => {
        if (code === '1006' || code === '1005') {
          navigate('/systemManage/realNameAuth');
        }
      });
  };
  const iframeModalCancel = () => {
    setIframeModalShow(false);
    getListPurchaseOrder(query);
  };
  // 上传付款凭证
  const uploadPaymentCancel = () => {
    setUploadPaymentShow(false);
  };
  const uploadPaymentOk = () => {
    setUploadPaymentShow(false);
    getListPurchaseOrder(query);
  };
  // 再次上传付款凭证
  const againUploadPayment = (record: procurementOrderListType[0]) => {
    setCurrentOrderItem({ ...record });
    setUploadPaymentShow(true);
  };
  const isAgainUploadPaymentShow = (record: procurementOrderListType[0]) => {
    return [500].includes(record.statusCode) && userInfo.companyInfoVO.companyType === 0;
  };

  // 凭证审批
  const approvalOrderOk = () => {
    getListPurchaseOrder(query);
    setApprovalOrderShow(false);
  };
  const approvalOrderCancel = () => {
    setApprovalOrderShow(false);
    getListPurchaseOrder(query);
  };
  const isApprovePaymentShow = (record: procurementOrderListType[0]) => {
    return (
      userInfo.companyInfoVO.companyType !== 0 &&
      ([420].includes(record.statusCode) || record.payDTOS?.some((v) => v.checkStatus === 0))
    );
  };
  const approvePaymentClick = (record: procurementOrderListType[0]) => {
    setCurrentOrderItem({ ...record });
    setApprovalOrderShow(true);
  };

  // 发货
  const shipmentsOrderCancel = () => {
    setShipmentsOrderShow(false);
  };
  const shipmentsOrderOk = () => {
    setShipmentsOrderShow(false);
    getListPurchaseOrder(query);
  };
  // 备注
  const remarkModalShowClick = (record: procurementOrderListType[0]) => {
    setCurrentOrderItem({ ...record });
    setRemarkModalShow(true);
  };
  const remarkModalOk = () => {
    setRemarkModalShow(false);
    getListPurchaseOrder(query);
  };
  const remarkModalCancel = () => {
    setRemarkModalShow(false);
  };
  const getCurrenRemark = (record: procurementOrderListType[0]) => {
    return userInfo.companyInfoVO.companyType === 0 ? record.sellerRemark : record.userRemark;
  };

  useEffect(() => {
    getOrderStatusList();
    getListPurchaseOrder();
  }, []);

  return (
    <div className='procurement-order-list'>
      <SearchBox
        search={[
          {
            label: '订单编号',
            name: 'keyword',
            type: 'input',
            placeholder: '请输入订单编号',
          },
          {
            label: '时间',
            name: 'rangeTime',
            type: 'rangePicker',
            placeholder: '请选择创建时间',
          },
        ]}
        sufFixBtn={
          <>
            {tranStatusList?.map((i, j) => {
              return (
                <Button
                  key={j}
                  type={j === statusCodeButtonIndex ? 'primary' : 'default'}
                  onClick={() => statusChangeEvent(j)}
                  style={{ marginTop: '5px' }}
                >
                  {i.label}
                </Button>
              );
            })}
          </>
        }
        searchData={searchSuccess}
      />
      <Table
        columns={tableColumns}
        dataSource={tableData}
        rowKey='id'
        loading={loading}
        pagination={{
          total: pagination.totalCount,
          pageSize: pagination.pageSize,
          current: pagination.pageNo,
          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={0}
      />
      {/*签署合同*/}
      <IframeModal
        url={contractUrl}
        title='合同签署'
        open={iframeModalShow}
        onCancel={iframeModalCancel}
      />
      {/*上传凭证*/}
      <UploadPayment
        open={uploadPaymentShow}
        onCancel={uploadPaymentCancel}
        onOk={uploadPaymentOk}
        currentOrderItem={currentOrderItem}
      />
      {/*凭证审批*/}
      <ApprovalOrder
        mallOrderItem={currentOrderItem}
        type={0}
        open={approvalOrderShow}
        onCancel={approvalOrderCancel}
        onOk={approvalOrderOk}
      />
      {/*发货*/}
      <ShipmentsOrder
        open={shipmentsOrderShow}
        onCancel={shipmentsOrderCancel}
        onOk={shipmentsOrderOk}
        currentOrderItem={currentOrderItem}
        type={0}
      />
      {/*备注*/}
      <RemarkModal
        open={remarkModalShow}
        onOk={remarkModalOk}
        onCancel={remarkModalCancel}
        currentOrderItem={currentOrderItem}
      />
    </div>
  );
};
export default ProcurementOrderList;
