import { FC, useEffect, useState } from 'react';
import {
  Button,
  Col,
  DatePicker,
  Form,
  Image,
  Input,
  message,
  Modal,
  ModalProps,
  Row,
  Table,
} from 'antd';
import './index.scss';
import { ColumnsType } from 'antd/es/table/InternalTable';
import { UploadOutlined } from '@ant-design/icons';
import { Uploader } from '~/components/uploader';
import { InterDataType, InterListType } from '~/api/interface';
import { mallOrderListType } from '~/api/interface/orderManageType';
import { FddInterfaceAPI, OrderManageAPI } from '~/api';
import IframeModal from '~/components/modal/iframeModal';
import { decode } from 'js-base64';
import { UploadFile } from 'antd/es/upload/interface';
import { uploadContractType } from '~/api/interface/fddInterfaceType';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

// 商城订单对象类型
type mallOrderItemType = InterListType<mallOrderListType>[0];
// 合同返回类型
type contractType = InterDataType<uploadContractType>;

interface selfProps {
  onCancel: () => void;
  onOk: () => void;
  orderItem: any;
  type: number; //0:采购订单，1：商城订单
}

const SureOrder: FC<ModalProps & selfProps> = ({
  open,
  onOk,
  onCancel,
  orderItem,
  type,
  updateContract,
}) => {
  const navigate = useNavigate();
  const [orderInfoForm] = Form.useForm<{
    orderTotalAmount: number;
    deliveryTime: string;
    totalSalary: number;
    cashAmt: number;
  }>();
  // 实付总额
  const [totalAmountPaid, setTotalAmountPaid] = useState<string | number>('');
  const [contractForm] = Form.useForm<{ contractUrl: string; contractTitle: string }>();
  const tableColumns: ColumnsType<mallOrderItemType['skuDTOList'][0]> = [
    {
      title: '商品',
      align: 'center',
      render: (_text: any, record) => (
        <div className='mall-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: '价格',
      align: 'center',
      dataIndex: 'unitPrice',
      render: (text: number) => '￥' + text.toLocaleString(),
    },
    {
      title: '数量',
      align: 'center',
      dataIndex: 'orderNum',
    },
  ];
  // 签署合同地址
  const [contractFileList, setContractFileList] = useState<UploadFile[]>([]);
  const [contractInfo, setContractInfo] = useState<contractType>();
  const [contractUrl, setContractUrl] = useState<string>('');
  const [iframeModalShow, setIframeModalShow] = useState<boolean>(false);

  // 合同上传
  const uploadSuccess = (value: any) => {
    contractForm
      .validateFields(['contractTitle'])
      .then((values) => {
        FddInterfaceAPI.uploadContract({
          docUrl: value[0].url,
          orderNo: orderItem.orderNo,
          port: 1,
          title: values.contractTitle,
        })
          .then(({ result }) => {
            setContractFileList(value);
            contractForm.setFieldValue('contractUrl', value[0].url);
            setContractInfo(result);
          })
          .catch(({ code }) => {
            if (code === '1006' || code === '1005') {
              navigate('/systemManage/realNameAuth');
            }
            setContractFileList([]);
          });
      })
      .catch((error: any) => {
        setContractFileList([]);
        message.warning(error?.errorFields[0]?.errors[0]);
      });
  };
  //签署合同
  const signContractClick = () => {
    contractForm
      .validateFields()
      .then(() => {
        if (contractInfo) {
          signContract(contractInfo.contractNo);
        }
      })
      .catch((error: any) => {
        message.warning(error?.errorFields[0]?.errors[0]);
      });
  };
  // 签署合同
  const signContract = (contractId: string) => {
    FddInterfaceAPI.signContract({ contractId, port: 1 }).then(({ result }) => {
      if (result) {
        setContractUrl(decode(result));
        setIframeModalShow(true);
      }
    });
  };
  const iframeModalCancel = () => {
    setIframeModalShow(false);
  };
  // 用户钱包信息
  const getWalletAmount = () => {
    OrderManageAPI.getWalletAmount({ userAccountId: orderItem?.userAccountId }).then(
      ({ result }) => {
        if (result) {
          orderInfoForm.setFieldsValue({
            cashAmt: result.cashAmt,
          });
          orderTotalAmountInputEvent();
        }
      },
    );
  };
  // 获取实付款总额
  const orderTotalAmountInputEvent = () => {
    const amount =
      orderInfoForm.getFieldValue('orderTotalAmount') >
      (orderInfoForm.getFieldValue('cashAmt') || 0)
        ? (
            orderInfoForm.getFieldValue('orderTotalAmount') - orderInfoForm.getFieldValue('cashAmt')
          ).toLocaleString()
        : 0;
    setTotalAmountPaid('￥' + amount);
  };
  const handleOk = () => {
    if (orderItem) {
      Promise.all([orderInfoForm.validateFields(), contractForm.validateFields()])
        .then((values) => {
          OrderManageAPI[type === 1 ? 'confirmOrder' : 'confirmPOrder']({
            ...values[0],
            id: orderItem.id,
            orderAmount: type === 1 ? undefined : values[0].orderTotalAmount,
            orderTotalAmount: type === 1 ? values[0].orderTotalAmount : undefined,
            deliveryTime: dayjs(values[0].deliveryTime).format('YYYY-MM-DD'),
          }).then(({ code, message: msg }) => {
            if (code === '200') {
              message.success('确认订单成功');
              orderInfoForm.resetFields();
              contractForm.resetFields();
              setContractFileList([]);
              onOk();
            } else {
              message.error(msg);
            }
          });
        })
        .catch((error: any) => {
          message.warning(error?.errorFields[0]?.errors[0]);
        });
    }
  };
  const handleCancel = () => {
    orderInfoForm.resetFields();
    contractForm.resetFields();
    setContractFileList([]);
    onCancel();
  };

  useEffect(() => {
    if (orderItem) {
      if (type === 1) {
        getWalletAmount();
      }
      orderInfoForm.setFieldValue(
        'orderTotalAmount',
        type === 1 ? orderItem.orderTotalAmount : orderItem.orderAmount,
      );
    }
  }, [orderItem, type]);

  return (
    <Modal open={open} title='确认订单' onOk={handleOk} onCancel={handleCancel} width={800}>
      <div className='sure-order'>
        <div className='order-info'>
          <div className='order-info-title'>订单信息：</div>
          <Row>
            <Col span={3}></Col>
            <Col span={16}>
              <div className='order-info-table'>
                <Table
                  bordered
                  columns={tableColumns}
                  dataSource={orderItem?.skuDTOList || []}
                  pagination={false}
                  rowKey='id'
                />
              </div>
              <div className='order-info-form'>
                <Form wrapperCol={{ span: 10 }} labelCol={{ span: 3 }} form={orderInfoForm}>
                  <Form.Item
                    label='订单总额'
                    name='orderTotalAmount'
                    rules={[{ required: true, message: '请输入实付总额' }]}
                  >
                    <Input
                      placeholder='请输入订单总额'
                      suffix='元'
                      maxLength={30}
                      onChange={orderTotalAmountInputEvent}
                    />
                  </Form.Item>
                  {type === 1 ? (
                    <>
                      <Form.Item label='云享金' name='cashAmt'>
                        <Input placeholder='请输入抵扣云享金' suffix='元' disabled />
                      </Form.Item>
                      <Form.Item
                        label='订单交期'
                        name='deliveryTime'
                        rules={[{ required: true, message: '请选择订单交期' }]}
                      >
                        <DatePicker />
                      </Form.Item>
                      <Form.Item label='实付总额'>{totalAmountPaid}</Form.Item>
                    </>
                  ) : (
                    ''
                  )}
                </Form>
              </div>
            </Col>
          </Row>
        </div>
        <div className='contract-info'>
          <div className='contract-info-title'>合同签署：</div>
          <div className='contract-info-form'>
            <Form labelCol={{ span: 5 }} wrapperCol={{ span: 7 }} form={contractForm}>
              <Form.Item
                name='contractTitle'
                label='合同标题'
                rules={[{ required: true, message: '请输入合同标题' }]}
              >
                <Input placeholder='请输入合同标题' maxLength={30} />
              </Form.Item>
              <Form.Item
                label='上传合同'
                name='contractUrl'
                rules={[{ required: true, message: '请上传合同' }]}
              >
                <Uploader
                  fileUpload
                  listType='text'
                  fileLength={1}
                  onChange={uploadSuccess}
                  fileType={['application/pdf']}
                  defaultFileList={contractFileList}
                >
                  <Button icon={<UploadOutlined />} />
                </Uploader>
              </Form.Item>
              <Row>
                <Col span={5}></Col>
                <Col>
                  <div>
                    <Button type='primary' size='small' onClick={signContractClick}>
                      签署合同
                    </Button>
                    <span style={{ color: 'red' }}>（上传合同后需完成签署!）</span>
                  </div>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
      </div>
      <IframeModal
        url={contractUrl}
        title='合同签署'
        open={iframeModalShow}
        onCancel={iframeModalCancel}
      />
    </Modal>
  );
};
export default SureOrder;
