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 { apiSave, apiAdd } from './services';
import { addrQuery } from '../afterSaleAddress/services';

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?.key || 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 = apiSave;
      }
      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('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
                placeholder={`请选择${area.name}`}
                onChange={val => getAddr(val, area.child)}
                labelInValue
                allowClear
              >
                {area.data.map(item => (
                  <Option value={item.addrId} key={item.addrId}>
                    {item.addrName}
                  </Option>
                ))}
              </Select>,
            )}
          </FormItem>
        ))}
        <FormItem label="详情地址">
          {getFieldDecorator('detail', {
            initialValue: formData.detail,
            rules: [
              {
                required: true,
                message: '请输入详情地址!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="联系人姓名">
          {getFieldDecorator('receiverName', {
            initialValue: formData.receiverName,
            rules: [
              {
                required: true,
                message: '请输入联系人姓名!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="联系人电话">
          {getFieldDecorator('receiverTel', {
            initialValue: formData.receiverTel,
            rules: [
              {
                required: true,
                message: '请输入联系人电话!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="备注">
          {getFieldDecorator('remark', {
            initialValue: formData.remark,
            rules: [
              {
                required: true,
                message: '请输入备注!',
              },
            ],
          })(<Input />)}
        </FormItem>
      </Form>
    </Modal>
  );
};

export default Form.create()(AddressForm);
