import React, { useRef, useState, useEffect } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Input, Cascader, notification, Select, Button } from 'antd';
import { history } from 'umi';
import { shopAudit, afterSalesAddrsPage } from '../services';
import styles from '../index.less';

import LogisticsRecordModal from './LogisticsRecordModal';

const FormItem = Form.Item;
const { TextArea } = Input;
const { confirm } = Modal;
const AuditModal = props => {
  const {
    visible,
    onCancel,
    form: { getFieldDecorator, getFieldValue, validateFields, resetFields, setFieldsValue },
    formData = {},
  } = props;
  const [addrList, setAddrList] = useState([]);

  console.log('formData :>> ', formData);
  const logisticsRecordModalRef = useRef();
  const handleCancel = isSuccess => {
    resetFields();
    onCancel(isSuccess);
  };
  const treeData = [
    {
      label: $t('agree'),
      value: 1,
    },
    {
      label: $t('disagree'),
      value: 2,
      children: [
        {
          label: $t('product.mismatch'),
          value: 1,
        },
        {
          label: $t('affects.resale'),
          value: 2,
        },
        {
          label: $t('upload.product.photos'),
          value: 4,
        },
        {
          label: $t('parcel.in.transit'),
          value: 5,
        },
        {
          label: $t('order.canceled'),
          value: 6,
        },
        {
          label: $t('product.beyond.aftersale.period'),
          value: 7,
        },
        {
          label: $t('parcel.received.apply.refund.with.receipt.photo'),
          value: 8,
        },
        {
          label: $t('other'),
          value: 3,
        },
      ],
    },
  ];
  const submitCheckResult = async fieldsValue => {
    const { auditResult } = fieldsValue;
    const data = await shopAudit({
      ...fieldsValue,
      refuseCode: auditResult?.[1],
      auditResult: auditResult?.[0],
      serviceNo: formData?.serviceNo,
    });
    if (data.businessCode === '0000') {
      notification.success({ message: $t('review.success') });
      handleCancel(true);
    }
  };
  const handleOk = () => {
    validateFields((error, fieldsValue) => {
      if (!error) {
        const { auditResult } = fieldsValue;
        // 如果为仅退款 并且 审核同意 弹出二次确认提示
        if (+formData.serviceType === 1 && auditResult?.[0] === 1) {
          confirm({
            title: $t('reminder'),
            content: (
              <div>{$t('current.type')}<span className={styles.redTipBold}>{$t('refund.only')}</span>{$t('check.order.logistics.status.first.to.intercept.any.intransit.shipments.before.confirming')}</div>
            ),
            okText: $t('confirm.refund'),
            onOk() {
              submitCheckResult(fieldsValue);
            },
            onCancel() {
              handleCancel(true);
            },
          });
        } else {
          submitCheckResult(fieldsValue);
        }
      }
    });
  };

  const toSetAddr = () => {
    history.push('/afterSaleAddress');
  };

  const onAddrChange = e => {
    try {
      const obj = JSON.parse(e);
      setFieldsValue({
        receiveAddress:
          obj.provinceName + obj.cityName + obj.countyName + (obj.townName || '') + obj.detail,
        receiverName: obj.receiverName,
        receiverPhone: obj.receiverTel,
      });
    } catch {
      console.log($t('parse.error'), 111);
    }
  };

  const getAddrList = async () => {
    const res = await afterSalesAddrsPage();
    if (res && res.data && res.data.records && res.data.records.length) {
      setAddrList(
        res.data.records.map(item => ({
          label: item.addressName,
          value: JSON.stringify(item),
        })),
      );
    }
  };
  useEffect(() => {
    if (props.visible && addrList.length === 0) {
      getAddrList();
    }
  }, [props.visible]);

  const openLogisticsRecord = () => {
    const { orderNo, skuNo } = formData;
    logisticsRecordModalRef.current.open({ orderNo, skuNo });
  };

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };
  const auditResult = getFieldValue('auditResult');
  const isAgree = () => auditResult?.[0] === 1;
  const isRefuse = () => auditResult && auditResult[0] !== 1;
  return (
    <>
      <Modal
        title={$t('aftersales.confirmation')}
        visible={visible}
        footer={[
          +formData.serviceType === 2 && (
            <Button type="link" onClick={openLogisticsRecord}>{$t('view.logistics')}</Button>
          ),
          <Button onClick={handleCancel}>{$t('cancel')}</Button>,
          <Button type="primary" onClick={handleOk}>{$t('confirm')}</Button>,
        ]}
      >
        {+formData.serviceType === 1 && (
          <div className={styles.redTip}>{$t('reminder.current.aftersales.type.is.product.not.received')}<span className={styles.redTipBold}>{$t('refund.only')}</span>{$t('verify.logistics.status.before.approval')}<a onClick={openLogisticsRecord}>{$t('view.logistics')}</a>
          </div>
        )}

        <Form {...layout} name="formData">
          <FormItem label={$t('review.result')}>
            {getFieldDecorator('auditResult', {
              rules: [
                {
                  required: true,
                  message: $t('select.audit.result'),
                },
              ],
            })(
              <Cascader
                allowClear
                showSearch
                style={{ width: '315px' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                options={treeData}
                placeholder={$t('select')}
              />,
            )}
          </FormItem>
          {isAgree() && +formData.serviceType === 2 && (
            <div>
              <FormItem label={$t('aftersales.address')}>
                <div className={styles.saleAddr}>
                  <Select options={addrList} onChange={onAddrChange} />
                  <Button type="link" onClick={toSetAddr}>{$t('new')}</Button>
                </div>
              </FormItem>
              <FormItem label={$t('return.address')}>
                {getFieldDecorator('receiveAddress', {
                  initialValue: formData.address,
                  rules: [
                    {
                      required: true,
                      message: $t('enter.return.address'),
                    },
                    {
                      message: $t('invalid.format.enter.correct.return.address'),
                      pattern: /[a-zA-Z0-9_\u4e00-\u9fa5]/g,
                    },
                  ],
                })(
                  <TextArea
                    placeholder={$t('max.50.characters')}
                    maxLength="50"
                    allowClear
                    autoSize={{ minRows: 3, maxRows: 6 }}
                  />,
                )}
              </FormItem>
              <FormItem label={$t('recipient')}>
                {getFieldDecorator('receiverName', {
                  initialValue: formData.name,
                  rules: [
                    {
                      required: true,
                      message: $t('enter.recipient'),
                    },
                    {
                      message: $t('invalid.format.enter.chineseenglishdigits'),
                      pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/,
                    },
                  ],
                })(<Input placeholder={$t('max.25.characters')} maxLength="25" allowClear />)}
              </FormItem>
              <FormItem label={$t('mobile.number')}>
                {getFieldDecorator('receiverPhone', {
                  initialValue: formData.phone,
                  rules: [
                    // {
                    //   pattern: new RegExp(/^1[3456789]\d{9}$/, 'g'),
                    //   message: '手机号码格式不正确!',
                    // },
                    {
                      pattern: new RegExp(/^[0-9]*$/),
                      message: $t('invalid.phone.format'),
                    },
                    {
                      required: true,
                      message: $t('enter.phone.number'),
                    },
                  ],
                })(<Input placeholder={$t('enter.phone.number')} maxLength="11" allowClear />)}
              </FormItem>
            </div>
          )}
          {isRefuse() && auditResult[1] === 3 && (
            <FormItem label={$t('rejection.reason')}>
              {getFieldDecorator('refuseDesc', {
                initialValue: formData.refuseDesc,
                rules: [
                  {
                    required: true,
                    message: $t('enter.rejection.reason'),
                  },
                ],
              })(
                <TextArea
                  placeholder={$t('enter.rejection.reason')}
                  allowClear
                  autoSize={{ minRows: 3, maxRows: 6 }}
                />,
              )}
            </FormItem>
          )}
          {isRefuse() && auditResult[1] !== 3 && (
            <FormItem label={$t('additional.notes')}>
              {getFieldDecorator('refuseDesc', {
                initialValue: formData.refuseDesc,
                rules: [
                  {
                    message: $t('enter.additional.notes'),
                  },
                ],
              })(
                <TextArea
                  placeholder={$t('enter.additional.notes')}
                  allowClear
                  autoSize={{ minRows: 3, maxRows: 6 }}
                  maxLength={120}
                  showCount
                />,
              )}
            </FormItem>
          )}
        </Form>
      </Modal>
      <LogisticsRecordModal ref={logisticsRecordModalRef} />
    </>
  );
};

export default Form.create()(AuditModal);
