import React, { useEffect, useState } from 'react';
import { Button, Form, Input, message, Select } from 'antd';
import ImageUpload from '@/components/XForm/ImageUpload';
import AuthButton from '@/components/AuthButton'
import { fetch, apis } from '@/utils/request';
import ModalForm from '../components/ModalForm';
import InputNumber from '../components/InputNumber';
import { validMinNum } from '../utils';

const Option = Select.Option;
const fullWidth = { width: '100%' };
const saveData = fetch(apis.building.buildingApartmentAdd);
const updateData = fetch(apis.building.buildingApartmentUpdate);

const saleType = [
  {
    id: '1',
    name: '未开盘',
  },
  {
    id: '2',
    name: '售罄',
  },
  {
    id: '3',
    name: '在售',
  },
  // {
  //   id: '4',
  //   name: '在租',
  // },
];

const houseType = [
  {
    id: '1',
    name: '1室',
  },
  {
    id: '2',
    name: '2室',
  },
  {
    id: '3',
    name: '3室',
  },
  {
    id: '4',
    name: '4室',
  },
  {
    id: '5',
    name: '5室及以上',
  },
];

const AMForm = props => {
  const { visible, onCancel, form, formData, onSuccess,buildingId } = props;
  const { getFieldDecorator, setFieldsValue, resetFields, validateFields } = form;

  const [loading, setLoading] = useState(false);

  const handleSubmit = e => {
    e.preventDefault();
    validateFields((err, values) => {
      if (err) {
        console.error(err);
        return;
      }

      const request = formData && formData.apartmentId ? updateData : saveData;

      //  console.log(values)
      // TODO 这里应该是要支持多图，但是封装的控件没有
      // data.img = data.img.map((item, index) => ({ imgType: 'aparment', url: item, orderNo: index }))
      console.log(formData, values, '--------------');
      values.img = [{ imgType: 'aparment', url: values.img, orderNo: 0 }];
      values.buildingId = buildingId;
      values.apartmentType = 'apart';
      // const api = data.apartmentId !== undefined ? apis.building.buildingApartmentUpdate : apis.building.buildingApartmentAdd;

      const data = {
        ...(formData || {}),
        ...values,
      };

      setLoading(true);
      request({ data })
        .then(res => {
          setLoading(false);
          message.success('操作成功');
          onSuccess(res);
        })
        .catch(err => {
          setLoading(false);
          console.error(err);
        });
    });
  };

  useEffect(() => {
    resetFields();
    if (formData?.buildingImgList) {
      formData.img = formData.buildingImgList[0].url;
    }
    setFieldsValue(formData || {});
  }, [formData]);

  return (
    <ModalForm title="户型设置" visible={visible} onCancel={onCancel} onSubmit={handleSubmit}>
      <Form.Item label="户型名称">
        {getFieldDecorator('apartmentName', {
          rules: [
            { required: true, message: '请填写户型名称' },
            { max: 10, message: '户型名称不超过10个字符' },
          ],
        })(<Input placeholder="户型名称不超过10个字符" />)}
      </Form.Item>
      <Form.Item label="销售状态">
        {getFieldDecorator('marketStatus', {
          rules: [{ required: true, message: '请选择销售状态' }],
        })(
          <Select placeholder="销售状态">
            {saleType.map((item, _) => (
              <Option value={item.id} key={item.id}>{item.name}</Option>
            ))}
          </Select>,
        )}
      </Form.Item>
      <Form.Item label="图片" help="建议图片尺寸336px*336px，比例1:1,格式：jpg">
        {getFieldDecorator('img', {
          rules: [{ required: true, message: '请上传户型图片' }],
        })(<ImageUpload />)}
      </Form.Item>
      <Form.Item label="厅室">
        {getFieldDecorator('houseType', {
          rules: [{ required: true, message: '请填写户型厅室' }],
        })(
          <Select placeholder="户型">
            {houseType.map((item, _) => (
              <Option value={item.id} key={item.id}>{item.name}</Option>
            ))}
          </Select>,
        )}
      </Form.Item>
      <Form.Item label="面积">
        {getFieldDecorator('buildingArea', {
          rules: [{ validator: validMinNum }],
        })(<InputNumber precision={2} min={0} step={0.01} addonAfter="㎡" />)}
      </Form.Item>
      {/* <Form.Item label="使用面积">
        {getFieldDecorator('insideArea', {
          rules: [{ validator: validMinNum }],
        })(<InputNumber precision={2} min={0} step={0.01} addonAfter="㎡" />)}
      </Form.Item> */}
      <Form.Item label="权重" help="数值越大越靠前">
        {getFieldDecorator('orderNo', {
          rules: [{ validator: validMinNum }],
        })(<InputNumber min={0} step={1} style={fullWidth} />)}
      </Form.Item>
      <Form.Item label=" " colon={false} style={{ marginTop: '2em' }}>
        <AuthButton name="building.houseType.edit">
          <Button loading={loading} style={{ marginLeft: '4em' }} type="primary" htmlType="submit">
            保存
          </Button>
        </AuthButton>
        <Button style={{ marginLeft: '2em' }} onClick={props.onCancel}>
          取消
        </Button>
      </Form.Item>
    </ModalForm>
  );
};

export default Form.create({})(AMForm);
