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;
  mallOrderItem: mallOrderItemType | undefined;
}

const SureOrder: FC<ModalProps & selfProps> = ({ open, onOk, onCancel, mallOrderItem }) => {
  const [orderInfoForm] = Form.useForm<{ orderTotalAmount: number; deliveryTime: string }>();
  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 (mallOrderItem) {
      contractForm
        .validateFields()
        .then((values) => {
          FddInterfaceAPI.uploadContract({
            docUrl: values.contractUrl,
            orderNo: mallOrderItem.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 handleOk = () => {
    if (mallOrderItem) {
      Promise.all([orderInfoForm.validateFields(), contractForm.validateFields()])
        .then((values) => {
          OrderManageAPI.confirmOrder({ ...values[0], id: mallOrderItem.id }).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 (mallOrderItem) {
      orderInfoForm.setFieldValue('orderTotalAmount', mallOrderItem.orderTotalAmount);
    }
  }, [mallOrderItem]);
  return (
    <Modal open={open} title='确认订单' onOk={handleOk} onCancel={handleCancel} width={800}>
      <div className='sure-order'>
        {/*<div className='address-info'>*/}
        {/*  <div className='address-info-title'>收货信息：</div>*/}
        {/*  <div className='address-info-form'>*/}
        {/*    <Form labelCol={{ span: 5 }} wrapperCol={{ span: 16 }}>*/}
        {/*      <Form.Item*/}
        {/*        label='收货人'*/}
        {/*        name='takeName'*/}
        {/*        // rules={[{ required: true, validator: validateUserName }]}*/}
        {/*      >*/}
        {/*        <Input placeholder='请输入收货人' style={{ width: '300px' }} />*/}
        {/*      </Form.Item>*/}
        {/*      <Form.Item*/}
        {/*        label='联系方式'*/}
        {/*        name='takePhone'*/}
        {/*        // rules={[{ required: true, validator: validatePhone }]}*/}
        {/*      >*/}
        {/*        <Input placeholder='请输入联系方式' style={{ width: '300px' }} />*/}
        {/*      </Form.Item>*/}
        {/*      <Form.Item*/}
        {/*        label='所属地区'*/}
        {/*        rules={[{ required: true, message: '请输入所属地区' }]}*/}
        {/*        name='takeRegion'*/}
        {/*      >*/}
        {/*        <Cascader*/}
        {/*          // options={location}*/}
        {/*          style={{ width: '300px' }}*/}
        {/*          fieldNames={{*/}
        {/*            label: 'name',*/}
        {/*            value: 'name',*/}
        {/*            children: 'childInfo',*/}
        {/*          }}*/}
        {/*          placeholder='请选择所属地区'*/}
        {/*        />*/}
        {/*      </Form.Item>*/}
        {/*      <Form.Item*/}
        {/*        label='详细地址'*/}
        {/*        name='takeAddress'*/}
        {/*        rules={[{ required: true, message: '请输入详细地址' }]}*/}
        {/*      >*/}
        {/*        <Input.TextArea*/}
        {/*          maxLength={250}*/}
        {/*          placeholder='请输入详细地址'*/}
        {/*          showCount*/}
        {/*          rows={4}*/}
        {/*          style={{ width: '300px' }}*/}
        {/*        />*/}
        {/*      </Form.Item>*/}
        {/*    </Form>*/}
        {/*  </div>*/}
        {/*</div>*/}
        <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={mallOrderItem?.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>
                  <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;
