import React, { useEffect, useState } from 'react'
import { Button, Radio, Icon, Form, Input, Row, Col, Modal, notification, Checkbox } from 'antd';
import { render } from 'react-dom';
import request from '../../../../../utils/request';
import apis from '../../../../../services/apis';


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

/**
 * 项目类型 form 表单子组件
 *
 * @param {*} props
 */
class TypeForm extends React.Component {

  componentDidMount() {
    this.props.form.setFieldsValue(this.props.type)
  }

  onChange(e, name) {
    // console.log(e.target.value)
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // console.log('Received values of form: ', values);
        values[name] = e.target.value
        values.buildingTypeName = this.props.type.buildingTypeName
        console.log('values: ', values)
        this.props.onSuccess(values)
      }
    });
  }

  close() {
    this.props.onClose(this.props.form.getFieldsValue(['buildingTypeId']))
  }

  render() {
    const { getFieldDecorator } = this.props.form;

    // this.props.form.setFieldsValue(this.props.type)

    return (
      <>
        <div>
          <Row>
            <Col span={8}>{ this.props.type.buildingTypeName || ''}</Col>
            <Col span={1}>
              <Button type="link" icon="close" onClick={() => this.close()} />
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form {...formItemLayout}>
                <Form.Item label="类型编号" style={{ display: 'none' }}>
                  {getFieldDecorator('buildingTypeId')(<Input disabled />)}
                </Form.Item>
                <Form.Item label="状态" style={{ display: 'none' }}>
                  {getFieldDecorator('status')(<Input disabled />)}
                </Form.Item>
                <Form.Item label="价格">
                  {getFieldDecorator('price')(<Input type="number" placeholder="元/㎡" onChange={e => this.onChange(e, 'price')}/>)}
                </Form.Item>
                <Form.Item label="装修标准">
                  {getFieldDecorator('decoration')(<Input onChange={e => this.onChange(e, 'decoration')}/>)}
                </Form.Item>
                <Form.Item label="产权年限">
                  {getFieldDecorator('rightsYear')(<Input onChange={e => this.onChange(e, 'rightsYear')}/>)}
                </Form.Item>
              </Form>
            </Col>
          </Row>
        </div>
      </>
    )
  }
}

const WrappedTypeForm = Form.create({ name: 'TypeForm' })(TypeForm);

/**
 *项目类型组件
 *
 * @param {*} props
 */
class ProjectTypeBody extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      one: false,
      projectType: [],
      defaultCheckboxValue: [], // 多选框默认选中的值
      visible: false,
      data: [],
      // data: [{ buildingTypeId: '1', buildingTypeName: '公寓', price: '10', decoration: '全包', rightsYear: '10', status: '1' }, { buildingTypeId: '2', buildingTypeName: '住宅', price: '10', decoration: '全包', rightsYear: '10', status: '1' }, { buildingTypeId: '3', buildingTypeName: '太平房', price: '10', decoration: '全包', rightsYear: '10', status: '1' }],
    }
  }

  componentDidMount() {
    this.getList({ pageNum: 1, pageSize: 999 })
  }

  componentDidUpdate(prevProps) {
    // 典型用法（不要忘记比较 props）：
    if (this.props.value !== prevProps.data && !this.state.one) {
      this.setValue()
      this.setState({ one: true })
    }
  }

  onSuccess = (values, item) => {
    console.log('values: ', values)
    console.log('data: ', this.state.data, 'item: ', item)
    const newData = this.getNewProjectType(values)
    console.log('newData: ', newData)
    this.setState({ data: newData })
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(newData)
    }
  }

  onCheckboxChange = checkedValues => {
      const checked = (`${checkedValues}` || '').split(',')
      const { projectType } = this.state
      const buildingType = projectType.filter(item => checked.includes(`${item.buildingTypeId}`))

      // 这里会把值替换掉

      const tempDate = buildingType.map(item => ({ buildingTypeId: item.buildingTypeId, buildingTypeName: item.buildingTypeName, price: '', decoration: '', rightsYear: '', status: '1' }))
      const updateProjectDate = this.updateProjectType(checkedValues)
      console.log('updateProjectDate: ', updateProjectDate)
      this.setState({ data: updateProjectDate })
  }

  onClose = e => {
    const { data } = this.state
    const buildingType = data.filter(item => e.buildingTypeId !== item.buildingTypeId)
    console.log('buildingType: ', buildingType)
    this.setState({ data: buildingType })
    this.setState({ defaultCheckboxValue: buildingType.map(item => item.buildingTypeId) })
  }

  getNewProjectType = values => {
    const data = []
    this.state.data.map(item => {
      console.log('item: ', item)
      if (item.buildingTypeId === values.buildingTypeId) {
        data.push(values)
      } else {
        data.push(item)
      }
    })

    return data
  }

  updateProjectType = values => {
    const data = []
    this.state.data.map(item => {
      values.map(va => {
        if (item.buildingTypeId === va.buildingTypeId) {
          data.push(va)
        } else {
          data.push(item)
        }
      })
    })

    return data
  }

  getList = params => {
    request({ ...apis.buildingType.getList, params: { ...params } }).then(res => {
      this.setState({ projectType: res.records })
    }).catch(err => {
      this.openNotificationWithIcon('error', err.message)
    })
  }

  setValue = () => {
    let tempData = []
    let tempCheckboxValue = []
    const { value } = this.props
    // console.log('value: ', value)
    if (value !== undefined && value !== null) {
      tempData = value
      tempCheckboxValue = tempData.map(item => item.buildingTypeId)
      this.setState({ defaultCheckboxValue: tempCheckboxValue })
      this.setState({ data: tempData }, () => {
        console.log("state: ", this.state.data)
      })

      console.log("tempData: ", tempData, "tempCheckboxValue: ", tempCheckboxValue, "value: ", value)
    }
  }

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

  handleOk = e => {
    this.setState({
      visible: false,
    });
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  showMadel = () => {
    this.setState({ visible: true })
    this.getList({ pageNum: 1, pageSize: 999 })
  }

  render () {

    // let tempData = []
    // let tempCheckboxValue = []
    // const { value } = this.props
    // if (value !== undefined && value !== null) {
    //   tempData = value
    // } else {
    //   tempData = this.state.data
    // }

    // tempCheckboxValue = tempData.map(item => item.buildingTypeId)
    return (
      <>
        <Button type="primary" icon="plus" size="large" onClick={() => this.showMadel()} />
        <Modal
          title="项目类型"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Checkbox.Group options={this.state.projectType.map(item => ({ label: item.buildingTypeName, value: item.buildingTypeId }))} defaultValue={this.state.defaultCheckboxValue} onChange={e => this.onCheckboxChange(e)} />
        </Modal>
        {
          this.state.data.map(item => <WrappedTypeForm type={item} key={item.id} onSuccess={(e) => this.onSuccess(e, item)} onClose={(e) => this.onClose(e)} />)
        }
      </>
    )
  }
}

export default ProjectTypeBody
