import {
  Form,
  Input,
  Modal,
  ModalProps,
  Radio,
  RadioChangeEvent,
  Button,
  message,
  InputNumber,
} from 'antd';
import React, { FC, useState } from 'react';
import { InterDataType } from '~/api/interface';
import { rentOrderDetailType } from '~/api/interface/orderManageType';
import LogisticsStepModal from '~/components/order/productOrder/logisticsStepModal';
import { OrderManageAPI } from '~/api';
import { UploadOutlined } from '@ant-design/icons';
import { UploadFile } from 'antd/es/upload/interface';
import { Uploader } from '~/components/uploader';
import { isEmptyBol } from '~/utils/validateUtils';

// 租赁订单详情返回类型
type detailType = InterDataType<rentOrderDetailType>;

interface selfProps {
  onOk: () => void;
  onCancel: () => void;
  currentOrderItem: detailType | undefined;
  modalTitle: string;
}

const ConfirmReturn: FC<ModalProps & selfProps> = ({
  open,
  onOk,
  onCancel,
  currentOrderItem,
  modalTitle,
}) => {
  const [form] = Form.useForm<{ damage: number; reason: string }>();
  const [isDilapidation, setIsDilapidation] = useState<boolean>(false);
  const [logisticsStepModalShow, setLogisticsStepModalShow] = useState<boolean>(false);
  const [dilapidationImgList, setDilapidationImgList] = useState<UploadFile[]>([]);

  const radioChangeEvent = (e: RadioChangeEvent) => {
    setIsDilapidation(!!e.target.value);
  };
  // 物流弹窗
  const logisticsStepModalShowClick = () => {
    setLogisticsStepModalShow(true);
  };
  const logisticsStepModalCancel = () => {
    setLogisticsStepModalShow(false);
  };

  const handleOk = () => {
    form.validateFields().then((values) => {
      OrderManageAPI.rentPfConfirmOrderWare({
        ...values,
        orderId: currentOrderItem?.id,
      }).then(({ code }) => {
        if (code === '200') {
          message.success('确认归还成功');
          form.resetFields();
          setDilapidationImgList([]);
          setIsDilapidation(false);
          onOk();
        }
      });
    });
  };
  const handleCancel = () => {
    onCancel();
    form.resetFields();
    setDilapidationImgList([]);
    setIsDilapidation(false);
  };
  // 破损图片上传
  const uploadDilapidationImg = (value: any) => {
    setDilapidationImgList(value);
    form.setFieldValue('file', JSON.stringify(value.map((v: any) => v.url)));
  };

  // 破损金额限制
  const priceValidator = (_rule: any, value: any, callback: any) => {
    if (isEmptyBol(value)) {
      return callback(new Error('金额不能为空'));
    }
    if (value < 0) {
      return callback(new Error('金额不能小于0'));
    }
    if (value > (currentOrderItem?.deposit || 0) * (currentOrderItem?.wareNum || 0)) {
      return callback(
        new Error(
          `金额不能大于${(currentOrderItem?.deposit || 0) * (currentOrderItem?.wareNum || 0)}`,
        ),
      );
    }
    callback();
  };

  return (
    <Modal open={open} onOk={handleOk} onCancel={handleCancel} title={modalTitle}>
      <Form initialValues={{ damage: 0 }} form={form}>
        <Form.Item label='判定' name='damage'>
          <Radio.Group onChange={radioChangeEvent}>
            <Radio value={0}>未破损</Radio>
            <Radio value={1}>破损</Radio>
          </Radio.Group>
        </Form.Item>
        {isDilapidation ? (
          <>
            <Form.Item
              label='扣除金额'
              name='deductionAmount'
              rules={[{ required: true, validator: priceValidator }]}
            >
              <InputNumber placeholder='请输入抵扣金额' style={{ width: '200px' }} />
            </Form.Item>
            <Form.Item
              label='破损图片'
              name='file'
              rules={[{ required: true, message: '请上传破损图片' }]}
            >
              <Uploader
                listType='picture-card'
                fileUpload
                onChange={uploadDilapidationImg}
                defaultFileList={dilapidationImgList}
              >
                <UploadOutlined />
              </Uploader>
            </Form.Item>
            <Form.Item
              label='破损描述'
              name='reason'
              rules={[{ required: true, message: '请输入破损描述' }]}
            >
              <Input.TextArea placeholder='请输入破损描述' maxLength={70} showCount rows={3} />
            </Form.Item>
          </>
        ) : (
          ''
        )}
        <Form.Item label='物流信息'>
          <div>
            <Button type='link' onClick={logisticsStepModalShowClick}>
              查看详情
            </Button>
          </div>
        </Form.Item>
        <LogisticsStepModal
          open={logisticsStepModalShow}
          onCancel={logisticsStepModalCancel}
          logisticsStep={currentOrderItem?.returnKdnExpDTO}
        />
      </Form>
    </Modal>
  );
};

export default ConfirmReturn;
