import { Button, Descriptions, Image, Steps, Table } from 'antd';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { FddInterfaceAPI, OrderManageAPI } from '~/api';
import React, { useEffect, useState } from 'react';
import { purchaseOrderDetailType } from '~/api/interface/orderManageType';
import { InterDataType } from '~/api/interface';
import dayjs from 'dayjs';
import { ColumnsType } from 'antd/es/table';
import './index.scss';
import { decode } from 'js-base64';
import FileSaver from 'file-saver';
import LogisticsStepModal from '~/components/order/productOrder/logisticsStepModal';

// 采购订单详情返回类型
type detailType = InterDataType<purchaseOrderDetailType>;

const ProcurementOrderDetail = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [purchaseOrderDetail, setPurchaseOrderDetail] = useState<detailType>();
  // 订单状态
  const [orderStatusList, setOrderStatusList] = useState<{ value: number; label: string }[]>([]);
  const columns: ColumnsType<detailType['skuDTOList'][0]> = [
    {
      title: '商品',
      align: 'center',
      width: '20%',
      render: (_text, record) => (
        <div className='procurement-sku-item'>
          <Image src={record.skuImage} className='sku-img' />
          <div className='sku-info'>
            <div className='info-name'>{record.tradeName}</div>
            <div className='info-spec'>
              {Object.entries(JSON.parse(record.productSpec)).map((v, index) => (
                <span key={index}>{v.join('：')}</span>
              ))}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '单价（元）',
      dataIndex: 'unitPrice',
      align: 'center',
      render: (text) => `￥${text?.toLocaleString()}`,
    },
    {
      title: '数量',
      dataIndex: 'orderNum',
      align: 'center',
    },
    {
      title: '订单状态',
      align: 'center',
      render: () => orderStatusList.find((v) => v.value === purchaseOrderDetail?.statusCode)?.label,
    },
    {
      title: '订单金额（元）',
      align: 'center',
      render: () => `￥${purchaseOrderDetail?.orderAmount}`,
    },
  ];
  const [logisticsStepModalShow, setLogisticsStepModalShow] = useState<boolean>(false);

  // 获取采购订单详情
  const getPurchaseOrderDetail = (id: number) => {
    OrderManageAPI.getPurchaseOrderDetail({ id }).then(({ result }) => {
      if (result) {
        setPurchaseOrderDetail(result);
      }
    });
  };
  // 获取订单状态
  const getOrderStatusList = () => {
    OrderManageAPI.getMallOrderStatusList().then(({ result }) => {
      if (result) {
        const list = result.map((item) => ({ value: item.code, label: item.status }));
        setOrderStatusList(list);
      }
    });
  };

  const backRoute = () => {
    navigate(-1);
  };

  //   合同预览
  const contractPreview = () => {
    if (purchaseOrderDetail?.contractInfoDTO?.contractNo) {
      FddInterfaceAPI.viewContract({
        contractId: purchaseOrderDetail?.contractInfoDTO?.contractNo,
      }).then(({ result }) => {
        window.open(decode(result), '_blank');
      });
    }
  };
  // 合同下载
  const downloadContract = () => {
    if (purchaseOrderDetail?.contractInfoDTO?.contractNo) {
      FddInterfaceAPI.downloadContract({
        contractId: purchaseOrderDetail?.contractInfoDTO?.contractNo,
      }).then(({ result }) => {
        FileSaver.saveAs(decode(result), `${purchaseOrderDetail?.contractInfoDTO?.contractNo}.pdf`);
      });
    }
  };
  const showStepModal = () => {
    setLogisticsStepModalShow(true);
  };
  const logisticsStepModalCancel = () => {
    setLogisticsStepModalShow(false);
  };

  useEffect(() => {
    getPurchaseOrderDetail(Number(searchParams.get('id')));
    getOrderStatusList();
  }, []);

  return (
    <div className='procurement-order-detail'>
      <Descriptions
        title='供应商'
        bordered
        extra={
          <Button type='primary' onClick={backRoute}>
            返回
          </Button>
        }
      >
        <Descriptions.Item label='供应商名称：'>
          {purchaseOrderDetail?.companyName}
        </Descriptions.Item>
        <Descriptions.Item label='供应商电话：'>
          {purchaseOrderDetail?.thirdPhoneNum}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='订单' style={{ marginTop: '10px' }} column={3}>
        <Descriptions.Item label='订单编号：' labelStyle={{ color: '#000' }}>
          {purchaseOrderDetail?.orderNo}
        </Descriptions.Item>
        <Descriptions.Item label='创建时间：' labelStyle={{ color: '#000' }}>
          {dayjs(purchaseOrderDetail?.createTime).format('YYYY-MM-DD HH:mm:ss')}
        </Descriptions.Item>
        <Descriptions.Item label='合同编号：' labelStyle={{ color: '#000' }}>
          {purchaseOrderDetail?.contractInfoDTO?.contractNo || '--'}
        </Descriptions.Item>
        <Descriptions.Item span={3}>
          <Table
            size='small'
            dataSource={purchaseOrderDetail?.skuDTOList || []}
            columns={columns}
            rowKey='id'
            bordered
            pagination={false}
            style={{ width: '100%' }}
            // rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
          />
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='物流' bordered style={{ marginTop: '10px' }}>
        <Descriptions.Item label='收货人：'>
          {purchaseOrderDetail?.uavOrderExpressDTO.takeName}
        </Descriptions.Item>
        <Descriptions.Item label='手机号：'>
          {purchaseOrderDetail?.uavOrderExpressDTO.takePhone}
        </Descriptions.Item>
        <Descriptions.Item label='收货地址：'>
          {purchaseOrderDetail?.uavOrderExpressDTO.takeRegion.split('/').join('') ||
            '' + purchaseOrderDetail?.uavOrderExpressDTO.takeAddress}
        </Descriptions.Item>
        <Descriptions.Item label='物流单号：'>
          {purchaseOrderDetail?.uavOrderExpressDTO.sendExpNo || '--'}
        </Descriptions.Item>
        <Descriptions.Item label='物流进度：'>
          {purchaseOrderDetail?.kdnExpDTO?.traces?.length ? (
            <>
              <div>
                <Steps
                  direction='vertical'
                  current={0}
                  progressDot
                  items={[
                    {
                      title: purchaseOrderDetail?.kdnExpDTO?.traces?.[0]?.acceptStation,
                      description: purchaseOrderDetail?.kdnExpDTO?.traces?.[0]?.acceptTime,
                    },
                    {
                      title: `送至${
                        purchaseOrderDetail?.uavOrderExpressDTO?.takeRegion.split('/').join('') ||
                        '' + purchaseOrderDetail?.uavOrderExpressDTO?.takeAddress
                      }`,
                    },
                  ]}
                />
              </div>
              <div>
                <Button type='link' onClick={showStepModal}>
                  查看详情
                </Button>
              </div>
            </>
          ) : (
            '--'
          )}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='凭证及合同' bordered style={{ marginTop: '10px' }}>
        <Descriptions.Item label='付款凭证：'>
          {purchaseOrderDetail?.payDTOS.map((v, index) => (
            <div className='pay-wrap' key={index}>
              <div className='pay-item'>
                <div className='pay-item-laebl'>
                  第{index + 1}次上传{' '}
                  <span style={{ color: 'red' }}>
                    ({v.checkStatus === 0 ? '待审批' : v.checkStatus === 1 ? '已通过' : '未通过'})
                  </span>
                  ：
                </div>
                <div className='pay-item-content'>
                  {JSON.parse(v.payImgList).map((i: any, j: number) => (
                    <Image key={j} src={i.filePath} width={100} height={100} />
                  ))}
                </div>
              </div>
              <div className='pay-remark'>
                <div className='label'> 第{index + 1}次上传凭证说明：</div>
                <div className='value'>{v.payRemark}</div>
              </div>
            </div>
          ))}
        </Descriptions.Item>
        <Descriptions.Item label='合同信息：'>
          {purchaseOrderDetail?.contractInfoDTO ? (
            <>
              <Button type='link' onClick={contractPreview}>
                查看
              </Button>
              <Button type='link' onClick={downloadContract}>
                下载
              </Button>
            </>
          ) : (
            '--'
          )}
        </Descriptions.Item>
      </Descriptions>
      <LogisticsStepModal
        open={logisticsStepModalShow}
        logisticsStep={purchaseOrderDetail?.kdnExpDTO}
        onCancel={logisticsStepModalCancel}
      />
    </div>
  );
};
export default ProcurementOrderDetail;
