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: '同意',
      value: 1,
    },
    {
      label: '不同意',
      value: 2,
      children: [
        {
          label: '商品与出售商品不符',
          value: 1,
        },
        {
          label: '影响二次销售',
          value: 2,
        },
        {
          label: '未提供商品照片,需要上传照片',
          value: 4,
        },
        {
          label: '快递正在配送中',
          value: 5,
        },
        {
          label: '订单已经取消',
          value: 6,
        },
        {
          label: '商品已超过售后期',
          value: 7,
        },
        {
          label: '快递已签收，请申请退货退款，并上传快递面单和商品完好照片',
          value: 8,
        },
        {
          label: '其他',
          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: '审核成功' });
      handleCancel(true);
    }
  };
  const handleOk = () => {
    validateFields((error, fieldsValue) => {
      if (!error) {
        const { auditResult } = fieldsValue;
        // 如果为仅退款 并且 审核同意 弹出二次确认提示
        if (+formData.serviceType === 1 && auditResult?.[0] === 1) {
          confirm({
            title: '温馨提示',
            content: (
              <div>
                当前类型为【<span className={styles.redTipBold}>仅退款</span>
                】，请核查该订单物流状态，如有在途物流，务必自行拦截后点击确认；
              </div>
            ),
            okText: '确认退款',
            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('解析错误 :>> ', 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="售后操作确认"
        visible={visible}
        footer={[
          +formData.serviceType === 2 && (
            <Button type="link" onClick={openLogisticsRecord}>
              查看物流
            </Button>
          ),
          <Button onClick={handleCancel}>取消</Button>,
          <Button type="primary" onClick={handleOk}>
            确定
          </Button>,
        ]}
      >
        {+formData.serviceType === 1 && (
          <div className={styles.redTip}>
            温馨提示：当前售后类型为用户未收到产品，申请
            <span className={styles.redTipBold}>仅退款</span>
            ，请务必检查此单物流状态后审核。<a onClick={openLogisticsRecord}>查看物流</a>
          </div>
        )}

        <Form {...layout} name="formData">
          <FormItem label="审核结果">
            {getFieldDecorator('auditResult', {
              rules: [
                {
                  required: true,
                  message: '请选择审核结果!',
                },
              ],
            })(
              <Cascader
                allowClear
                showSearch
                style={{ width: '315px' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                options={treeData}
                placeholder="请选择"
              />,
            )}
          </FormItem>
          {isAgree() && +formData.serviceType === 2 && (
            <div>
              <FormItem label="售后地址">
                <div className={styles.saleAddr}>
                  <Select options={addrList} onChange={onAddrChange} />
                  <Button type="link" onClick={toSetAddr}>
                    新建
                  </Button>
                </div>
              </FormItem>
              <FormItem label="退货地址">
                {getFieldDecorator('receiveAddress', {
                  initialValue: formData.address,
                  rules: [
                    {
                      required: true,
                      message: '请填写退货地址!',
                    },
                    {
                      message: '格式有误，请填写正确的退货地址!',
                      pattern: /[a-zA-Z0-9_\u4e00-\u9fa5]/g,
                    },
                  ],
                })(
                  <TextArea
                    placeholder="最多输入50个字符"
                    maxLength="50"
                    allowClear
                    autoSize={{ minRows: 3, maxRows: 6 }}
                  />,
                )}
              </FormItem>
              <FormItem label="收件人">
                {getFieldDecorator('receiverName', {
                  initialValue: formData.name,
                  rules: [
                    {
                      required: true,
                      message: '请填写收件人!',
                    },
                    {
                      message: '格式有误，请输入中英文、数字!',
                      pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/,
                    },
                  ],
                })(<Input placeholder="最多输入25个字符" maxLength="25" allowClear />)}
              </FormItem>
              <FormItem label="手机号码">
                {getFieldDecorator('receiverPhone', {
                  initialValue: formData.phone,
                  rules: [
                    // {
                    //   pattern: new RegExp(/^1[3456789]\d{9}$/, 'g'),
                    //   message: '手机号码格式不正确!',
                    // },
                    {
                      pattern: new RegExp(/^[0-9]*$/),
                      message: '手机号码格式不正确!',
                    },
                    {
                      required: true,
                      message: '请填写手机号码!',
                    },
                  ],
                })(<Input placeholder="请填写手机号码" maxLength="11" allowClear />)}
              </FormItem>
            </div>
          )}
          {isRefuse() && auditResult[1] === 3 && (
            <FormItem label="拒绝原因">
              {getFieldDecorator('refuseDesc', {
                initialValue: formData.refuseDesc,
                rules: [
                  {
                    required: true,
                    message: '请填写拒绝原因!',
                  },
                ],
              })(
                <TextArea
                  placeholder="请填写拒绝原因"
                  allowClear
                  autoSize={{ minRows: 3, maxRows: 6 }}
                />,
              )}
            </FormItem>
          )}
          {isRefuse() && auditResult[1] !== 3 && (
            <FormItem label="补充说明">
              {getFieldDecorator('refuseDesc', {
                initialValue: formData.refuseDesc,
                rules: [
                  {
                    message: '请填写补充说明!',
                  },
                ],
              })(
                <TextArea
                  placeholder="请填写补充说明"
                  allowClear
                  autoSize={{ minRows: 3, maxRows: 6 }}
                  maxLength={120}
                  showCount
                />,
              )}
            </FormItem>
          )}
        </Form>
      </Modal>
      <LogisticsRecordModal ref={logisticsRecordModalRef} />
    </>
  );
};

export default Form.create()(AuditModal);
