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';
import styles from './style.less';
import cardImg from '../../../../assets/card.png';
import girlImg from '../../../../assets/girl.png';
import boyImg from '../../../../assets/boy.png';


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() {
    console.log(this.props.type, 'this.props.type')
    this.props.form.setFieldsValue(this.props.type)
  }

  onChange(e, name) {
    // console.log(e)
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.onSuccess(values)
      }
    });
  }

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

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

    return (
      <>
        <Col span={24} className={styles.card} >
          <Form {...formItemLayout} style={{ padding: '30px 26px' }}>
            <div className={styles.flexItem}>
              <img src={this.props.type.avatar} height="50px" width="50px" style={{ borderRadius: '50%', margin: ' 0 7px 0 10px' }} /><span>{this.props.type.contactName}</span>
            </div>
            <div className={styles.flexItem} style={{ justifyContent: 'space-between' }}>
              <div>
                {this.props.type.sex != '' && this.props.type.sex != null && <div className={styles.flexItem}>
                  <div className={styles.left}> 性别 </div>
                  <div className={styles.right} style={{ display: 'flex', alignItems: 'center' }}>{this.props.type.sex == '1' ? '男' : '女'}<img src={this.props.type.sex == '1' ? boyImg : girlImg} height="16px" width="16px" style={{ marginLeft: '5px' }} /></div>
                </div>}
                {this.props.type.appellation != '' && this.props.type.appellation != null && <div className={styles.flexItem}>
                  <div className={styles.left}><img src={cardImg} height="18px" width="24px" /></div>
                  <div className={styles.right}>{this.props.type.appellation}</div>
                </div>}
                {this.props.type.telephone != '' && this.props.type.telephone != null && <div className={styles.flexItem}>
                  <div className={styles.left}> 固话 </div>
                  <div className={styles.right}>{this.props.type.telephone}</div>
                </div>}
                {this.props.type.phone != '' && this.props.type.phone != null && <div className={styles.flexItem}>
                  <div className={styles.left}> 手机 </div>
                  <div className={styles.right}>{this.props.type.phone}</div>
                </div>}
                {this.props.type.mail != '' && this.props.type.mail != null && <div className={styles.flexItem}>
                  <div className={styles.left}> 邮箱 </div>
                  <div className={styles.right}>{this.props.type.mail}</div>
                </div>}
                {this.props.type.address != '' && this.props.type.address != null && <div className={styles.flexItem}>
                  <div className={styles.left}> 联系地址 </div>
                  <div className={styles.right}>{this.props.type.address}</div>
                </div>}
              </div>
              {this.props.type.wxCardImg != null && this.props.type.wxCardImg != '' &&
              <div style={{ textAlign: 'center' }}>
                <img src={this.props.type.wxCardImg} height="80px" width="80px" />
                <p style={{ margin: ' 0px', fontSize: '0.096rem', color: '#666' }}>扫码添加微信好友</p>
                <p sstyle={{ margin: ' 0px', fontSize: '0.096rem', color: '#666' }}>备注H5活动咨询</p>
              </div>}
            </div>
          </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: true,
      data: [],
      sampleId: props.sampleId,
      // 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 => {
    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)
      }
    })
    console.log('getNewProjectType', getNewProjectType)
    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.taH5SampleManager.taContactList, urlData: { id: this.state.sampleId } }).then(res => {
      this.setState({ data: res.records })
      console.log(this.state.data, 'data');
    }).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 (
      <>
        <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
