/**
 * 
 * 部位弹框
 */

import React, { Component } from 'react';
import {
  Input, Form, Select, Modal, Button, Icon, Table, message,
  Tooltip, Card, Tree, Checkbox, Row, Col
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import '../style/index.less';
import moment from 'moment';

const Option = Select.Option;
const { TreeNode } = Tree;

class ShowPartsModal extends Component {

  constructor(props) {
    super(props);
    var date = new Date();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    var patientData = JSON.parse(sessionStorage.getItem('patientData'))
    this.state = {
      leftData: [],
      rightData: [],
      userData: userData,
      patientData: patientData,
      autoExpandParent: true,
      expandedKeys: [],
      selectedKeys: [],
      dataSource: [],
      sourceList: [],
      templateName: '',
      checked: []
    }
  }
  componentWillReceiveProps(nextProp) {
    if (nextProp.isShow === true) {
      var data = nextProp.partListModal;
      this.setState({
        partData: nextProp.dataSource, dataSource: data ? data : [],
        partLeftData: nextProp.dataSource ? nextProp.dataSource.partList : [],
        reviewData: data,
        // rowMedID: nextProp.rowMedID,
        medID: nextProp.medID
      }, () => {
        this.loadCommonModal()
        this.initData();
        this.loadData()
      })
    } else if (this.props.isShow === false) {
      this.cleanInput();
    }
  }

  componentDidMount() {
    this.initData();
  }

  loadCommonModal() {
    let data = {
      params: [{
        compontName: "ApplicationForm",
        type: "C",
        reactCode: ['ApplicationForm']
      }]
    }
    $http.post('urlDeault', this, {
      code: "01040073",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          this.setState({
            localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
          }, () => {
            this.initData()
          })
        }
      }
    })
  }

  //国际化
  setMessage(name, message) {
    return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
  }

  initData() {
    this.columns = [
      {
        title: this.setMessage('ApplicationFormPart', 'descripts') || '部位',
        dataIndex: 'title',
        width: 130,
        align: 'center',
      }, {
        title: this.setMessage('ApplicationFormAsana', 'descripts') || '体位',
        dataIndex: 'qty',
        width: 120,
        align: 'center',
        render: (text, data, index) => {
          var partOption = []
          data && data.part && data.part.map((item, index) => {
            partOption.push(<Option key={index} value={item.id} code={item.descripts}>{item.descripts}</Option>)
          })
          return <Select onChange={(e, option) => this.handleSelectChange('positionID', 'descripts',data.part, index, e, option)}
            value={data.positionID} mode="multiple"
            style={{ width: '100%' }}>{partOption}</Select>
        }
      }, {
        title: this.setMessage('ApplicationFormoperate', 'descripts') || '操作',
        dataIndex: '4',
        width: 120,
        align: 'center',
        render: (text, data, index) => {
          return <span style={{ color: 'red', cursor: 'pointer' }}
            onClick={this.handleDel.bind(this, index, data)}>{this.setMessage('ApplicationFormDelete', 'descripts')}</span>
        }
      }
    ]
    this.leftColumns = [
      {
        title: this.state.userData.language == 'EN' ? 'Parts' : '部位',
        dataIndex: 'descripts',
        width: 180,
        align: 'center',
      }
    ]
  }

  handleSelectChange(name, code,data, index, e, option) {
    var source = []
    for(var i=0;i<data.length;i++){
      for(var j=0;j<e.length;j++){
        if(data[i].id == e[j]){
          source.push(data[i].descripts)
        }
      }
    }
    this.state.dataSource[index][name] = e
    this.state.dataSource[index][code] = source
    this.setState({})
  }

  //删除
  handleDel(index, data) {
    var { checked, groupData } = this.state;
    if (!Util.isEmpty(groupData)) {
      for (var i = 0; i < groupData.length; i++) {
        if (groupData[i].id == data.id) {
          this.state.groupData[i]['checked'] = false
        }
      }
    }
    var checkOne = []
    if (!Util.isEmpty(checked)) {
      for (var i = 0; i < checked.length; i++) {
        if (checked[i] !== data.id) {
          checkOne.push(checked[i])
        }
      }
    }
    this.state.dataSource.splice(index, 1);
    this.setState({ checked: checkOne })
  }

  loadData() {
    var params = {
      params: [{
        medID: this.state.medID,
        areaID: this.state.rowMedID,
        hospID: this.state.userData.hospID,
        searchCode: this.state.templateName
      }]

    }
    $http.post('urlDeault', this, {
      code: "03050147",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          var groupData = res.result;
          var { dataSource } = this.state;
          if (!Util.isEmpty(dataSource) && !Util.isEmpty(groupData)) {
            for (var i = 0; i < groupData.length; i++) {
              for (var j = 0; j < dataSource.length; j++) {
                if (groupData[i].id == dataSource[j].id) {
                  groupData[i]['checked'] = true
                }
              }
            }
            this.setState({
              groupData: res.result,
            })
          } else {
            this.setState({
              groupData: res.result,
            })
          }
        }
      }
    });
  }

  closeModal(name) {
    let { onHide } = this.props;
    onHide && onHide();
    this.cleanInput();
  }

  //清空输入框
  cleanInput() {
    this.setState({
      dataSource: [],
      newCode: [],
      sourceList: [],
      rowMedID: ''
    })
  }

  delAllData() {
    var { groupData } = this.state;
    if (!Util.isEmpty(groupData)) {
      for (var i = 0; i < groupData.length; i++) {
        this.state.groupData[i]['checked'] = false
      }
    }
    this.setState({
      dataSource: [],
      newCode: [],
      sourceList: [],
      checked: []
    })
  }

  //双击到右边列表
  addpartDataToTable(data) {
    var { groupData, dataSource } = this.state;
    var sourceMap = []
    if (!Util.isEmpty(data)) {
      for (var i = 0; i < groupData.length; i++) {
        for (var j = 0; j < data.length; j++) {
          if (groupData[i].id == data[j]) {
            this.state.dataSource.push({
              title: groupData[i].descripts,
              id: groupData[i].id,
              number: groupData[i].number,
              part: this.state.partData ? this.state.partData.positionList : []
            })
          }
        }
      }
    }

    var result = []
    var obj = {}
    for (var i = 0; i < dataSource.length; i++) {
      for (var j = 0; j < data.length; j++) {
        // if (dataSource[i].id == data[j]) {
        if (!obj[dataSource[i].id]) {
          result.push(dataSource[i])
          obj[dataSource[i].id] = true;
        }
        // }
      }
    }
    // for(var i=0;i<dataSource.length -1; i++){
    //   for(var j=i+1;j<dataSource.length;j++){
    //     if(dataSource[i].id == dataSource[j].id){
    //       dataSource.splice(j,1)
    //       j--
    //     }
    //   }
    // }
    this.setState({ dataSource: result, checked: data })
  }

  onChangeCheck(data, e) {
    var code = []
    var { dataSource } = this.state;
    if (!Util.isEmpty(dataSource)) {
      for (var i = 0; i < dataSource.length; i++) {
        if (data.id !== dataSource[i].id) {
          code.push(dataSource[i])
        }
      }
    }
    this.setState({ dataSource: code })
  }

  onSubmit() {
    var { onSubmit } = this.props;
    var { dataSource } = this.state;
    // if (Util.isEmpty(dataSource)) {
    //   message.error(this.setMessage('ApplicationFormdata', 'descripts'),this.state.userData && this.state.userData.messageTime)
    //   return
    // }
    var data = []
    var number = 0
    if(Util.isEmpty(dataSource)){
      for (var i = 0; i < dataSource.length; i++) {
        data.push({
          partID: dataSource[i].id,
          positionID: dataSource[i].positionID
        })
        number += dataSource[i].number
      }
    }
    onSubmit && onSubmit(data, dataSource, number)
  }

  handleTemplateNameChange = e => {
    this.setState({
      templateName: e.target.value,
    });
  }

  onKeyDownList(e) {
    if (e.keyCode == '13') {
      this.loadData()
    }
  }

  setElement = (record) => {
    return {
      onClick: () => {
        this.setState({
          rowMedID: record.id
        }, () => {
          this.loadData()
        })
      }
    }
  }
  setRowClassName = (record) => {
    return record.id === this.state.rowMedID ? 'clickRowStyle' : '';
  }

  onChangeData(data, index, e) {
    var { dataSource, groupData } = this.state;
    var sourceMap = []
    if (e.target.checked) {

      if (!Util.isEmpty(dataSource)) {
        for (var i = 0; i < dataSource.length; i++) {
          if (data.id == dataSource[i].id) {
            message.error(this.setMessage('ApplicationFormyy', 'descripts'),this.state.userData && this.state.userData.messageTime)
            return
          }
        }
      }
      this.state.groupData[index]['checked'] = true
      for (var i = 0; i < groupData.length; i++) {
        if (data.id == groupData[i].id) {
          this.state.dataSource.push({
            title: groupData[i].descripts,
            id: groupData[i].id,
            number: groupData[i].number,
            part: this.state.partData ? this.state.partData.positionList : []
          })
        }
        this.setState({})
      }
    } else {
      this.state.groupData[index]['checked'] = false
      for (var i = 0; i < dataSource.length; i++) {
        if (data.id !== dataSource[i].id) {
          sourceMap.push(dataSource[i])
        }
        this.setState({ dataSource: sourceMap })
      }
    }
  }

  onDoubleClickMsg(data, index) {
    var { dataSource, groupData } = this.state;
    var sourceMap = []
    if (this.state.groupData[index]['checked'] === true) {

      this.state.groupData[index]['checked'] = false
      for (var i = 0; i < dataSource.length; i++) {
        if (data.id !== dataSource[i].id) {
          sourceMap.push(dataSource[i])
        }
        this.setState({ dataSource: sourceMap })
      }
    } else {
      if (!Util.isEmpty(dataSource)) {
        for (var i = 0; i < dataSource.length; i++) {
          if (data.id == dataSource[i].id) {
            message.error(this.setMessage('ApplicationFormyy', 'descripts'),this.state.userData && this.state.userData.messageTime)
            return
          }
        }
      }
      this.state.groupData[index]['checked'] = true
      for (var i = 0; i < groupData.length; i++) {
        if (data.id == groupData[i].id) {
          this.state.dataSource.push({
            title: groupData[i].descripts,
            id: groupData[i].id,
            number: groupData[i].number,
            part: this.state.partData ? this.state.partData.positionList : []
          })
        }
        this.setState({})
      }
    }
  }

  render() {

    var { templateName, partData, groupData, dataSource, checked } = this.state;
    var CheckOption = []
    groupData && groupData.map((item, index) => {
      // CheckOption.push(<Col span={8}onClick={this.onChangeCheck.bind(this,item)}>
      //   <Checkbox key={index} value={item.id}><span style={{ fontSize: 18 }}
      //   >{item.descripts}</span></Checkbox></Col>)

      CheckOption.push(<Col span={8}>
        <Checkbox key={index} value={item.id} onChange={this.onChangeData.bind(this, item, index)}
          checked={item.checked} /><span style={{ fontSize: 18, marginLeft: 5, cursor: 'pointer' }}
            onClick={this.onDoubleClickMsg.bind(this, item, index)}
          >{item.descripts}</span></Col>)
    })

    return <div>
      <Modal className='part-detail-modal'
        title={this.setMessage('ApplicationFormree', 'descripts') + this.props.medDesc + ')'}
        maskClosable={false}
        visible={this.props.isShow}
        okText={this.state.userData.language == 'EN' ? 'Submit' : '确定'}
        cancelText={this.state.userData.language == 'EN' ? 'Cancel' : '取消'}
        onOk={this.onSubmit.bind(this)}
        onCancel={this.closeModal.bind(this)}>
        <div style={{ float: 'left', width: '20.8%' }}>
          <Card hoverable={true}
            title={<span style={{ marginLeft: 10, color: 'rgba(0, 0, 0, 0.65)' }}>
              <Icon className='card-title-splice' />{this.setMessage('ApplicationFormPart', 'descripts')}</span>}
          // extra={<div onClick={this.batchAddTemplate.bind(this)} className='batch-add-temp'>
          //   <Icon type='plus-circle' />{this.setMessage('ApplicationFormaswew', 'descripts')}</div>}
          >
            <div style={{ height: '50vh', overflow: 'auto' }}>
              <Table columns={this.leftColumns}
                bordered
                dataSource={this.state.partLeftData}
                onRow={this.setElement}
                rowClassName={this.setRowClassName}
                rowKey={(data) => {
                  return data.id
                }}
                pagination={false}></Table>
            </div>
          </Card>
        </div>

        <div style={{ float: 'right', marginLeft: 10, width: '77%' }}>
          <div style={{ height: '25vh' }}>
            <div style={{ height: '3.5vh' }}>
              <span className='scheduling-title-border'></span>
              <span style={{ marginLeft: 10, lineHeight: '3.5vh', float: 'left' }}>{'添加部位'}</span>
              <span style={{ float: 'right' }}>
                <Input style={{ width: '25vh' }}
                  prefix={<Icon type="search" style={{ color: 'rgba(0,0,0,.25)' }} />}
                  onKeyDown={this.onKeyDownList.bind(this)}
                  placeholder={this.setMessage('ApplicationFormquery', 'descripts')} value={templateName} onChange={this.handleTemplateNameChange} />
              </span>
            </div>

            <div style={{ height: '21vh', overflowY: 'auto' }}>
              {/* <Checkbox.Group style={{ width: '100%' }} value={this.state.checked} onChange={this.addpartDataToTable.bind(this)}> */}
              <Row>{CheckOption}</Row>
              {/* </Checkbox.Group> */}
            </div>
          </div>
          <div style={{ height: 40, lineHeight: '40px' }}>
            <span className='scheduling-title-border' style={{ marginTop: 12 }}></span>
            <span style={{ float: 'left', marginLeft: 10 }}>{this.setMessage('ApplicationFormzzz', 'descripts')}</span>
            <span style={{ cursor: 'pointer', color: '#1890FF', float: 'right', marginRight: 10 }}
              onClick={this.delAllData.bind(this)}>{this.setMessage('ApplicationFormsdad', 'descripts')}</span>
          </div>
          <Table columns={this.columns} bordered
            dataSource={this.state.dataSource}
            scroll={{ y: '19vh' }}
            rowKey={(data) => {
              return data.id
            }}
            pagination={false}></Table>
        </div>
      </Modal></div>
  }
}

export default Form.create()(ShowPartsModal);