import React, { useEffect, useState } from 'react'
import { Button, Radio, Icon, Form, Input, Row, Col, Modal, notification, Checkbox, InputNumber } 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);
        const currentValue = e.target.value
        if (currentValue === '') {
          values[name] = null
        } else {
          values[name] = currentValue
        }
        
        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)
    console.log(this.props.type)
    return (
      <>
        <Col span={11} style={{
          position: 'relative',
          border: '1px solid #eee',
          borderRadius: '4px',
          marginTop:'16px'
        }}>

          <p style={{ padding: '20px', borderBottom: '1px solid #eee' }}>{this.props.type.buildingTypeName || ''}  <Button type="link" style={{ position: 'absolute', right: '16px' }} icon="close" onClick={() => this.close()} /></p>

          <Form {...formItemLayout} style={{ padding: '10px 0px 10px 10px' }}>
            <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>
      </>
    )
  }
}

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) => {
    const newData = this.getNewProjectType(values)
    this.setState({ data: newData })
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(newData)
    }
  }

  onCheckboxChange = checkedValues => {
    // console.log('checkedValues: ', 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: null, decoration: null, rightsYear: null, status: '1' }))
    const updateProjectDate = this.updateProjectType(tempDate)
    console.log('updateProjectDate: ', updateProjectDate)
    this.setState({ data: updateProjectDate })
  }

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

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

    return data
  }

  updateProjectType = values => {
    // 获取所有复选框选中的id
    const valueIdArray = values.map(item => item.buildingTypeId)
    // console.log('valueIdArray: ', valueIdArray)

    // 获取 data 中已经赋值的数据  交集
    const valueData = this.state.data.filter(item => valueIdArray.includes(item.buildingTypeId))
    // console.log('valueData: ', valueData)

    // 获取 非 data中数据(也就是没有赋值)，交集
    const trueValueArr = valueData.map(item => item.buildingTypeId)
    const trueValueData = values.filter(item => !trueValueArr.includes(item.buildingTypeId))

    // console.log('trueValueData: ', trueValueData)

    // 把两个 数组的值，合并返回
    return valueData.concat(trueValueData)
  }

  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 })
    }
  }

  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() {
    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>
        <Row type="flex" justify="space-between">
          {
            this.state.data.map(item => <WrappedTypeForm type={item} key={item.buildingTypeId} onSuccess={(e) => this.onSuccess(e, item)} onClose={(e) => this.onClose(e)} />)
          }
        </Row>
      </>
    )
  }
}

export default ProjectTypeBody
