import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, Table, Avatar, Radio, Modal, Descriptions, notification } from 'antd';
import moment from 'moment';
import request from '../../../../../utils/request';
import apis from '../../../../../services/apis';
import Styles from '../style.less';
import ImageUpload from '../../../../../components/XForm/ImageUpload'
import ImageListUpload from '../../../../../components/XForm/ImageListUpload'
import Wangedit from '../../../../../components/Wangedit/Wangedit'


const { Option } = Select;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { Meta } = Card;

const { TextArea } = Input;


const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 2 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

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室及以上',
  },
]

/**
 * 图片信息
 *
 * @param {*} props
 * @returns
 */
class ModalImage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
       visibleData: { visible: false, apartmentId: '', buildingId: '' },
    }
  }

  // 挂载之后
  // componentDidMount() {
  //
  // }

  componentDidUpdate(preProps, preState) {
    if (this.props.visibleData.visible !== preState.visibleData.visible) {
      console.log(this.props.visibleData)
      this.getById()
      this.setState({ visibleData: this.props.visibleData });
    }
  }

  // 弹框确定按钮
  // eslint-disable-next-line react/sort-comp
  handleOk() {
    this.setState({ visibleData: { visible: false, apartmentId: '', buildingId: '' } })
  }

  // 弹框取消按钮
  handleCancel() {
    // this.setState({ visibleData: { visible: false, apartmentId: '', buildingId: '' } })
    this.props.onSuccess()
  }

  getById(params) {
    const { apartmentId } = this.props.visibleData
    if (apartmentId === '' || apartmentId === undefined) {
      return
    }

    // 网路请求
    request({ ...apis.building.buildingApartmentGetById, urlData: { id: apartmentId }, params: { ...params } }).then(res => {
      // res.img = res.buildingImgList.map(item => item.url)
      if (res.buildingImgList) {
        res.img = res.buildingImgList[0].url
      }
      
      this.props.form.setFieldsValue(res)
    }).catch(err => {
     this.openNotificationWithIcon('error', err)
    })
  }

  openNotificationWithIcon = (type, message) => {
    notification[type]({
      message,
      description:
        '',
    });
  };

  // 提交
  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.submitData(values)
      }
    });
  }

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

    // 网路请求
    request({ ...api, data: { ...data } }).then(() => {
      // eslint-disable-next-line no-unused-expressions
      this.openNotificationWithIcon('success', '操作成功')

      // 传递父组件事件
      // onSuccess() 是自定义
      this.props.onSuccess()

      // this.setState({ visibleData: { visible: false, apartmentId: '', buildingId: '' } }, () => console.log('回调：', this.state.visibleData))
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions
      this.openNotificationWithIcon('error', err)
    })
  }

  /**
   * 取消按钮
   *
   * @memberof ModalImage
   */
  closeModal() {
    this.setState({ visibleData: { visible: false, apartmentId: '', buildingId: '' } })
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <>
        <Modal
            title="户型设置"
            width={1100}
            destroyOnClose="true"
            footer={null}
            visible={this.state.visibleData.visible}
            onOk={() => this.handleOk()}
            onCancel={e => this.handleCancel(e)}
          >
            <Form {...formItemLayout} onSubmit={e => this.handleSubmit(e)}>
              <Form.Item label="编号" style={{ display: 'none' }}>
                  {getFieldDecorator('apartmentId')(<Input />)}
              </Form.Item>
              <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}>{item.name}</Option>)
                    }
                  </Select>,
                )}
              </Form.Item>
              <Form.Item label="图片" help="建议图片尺寸336px*336px，比例1:1,格式：jpg">
              {getFieldDecorator('img', {
                  rules: [{ required: true, message: '请上传户型图片' }],
              })(
                // <ImageListUpload />,
                <ImageUpload />,
              )}
              </Form.Item>
              <Form.Item label="户型">
                {getFieldDecorator('houseType', {
                  rules: [{ required: true, message: '请选择户型' }],
                })(
                  <Select placeholder="户型">
                    {
                      houseType.map((item, _) => <Option value={item.id}>{item.name}</Option>)
                    }
                  </Select>,
                )}
              </Form.Item>
              <Form.Item label="面积" help="单位 ㎡">
                {getFieldDecorator('buildingArea')(<Input type="number" precision = '2' min='0.00' step='0.01'/>)}
              </Form.Item>
              <Form.Item label="使用面积" help="单位 ㎡">
                {getFieldDecorator('insideArea')(<Input type="number" precision = '2' min='0.00' step='0.01'/>)}
              </Form.Item>
              <Form.Item label="权重" help="数值越大越靠前">
                {getFieldDecorator('orderNo')(<Input type="number" />)}
              </Form.Item>
              <Form.Item style={{ width: '400px', margin: 'auto', display: 'flex', justifyContent: 'space-between' }}>
                <Button type="primary" htmlType="submit">保存</Button>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <Button onClick={() => this.handleCancel()}>取消</Button>
              </Form.Item>
            </Form>
        </Modal>
      </>
    );
  }
}

const WrappedModalImageForm = Form.create({ name: 'modalImage' })(ModalImage);

export default WrappedModalImageForm
