import React, { useEffect, useState } from 'react'
import { Button, Radio, Icon, Form, Input, Row, Col, Modal, notification, Checkbox, Select, 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)
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // console.log('Received values of form: ', values);
        const currentValue = name === 'marketStatus' ? e : e.target.value
        if (currentValue === '') {
          values[name] = null
        } else {
          values[name] = currentValue
        }
        
        values.buildingTypeName = this.props.type.buildingTypeName
        if(values["startPrice"] === "") {
          values["startPrice"] = null
        }
        if(values["endPrice"] === "") {
          values["endPrice"] = null
        }

        if(values["endPrice"] != null && values["startPrice"] == null){
          notification['warn']({
            message: "请填写最低价！",
            description: '',
          })
          return
        }
        if(values["startPrice"] != null && values["endPrice"] != null && Number(values["startPrice"]) > Number(values["endPrice"])){
          notification['warn']({
            message: "最低价不得高于最高价！",
            description: '',
          })
          return
        }
        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,"33333333")
    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: '5px 0px 5px 5px' }}>
            <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('priceType')(
                  <Radio.Group onChange={e => this.onChange(e, 'priceType')} >
                    <Radio value="average">均价</Radio>
                    <Radio value="total">总价</Radio>
                    <Radio value="lease">租赁价</Radio>
                  </Radio.Group>
                )}
              </Form.Item>
            <Form.Item label="价格区间" help='最高价与最低价一致时，只展示一个'>
              {getFieldDecorator('startPrice')(<Input type="number" placeholder="最低价" style={{width: '120px'}} maxLength="9" onChange={e => this.onChange(e, 'startPrice')} />)} --
              {getFieldDecorator('endPrice')(<Input type="number" placeholder="最高价" style={{width: '120px'}} maxLength="9" onChange={e => this.onChange(e, 'endPrice')} />)}{this.props.type.priceType === "average" ? "元/㎡" : this.props.type.priceType === "lease" ? "元/㎡/天" : "万元/套"}
            </Form.Item>
            <Form.Item label="销售状态" >
            {getFieldDecorator('marketStatus')(
              <Select placeholder="销售状态" onChange={e => this.onChange(e, 'marketStatus')} >
                <Option value="待售">待售</Option>
                <Option value="在售">在售</Option>
                <Option value="售罄">售罄</Option>
                <Option value="在租">在租</Option>
              </Select>,
            )}
          </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, startPrice: null,endPrice: null,priceType: "average", decoration: null, rightsYear: null, status: '1' }))
    const updateProjectDate = this.updateProjectType(tempDate)
    console.log('updateProjectDate: ', updateProjectDate)
    this.setState({ data: updateProjectDate })
    this.setState({ defaultCheckboxValue: updateProjectDate.map(item => item.buildingTypeId) })
  }

  onClose = e => {
    console.log(2)
    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——data111: ', buildingType)
    this.setState({ data: buildingType })
    this.setState({ defaultCheckboxValue: buildingType.map(item => item.buildingTypeId) })
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(buildingType)
    }
  }

  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}
          footer={
            [
            <Button key="submit" type="primary" onClick={this.handleOk}>
             确定  
            </Button>] 
          }
        >
          <Checkbox.Group options={this.state.projectType.map(item => ({ label: item.buildingTypeName, value: item.buildingTypeId }))} onChange={e => this.onCheckboxChange(e)} value={this.state.defaultCheckboxValue}/>
        </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
