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 { 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';

// 商城订单对象类型
type mallOrderItemType = InterListType<mallOrderListType>[0];
interface selfProps {
  onCancel: () => void;
  onOk: () => void;
  orderItem: any;
  type: number; //0:采购订单，1：商城订单
}

const SureOrder: FC<ModalProps & selfProps> = ({ open, onOk, onCancel, orderItem, type }) => {
  const [orderInfoForm] = Form.useForm<{
    orderTotalAmount: number;
    deliveryTime: string;
    totalSalary: number;
    cashAmt: 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 [contractUrl, setContractUrl] = useState<string>('');
  const [iframeModalShow, setIframeModalShow] = useState<boolean>(false);

  // 合同文件上传成功回调
  const uploadSuccess = (value: any) => {
    setContractFileList(value);
    contractForm.setFieldValue('contractUrl', value[0].url);
  };
  // 合同上传fdd
  const uploadContract = () => {
    if (orderItem) {
      contractForm
        .validateFields()
        .then((values) => {
          FddInterfaceAPI.uploadContract({
            docUrl: values.contractUrl,
            orderNo: orderItem.orderNo,
            port: 1,
            title: values.contractTitle,
          }).then(({ result }) => {
            signContract(result.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,
            totalSalary: result.totalSalary,
          });
        }
      },
    );
  };
  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,
          }).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} />
                  </Form.Item>
                  {type === 1 ? (
                    <>
                      <Form.Item label='云享金' name='cashAmt'>
                        <Input placeholder='请输入抵扣云享金' suffix='元' disabled />
                      </Form.Item>
                      <Form.Item label='佣金' name='totalSalary'>
                        <Input placeholder='请输入抵扣佣金' suffix='元' disabled />
                      </Form.Item>
                      <Form.Item
                        label='订单交期'
                        name='deliveryTime'
                        rules={[{ required: true, message: '请选择订单交期' }]}
                      >
                        <DatePicker />
                      </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',
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                  ]}
                  defaultFileList={contractFileList}
                >
                  <Button icon={<UploadOutlined />} />
                </Uploader>
              </Form.Item>
              <Row>
                <Col span={5}></Col>
                <Col>
                  <div>
                    <Button type='primary' size='small' onClick={uploadContract}>
                      签署合同
                    </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;
