import React, { useState, useEffect } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Select, Input, notification } from 'antd';
import _ from 'lodash';
import { addrQuery, apiEdit, apiAdd } from './services';

const { TextArea } = Input;
const FormItem = Form.Item;
const { Option } = Select;
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const AddressForm = props => {
  const { visible, supplierList } = props;
  const [formData, setFormData] = useState(() => _.cloneDeep(props.value));
  const [provinceList, setProvinceList] = useState([]);
  const [cityList, setCityList] = useState([]);
  const [countyList, setCountyList] = useState([]);
  const [townList, setTownList] = useState([]);
  const { getFieldDecorator } = props.form;
  const areaData = [
    {
      name: '省',
      key: 'province',
      child: 'city',
      data: provinceList,
      required: true,
    },
    {
      name: '市',
      key: 'city',
      child: 'county',
      data: cityList,
      required: true,
    },
    {
      name: '县',
      key: 'county',
      child: 'town',
      data: countyList,
    },
    {
      name: '镇',
      key: 'town',
      child: '',
      data: townList,
    },
  ];
  const resetForm = () => {
    props.form.resetFields();
    setFormData({});
  };

  const onCancel = () => {
    props.onClose();
    resetForm();
  };
  const getAddr = async (val, type, edit) => {
    const data = await addrQuery({ parentId: val?.value || val });
    switch (type) {
      case 'city':
        setCityList(data);
        if (!edit) {
          setCountyList([]);
          setTownList([]);
          props.form.setFieldsValue({
            city: { key: '', label: '' },
            county: { key: '', label: '' },
            town: { key: '', label: '' },
          });
        }
        break;
      case 'county':
        setCountyList(data);
        if (!edit) {
          setTownList([]);
          props.form.setFieldsValue({
            county: { key: '', label: '' },
            town: { key: '', label: '' },
          });
        }
        break;
      case 'town':
        setTownList(data);
        if (!edit) {
          props.form.setFieldsValue({ town: { key: '', label: '' } });
        }
        break;
      default:
        break;
    }
  };

  const getFormData = () => {
    const data = _.cloneDeep(props.value);
    if (data.id) {
      getAddr(data.provinceId, 'city', 'edit');
      getAddr(data.cityId, 'county', 'edit');
      getAddr(data.countyId, 'town', 'edit');
      return {
        ...data,
        province: {
          key: data.provinceId ?? null,
          label: data.provinceName ?? null,
        },
        city: {
          key: data.cityId ?? null,
          label: data.cityName ?? null,
        },
        county: {
          key: data.countyId ?? null,
          lable: data.countyName ?? null,
        },
        town: {
          key: data.townId ?? null,
          label: data.townName ?? null,
        },
      };
    }
    return data;
  };

  useEffect(() => {
    async function getProvince() {
      const data = await addrQuery();
      setProvinceList(data);
    }
    getProvince();
    setFormData(() => _.cloneDeep(getFormData()));
  }, [props.value]);

  const handleSubmit = () => {
    props.form.validateFields(async (err, fieldsValue) => {
      if (err) return;
      const { province = {}, city = {}, county = {}, town = {} } = fieldsValue;
      const params = {
        ...fieldsValue,
        provinceId: province.key,
        provinceName: province.label,
        cityId: city.key,
        cityName: city.label,
        countyId: county.key,
        countyName: county.label,
        townId: town.key,
        townName: town.label,
      };
      delete params.province;
      delete params.city;
      delete params.county;
      delete params.town;
      let api = apiAdd;
      if (formData.id) {
        params.id = formData.id;
        api = apiEdit;
      }

      const businessCode = await api(params);
      if (businessCode === '0000') {
        notification.success({ message: '操作成功' });
        resetForm();
        props.onClose('success');
      }
    });
  };

  return (
    <Modal
      title={`${formData.id ? '修改' : '增加'}售后地址`}
      visible={visible}
      onCancel={() => onCancel()}
      onOk={handleSubmit}
    >
      <Form {...layout} name="formData">
        <FormItem label="售后地址名称">
          {getFieldDecorator('addressName', {
            initialValue: formData.addressName,
            rules: [
              {
                required: true,
                message: '请输入售后地址名称!',
              },
            ],
          })(<Input placeholder="请输入售后地址名称" maxLength={20} />)}
        </FormItem>
        <FormItem label="供应商名称">
          {getFieldDecorator('shopId', {
            initialValue: formData.shopId,
            rules: [
              {
                required: true,
                message: '请选择供应商名称!',
              },
            ],
          })(
            <Select showSearch placeholder="请选择供应商名称" allowClear>
              {supplierList.map(item => (
                <Option value={item.id} key={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>,
          )}
        </FormItem>
        {areaData.map(area => (
          <FormItem label={area.name} name={area.key} key={area.key}>
            {getFieldDecorator(area.key, {
              initialValue: formData[area.key],
              rules: [
                {
                  required: area.required,
                  message: `请选择${area.name}!`,
                },
              ],
            })(
              <Select
                showSearch
                optionFilterProp="label"
                placeholder={`请选择${area.name}`}
                onChange={val => getAddr(val, area.child)}
                labelInValue
                allowClear
              >
                {area.data.map(item => (
                  <Option label={item.addrName} value={item.addrId} key={item.addrName}>
                    {item.addrName}
                  </Option>
                ))}
              </Select>,
            )}
          </FormItem>
        ))}
        <FormItem label="详情地址">
          {getFieldDecorator('detail', {
            initialValue: formData.detail,
            rules: [
              {
                required: true,
                message: '请输入详情地址!',
              },
            ],
          })(<Input placeholder="请输入详情地址" />)}
        </FormItem>
        <FormItem label="联系人姓名">
          {getFieldDecorator('receiverName', {
            initialValue: formData.receiverName,
            rules: [
              {
                required: true,
                message: '请输入联系人姓名!',
              },
            ],
          })(<Input placeholder="请输入联系人姓名" />)}
        </FormItem>
        <FormItem label="联系人电话">
          {getFieldDecorator('receiverTel', {
            initialValue: formData.receiverTel,
            rules: [
              {
                required: true,
                message: '请输入联系人电话!',
              },
            ],
          })(<Input placeholder="请输入联系人电话" />)}
        </FormItem>
        <FormItem label="备注">
          {getFieldDecorator('remark', {
            initialValue: formData.remark,
          })(<TextArea placeholder="请输入备注,仅限120字以内。" maxLength={120} />)}
        </FormItem>
      </Form>
    </Modal>
  );
};

export default Form.create()(AddressForm);
