import React from 'react';
import { Form, Button, Col, Row, Input, message, Modal, Select, Checkbox, Radio, Tabs } from 'antd';
import FormItem from 'antd/lib/form/FormItem';
import { $http } from 'containers/config/https';
import { Util } from 'tools/index';
import store from 'store';
import './style/index.less';
import PatientInfo from '../Patient/PatientInfo';

const { TabPane } = Tabs;
// 用户数据
let userData;
// 点击编辑时记录当前行数据
let tableRecord = {};
const { Option } = Select;

const radioLayout = {    // label 和input宽度
  labelCol: { span: 8 },
  wrapperCol: { span: 16},
};

// const radioLayoutAdd = {
//   labelCol: { span: 4},
//   wrapperCol: { span: 20},
// }
const radioLayoutChexck = {
  labelCol: { span: 4},
  wrapperCol: { span: 20},
}

const radioLayoutAdd = {
  labelCol: { span: 4},
  wrapperCol: { span: 20},
}
const radioLayoutInput={
  labelCol: { span: 4},
  wrapperCol: { span: 20},
}
const OperationCheck = Form.create()(
  class extends React.Component {
    constructor(props) {
      super(props);
      let patientData = JSON.parse(sessionStorage.getItem('patientData'));
      userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
      this.state = {
        admID:"",
        tableData: [],
        data: {},
        visible: false,//弹框显示状态
        patientData: patientData,
        activeKey: 0,
        patdoctor: '',
        patDoc: '',
        nurse: '',
        operationID: '',
        checkObj:{}
      }

    }
    componentDidMount() {
      this.props.onRef(this);
    }

    componentWillReceiveProps(nextProps) {  
    }
    //查询
    handleCheck = () => {
      let patientData = JSON.parse(sessionStorage.getItem('patientData'))
      if (!patientData || patientData.admID == '' || Util.isEmpty(this.state.tableData)) {
        return;
      }
      let cutTab=this.state.tableData[this.state.activeKey];
      let data = {
        params: [{
          operationID:this.props.operationID,
         // code:'PreAnaesthesia',
          code:cutTab.code,
          admID:patientData.admID ? patientData.admID : '',
        }]
      };
      $http.post('urlS', this, {
        code: '04160015',
        data: data,
        success: (res) => {
          if (res.errorCode === "0") {
            this.setState({ 
              data:this.state.checkObj[this.state.tableData[this.state.activeKey].code]?this.state.checkObj[this.state.tableData[this.state.activeKey].code]:res.result.data
            });
          } else {
            this.setState({
              data: {}
            });
          }
        }
      });
    }
    //保存
    handleSave = () => {
      let patientData = JSON.parse(sessionStorage.getItem('patientData'))
      if (!patientData || patientData.admID == '') {
        return;
      }
      let param={}
      let cutTab=this.state.tableData[this.state.activeKey];
      cutTab.component.map((conponent)=>{
        param[conponent.code]=this.props.form.getFieldValue(conponent.code)
      })
      let data = {
        params: [{
            //id:this.state.sonData[this.state.],
            operationID: this.props.operationID,
            admID: patientData.admID ? patientData.admID : '',
            checkCode: cutTab.code,
            data: param
        }]
      };
      $http.post('urlS', this, {
        code: '04160014',
        data: data,
        success: (res) => {
          //console.log(res);
          if (res.errorCode === "0") {
            message.success('成功');
            this.close();
          } else {
            this.setState({
          
            });
          }
        }
      });
    }
    // 关闭
    close = () => {
      this.setState({
        visible: false,
        data:{},
        checkObj:{},
      },() => {
        //console.log('111')
        this.props.handleQuery()
      });      
    };
    // 打开弹框
    showModal = (activeKey) => {
      this.handleSearch();
      //this.handleCheck();
      this.loadPatientMsg()//获取接诊病人信息
      let patientData = JSON.parse(sessionStorage.getItem('patientData'))
      if ((!patientData) || (patientData.admID == '')) {
        message.warning('请选择患者');
      }
      this.setState({
        visible: true,
        activeKey: activeKey?activeKey:0,
      });
    };

    changeActiveKey(e) {
      
      var isShow = false
      if (e == '3') {
        isShow = true
      }
      
      var formData = this.props.form.getFieldsValue();
      var formName = this.state.tableData[this.state.activeKey].code
      this.state.checkObj[formName] = formData

      this.props.form.resetFields();
      this.setState({
        activeKey: e,
        isShow: isShow,
        data:{},
      },()=>{
        this.handleCheck();
      })
    }

    //配置
    handleSearch = () => {
      let data = {
        params: [{

        }]
      };
      $http.post('urlS', this, {
        code: '04160013',
        data: data,
        success: (res) => {
          if (res.errorCode === "0") {
            for (let index = 0; index < res.result.length; index++) {
              res.result.Data[index].key = index + 1;
            }
            this.setState({
              tableData: res.result.Data,
            },()=>{
              this.handleCheck();
            });
          } else {
            this.setState({
              tableData: []
            });
          }
        }
      });
    }
  
    //麻醉医生
    handlePatDoctor = e => {
      this.setState({ patdoctor: e.target.value })
    }
    //手术医生
    handlepatDoc = e => {
      this.setState({ patDoc: e.target.value })
      
      
    }
    //手术护士
    handlePatNurse = e => {
      this.setState({ nurse: e.target.value })
    }

    loadPatientMsg() {
      let patientData = JSON.parse(sessionStorage.getItem('patientData'))
      if (!patientData || patientData.admID == '') {
        return;
      }
      var params = {
        params: [{
          admID: patientData.admID ? patientData.admID : '',
          userID: userData.userID
        }]
      }
      $http.post('urlDeault', this, {
        code: "04020007",
        data: params,
        success: function (res) {
          if (res.errorCode == '0') {
            sessionStorage.setItem('titleData', JSON.stringify(res.result))
            this.setState({
              titleData: res.result,
            })
          }
        }
      });
    }
    displayData = (data) => {
      let userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
      return userData.language == "EN" ? data.ENDesc : data.descripts;
    }
    render() {
      const { getFieldDecorator } = this.props.form;
      let tablePanel = [];
      let radioColSpan = +this.state.activeKey === 0 ? radioLayout : radioLayout
      //let CheckColColSpan = +this.state.activeKey === 0 ? radioLayout : radioLayoutChexck
      this.state.tableData.map((panelData, index) => {
       // console.log(index)
        tablePanel.push(
          <TabPane tab={<span>{this.displayData(panelData)}</span>} code={panelData.code} key={index + ""} >
            <Form>
              <div className="left">
                {
                  panelData.component.map((item, itemIndex) => {
                    if (item.title == "Y") {
                      return <Col span={24} style={{ width: '100%', padding: '0 12px' }}>{item.descripts}</Col>

                    } else {
                      if (item.type == "R") {
                        return <Col span={(item.singleLine == "Y") ? 24 :12}>
                          <FormItem {...radioColSpan} label={this.displayData(item)}>
                            {getFieldDecorator(item.code, {
                              initialValue: this.state.data[item.code],
                            })(
                              <Radio.Group>
                                {
                                  item.son.map((details, detailsIndex) => {
                                    return (<Radio value={details.code}>{this.displayData(details)}</Radio>)
                                  })
                                }
                              </Radio.Group>
                            )}
                          </FormItem>
                        </Col>
                      } else if (item.type == "C") {
                        return <Col span={(item.singleLine == "Y") ? 24 :12}>
                          <FormItem {...radioLayoutAdd} label={this.displayData(item)}>
                            {getFieldDecorator(item.code, {
                              initialValue: this.state.data[item.code],
                            })(<Checkbox.Group style={{ margin: '-10px',marginLeft:'2px'}}>
                              {
                                item.son.map((details, detailsIndex) => {
                                  return <Checkbox value={details.code} >
                                    {this.displayData(details)}
                                  </Checkbox>
                                })
                              }
                            </Checkbox.Group>
                            )}
                          </FormItem>
                        </Col>
                      } else if (item.type == "I") {
                        return <Col span={(item.singleLine == "Y") ? 12 : 12}>
                          <FormItem {...radioLayout} label={this.displayData(item)}>
                            {getFieldDecorator(item.code, {
                              initialValue:this.state.data[item.code],
                            })(
                              <Input></Input>
                            )}
                          </FormItem>
                        </Col>
                      }
                    }

                  })
                }
              </div>
            </Form>
          </TabPane >
        )
      })


      return (
        <Modal
          width='60%'
          title="手术安全核查"
          visible={this.state.visible}
          onCancel={this.close}
          footer={null}
        >
          <div className="outpatient-station-body">
            <Row style={{ background: 'rgba(248,248,248)', height: '45px', textAlign: 'left', lineHeight: '45px' }}>
              <Col span={24} style={{ display: 'flex' }}>
                <div style={{ width: '100%', height: 45, display: 'flex' }}>
                  <div className="ther" style={{ display: 'flex', flexShrink: '1', flex: '0 0 auto', width: 100 }}>
                    <div className={this.state.titleData && this.state.titleData.basicInfo.patSexCode == '1' ?
                      'splice-Boy' : (this.state.titleData && this.state.titleData.basicInfo.patSexCode == '2' ? 'splice-Girl' : 'splice-ther')}></div>
                    {/* <span className="bed">{this.state.titleData ? this.state.titleData.admInfo.admBedCode : ''}</span> */}
                    {/* <span>床号</span> */}
                  </div>
                  <div style={{ display: 'flex', flex: '1 1 auto' }}>
                    <div style={{ padding: '10px 0 0 20px' }} className="item">
                      <div>
                        <span className="bed">{this.state.titleData ? this.state.titleData.admInfo.admBedCode : ''}</span>
                        <i className="icon"></i>
                        <span>{this.state.titleData ? this.state.titleData.basicInfo.patName : ''}</span>
                      </div>
                      <div>
                        <i className="icon"></i>
                        <span>{this.state.titleData ? this.state.titleData.basicInfo.patSexDesc : ''}</span>
                      </div>
                      <div>
                        <i className="icon"></i>
                        <span>{this.state.titleData ? this.state.titleData.basicInfo.patAge : ''}</span>
                      </div>
                    </div>
                    <div style={{ fontWeight: 400, color: '#666666', fontSize: '16px', padding: '10px 0 0 20px' }} className="item">
                      <div>
                        <i className="icon"></i>
                        <span>{this.state.titleData ? this.state.titleData.admInfo.admLocDesc : ''}</span>
                      </div>
                      <div>
                        <i className="icon"></i>
                        <span>{this.state.titleData ? this.state.titleData.admInfo.admWardDesc : ''}</span>
                      </div>
                    </div>
                    <div style={{ fontWeight: 400, color: '#666666', fontSize: '16px', padding: '10px 0 0 20px' }} className="item">
                      <div>
                        <i className="icon"></i>
                        <span>{this.state.titleData ? this.state.titleData.basicInfo.patBirthDate : ''}</span>
                        <span>{this.state.titleData ? this.state.titleData.basicInfo.patBirthTime : ''}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </Col>
            </Row>
            <div>
              <Tabs defaultActiveKey={this.state.activeKey} onChange={this.changeActiveKey.bind(this)}>
                {tablePanel}
              </Tabs>
              <div className="save">
                <Button type='primary' onClick={this.handleSave}>保存</Button>
              </div>
              <br />
              <Row gutter={16} style={{ padding: '0 20px'}}>
                <Col span={8}> 麻醉医生签名:<Input style={{ width: '150px' }} value={this.state.patdoctor} onChange={this.handlePatDoctor} /></Col>
                <Col span={8}> 手术医师签名:<Input style={{ width: '150px' }} value={this.state.patDoc} onChange={this.handlepatDoc} /> </Col>
                <Col span={8}> 手术护士签名:<Input style={{ width: '150px' }} value={this.state.nurse} onChange={this.handlePatNurse} /></Col>
              </Row>
            </div>
          </div>
        </Modal>
      )
    }

  }
)
export default OperationCheck;