//产后记录
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, Modal, Table,Popconfirm,Icon, Pagination, message, TimePicker, Divider } from 'antd';
import moment from 'moment';
import { $http } from 'containers/config/https';
import store from 'store';
import PatientInfo from '../Patient/PatientInfo';
import "./CSS/ChildbirthRegister.less"
import { Util } from 'tools/index';
const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;
let userData ;
let initAdmID
const PostpartumRecords = Form.create()(
    class PostpartumRecords extends React.Component {
        cacheOriginData = {};
        constructor(props) {
            super(props)
            let patientData = {};
            if (window.sessionStorage.patientData) {
                patientData = JSON.parse(window.sessionStorage.patientData);
                }
            initAdmID = patientData.admID ? patientData.admID : '';
            userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
            this.state = {
                admID:initAdmID,
                baseFundus:[],//宫底高低下拉框
                baseBreast:[],//乳房下拉框
                baseLochiaColor:[],//恶露颜色下拉框
                baselochiaAmount:[],//恶露量下拉框
                baseperineum:[],//会因下拉框
                recordData: [],//产后记录表格数据
                selectData:[],
                saveFlag:false,       //保存按钮标志
            }
        }
        componentDidMount() {
            this.getSlect()
            this.getRecordData()
            this.handelSearch ();
        }
    //查询显示婴儿的信息 
    handelSearch = () => {
        let patientData = {};
        if (sessionStorage.patientData) {
          patientData = JSON.parse(sessionStorage.patientData);
        }
        let data = {
          params: [{
            power:"deliveryRoom",
            admID: patientData.admID ? patientData.admID : '',
          }]
        }
        $http.post('urlS', this, {
          code: "04110024",
          data: data,
          success: (res) => {
            if (+res.errorCode === 0) {
               // console.log(res);
              this.setState({
                selectData:res.result.Data,
              //  childPatName:res.result.childPatName

            })
                  
            }
          }
        })
      }
  
        //获取下拉框
        getSlect = () =>{
                let data = {}
                data = {
                    params: [{

                    }]
                  }
                  $http.post('urlS', this, {
                    code: '04110014',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({
                                baseFundus:res.fundus.data,//宫底高低下拉框
                                baseBreast:res.breast.data,//乳房下拉框
                                baseLochiaColor:res.lochiaColor.data,//恶露颜色下拉框
                                baselochiaAmount:res.lochiaAmount.data,//恶露量下拉框
                                baseperineum:res.perineum.data,//会因下拉框
                            })
                           
                        }
                    }
                })
        }
        //获取产后记录数据
        getRecordData = ()=>{
            let data = {}
            data = {
                params: [{
                    admID:initAdmID ? initAdmID : '',
                }]
              }
              $http.post('urlS', this, {
                code: '04110012',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            recordData:res.result
                        })
                    }else{
                        this.setState({
                          saveFlag:true,
                        })
                      }
                }
            })
        }
        //添加产后记录项模板
        addOrd = () => {
            const { recordData } = this.state;
            const newData = {
                id:"",
                admID:initAdmID ? initAdmID : '',
                recordDate: moment().format('YYYY-MM-DD'),
                recordTime: moment().format('HH:mm:ss'),
                key: `NEW_TEMP_ID_${this.index}`,
                bloodPressure: "",
                fundus: "",
                breast:"",
                lochiaColor:"",
                lochiaAmount:"",
                perineum:"",
                notes:"",
                handle:"",
                editable: true,
                isAdd: true,
            }
            this.index += 1;
            this.setState({ isAdd: true, recordData: [...recordData, newData] }, () => {
            });
        }
        //获取操作行数据对象
        getRowByKey(key, newData) {
            const { recordData } = this.state;
            return (newData || recordData).filter(item => item.id === key)[0];
        }
        //输入框 值更新
        handleFieldChangeDate(e,value,fieldName,key,index){
            const { recordData } = this.state;
            recordData[index][fieldName] = value
            this.setState({ recordData });
           
        }
        //选择框选择 值更新
        handleFieldChangeSelect(e,value,fieldName,key,index,desc){
            let {recordData} = this.state;
            recordData[index][fieldName] = value.key
            recordData[index][desc] = value.props.children
            this.setState({ recordData });
        }
        //文本框数据修改
        handleFieldChange(e, fieldName, key,index) {
            const { recordData } = this.state;
            recordData[index][fieldName] =  e.target.value;
            this.setState({ recordData });
        }
        //多行 -- 保存
        saveAll = ()=>{
            let data = {}
            data = {
                userID:userData.userID?userData.userID:"",
                params: this.state.recordData,
              }
              $http.post('urlS', this, {
                code: '04110011',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.state.recordData.map((item,index)=>{
                            if(item.isAdd){
                                item.isAdd=false
                            }
                            if(item.editable){
                                item.editable=false
                            }
                            item.key = index
                        })
                        this.setState({
                            recordData:[]
                        })
                        message.success("添加成功")
                        this.getRecordData()
                    }
                }
            })
        }
        //删除 产后记录项表格行
        cut = (e,record,key) => {
            let datas = {}
            let arr = []
            arr.push(record.id)
            datas = {
              params: [{
                afterChildbirthRecords:arr,
              }],
            }
            $http.post('urlS', this, {
              code: '04110013',
              data: datas,
              success: function (res) {
                if (+res.errorCode === 0) {
                    message.success("删除成功");
                    this.getRecordData()
                } 
              }
            })
        }
        //编辑 产后记录项表格行
        toggleEditable = (e, key, record,index) => {
            const { recordData } = this.state;
            e.preventDefault();
            let newData = recordData.map(item => ({ ...item }));
            let target = this.getRowByKey(key, newData);
            if (target) {
                if (!target.editable) {
                    this.cacheOriginData[key] = { ...target };
                }
                target.editable = !target.editable;
                this.setState({
                    recordData: newData,
                })
            }
        }
        //单行确定 回归不可编辑状态
        okOne = (e, key,record,index) =>{
            e.preventDefault();
            const { recordData } = this.state;
             let newData = recordData.map((item) => ({ ...item }));
             let target = this.getRowByKey(key, newData);
             target.editable = false;
             this.setState({ recordData: newData, });
        }
         //取消添加
         cancelAdd =(e,key,index) =>{
            e.preventDefault();
            const { recordData,} = this.state;
            const newData = recordData
            newData.splice(index,1)
            this.setState({ recordData: newData });
        }
        //取消 产后记录项表格行  编辑状态下
        cancel = (e, key,record,index) => {
            this.clickedCancel = true;
            e.preventDefault();
            const { recordData } = this.state;
            let newData = recordData.map((item) => ({ ...item }));
            let target = this.getRowByKey(key, newData);
            if (this.cacheOriginData[key]) {
                Object.assign(target, this.cacheOriginData[key]);
                delete this.cacheOriginData[key];
            }
            target.editable = false;
            this.setState({ recordData: newData, });
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            const { baseParms, localArr,baseFundus,baseBreast,baseLochiaColor,baselochiaAmount,baseperineum} = this.state;

            //科室
            let localArrOp = []
            localArr && localArr.map(item => {
                localArrOp.push(<Option key={item.id} disabled={item.disabled} value={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
            })
            //宫底高低
            let Fundus= []
            baseFundus && baseFundus.map(item => {
                Fundus.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
            })
             //乳房下拉框
             let Breast= []
             baseBreast && baseBreast.map(item => {
                Breast.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
             })
             //恶露颜色下拉框
             let LochiaColor= []
             baseLochiaColor && baseLochiaColor.map(item => {
                LochiaColor.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
             })
             //恶露量下拉框
             let lochiaAmount = []
             baselochiaAmount && baselochiaAmount.map(item => {
                lochiaAmount.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
             })
             //会阴下拉框
             let perineum = []
             baseperineum && baseperineum.map(item => {
                perineum.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
             })
            const dataSource = [
                {
                    key: '1',
                    recordDate: '2019-08-01',
                    recordTime: "test",
                    bloodPressure: '100cc',
                    Fundus: "10"
                },
                {
                    key: '2',
                    recordDate: '2019-08-07',
                    recordTime: "test1",
                    bloodPressure: '200cc',
                    Fundus: "20"
                },
                {
                    key: '3',
                    recordDate: '2019-08-06',
                    recordTime: "test2",
                    bloodPressure: '300cc',
                    Fundus: "30"
                },
            ];
            //左侧处方剂型
            const leftColumns = [
                {
                    width: 80,
                    align: "center",
                    title: '记录日期',
                    dataIndex: 'recordDate',
                    key: 'recordDate',
                    editable: true,
                    render: (text, record,index) => {
                        if (record.editable) {
                            return (
                                <DatePicker  
                                style={{ width: '100%' }}  
                                format='YYYY-MM-DD'
                                value={record.recordDate?moment(record.recordDate, 'YYYY-MM-DD'):undefined}      
                                onChange={(e,val)=> this.handleFieldChangeDate(e,val, 'recordDate', record.key,index)} 
                                disabledDate={(curDate) => {
                                    return curDate && curDate > moment().endOf('day');
                                }} />
                            )
                        }
                        return text;
                    }
                },
                {
                    width: 80,
                    align: "center",
                    title: '产后',
                    dataIndex: 'recordTime',
                    key: 'recordTime',
                    editable: true,
                    render: (text, record,index) => {
                        if (record.editable) {
                            return (
                                <TimePicker 
                                style={{width:'100%'}} 
                                separator=":" 
                                showToday
                                format='HH:mm:ss'
                                value={record.recordTime?moment(record.recordTime, 'HH:mm:ss'):undefined}
                                // format={this.state.isTransitionStart ? 'HH:mm' : 'HHmm'} 
                                // onOpenChange={this.handleOnOpenChangeStart}  
                                onChange={(e,val)=> this.handleFieldChangeDate(e,val, 'recordTime', record.key,index)}
                                placeholder="产后时间"
                                />
                                )
                        }
                        return text;
                    }
                },
                {
                    width: 80,
                    align: "center",
                    title: '血压(mmHg)',
                    dataIndex: 'bloodPressure',
                    key: 'bloodPressure',
                    editable: true,
                    render: (text, record, index) => {
                        if (record.editable) {
                            return (
                                <Input
                                    value={text}
                                    onChange={e => this.handleFieldChange(e, 'bloodPressure', record.key,index)}
                                />
                            )
                        }
                        return text;
                    },

                },
                {
                    width: 70,
                    align: "center",
                    title: '宫底高低',
                    dataIndex: 'fundusDesc',
                    key: 'fundus',
                    editable: true,
                    render: (text, record, index) => {
                        if (record.editable) {
                            return (
                                <Select
                                    value={record.fundus}
                                    style={{width:"100%", textAlign: "center" }}
                                    onChange={(e,value) => this.handleFieldChangeSelect(e,value,'fundus',record,index,"fundusDesc")}
                                >
                                    {Fundus}
                                </Select>
                            )
                        }
                        return text;
                    },
                },
                {
                    width: 80,
                    align: "center",
                    title: '乳房',
                    dataIndex: 'breastDesc',
                    key: 'breast',
                    editable: true,
                    render: (text, record, index) => {
                        if (record.editable) {
                            return (
                                <Select
                                    value={record.breast}
                                    style={{width:"100%", textAlign: "center" }}
                                    onChange={(e,value) => this.handleFieldChangeSelect(e,value,'breast',record.id,index,"breastDesc")}
                                >
                                {Breast}
                                </Select>
                            )
                        }
                        return text
                    },
                },
                {
                    width: 80,
                    align: "center",
                    title: '恶露颜色',
                    dataIndex: 'lochiaColorDesc',
                    key: 'lochiaColor',
                    editable: true,
                    render: (text, record, index) => {
                        if (record.editable) {
                            return (
                                <Select
                                    value={record.lochiaColor}
                                    style={{width:"100%",  textAlign: "center" }}
                                    onChange={(e,value) => this.handleFieldChangeSelect(e,value,'lochiaColor',record.id,index,"lochiaColorDesc")}
                                >
                                    {LochiaColor}
                                </Select>
                            )
                        }
                        return text
                    },
                },
                {
                    width: 70,
                    align: "center",
                    title: '恶露量',
                    dataIndex: 'lochiaAmountDesc',
                    key: 'lochiaAmount',
                    editable: true,
                    render: (text, record, index) => {
                        if (record.editable) {
                            return (
                                <Select
                                    value={record.lochiaAmount}
                                    style={{width:"100%", textAlign: "center" }}
                                    onChange={(e,value) => this.handleFieldChangeSelect(e,value,'lochiaAmount',record.id,index,"lochiaAmountDesc")}
                                >
                                    {lochiaAmount}
                                </Select>
                            )
                        }
                        return text
                    },
                },
                {
                    width: 70,
                    align: "center",
                    title: '会阴',
                    dataIndex: 'perineumDesc',
                    key: 'perineum',
                    editable: true,
                    render: (text, record, index) => {
                        if (record.editable) {
                            return (
                                <Select
                                    value={record.perineum}
                                    style={{width:"100%", textAlign: "center" }}
                                    onChange={(e,value) => this.handleFieldChangeSelect(e,value,'perineum',record.id,index,"perineumDesc")}
                                >
                                    {perineum}
                                </Select>
                            )
                        }
                        return text
                    },
                },
                {
                    width: 100,
                    align: "center",
                    title: '小便及膀胱情况',
                    dataIndex: 'handle',
                    key: 'handle',
                    editable: true,
                    render: (text, record, index) => {
                        if (record.editable) {
                            return (
                                <Input
                                    value={text}
                                    onChange={e => this.handleFieldChange(e, 'handle', record.key,index)}
                                />
                            )
                        }
                        return text;
                    },
                },
                {
                    width: 140,
                    align: "center",
                    title: '备注',
                    dataIndex: 'notes',
                    key: 'notes',
                    editable: true,
                    render: (text, record, index) => {
                        if (record.editable) {
                            return (
                                <Input
                                    value={text}
                                    onChange={e => this.handleFieldChange(e, 'notes', record.key,index)}
                                />
                            )
                        }
                        return text;
                    },
                },

                {
                    title: '操作',
                    dataIndex: 'operation',
                    key: 'action',
                    align: "center",
                    width: 80,
                    render: (text, record, index) => {
                        if (record.isAdd) {
                            return (
                                <span>
                                    <a onClick={(e) => this.cancelAdd(e,record.id,index)}>取消</a>
                                </span>
                            )
                        }
                        if(!record.editable){
                            return (
                                <span>
                                <a onClick={(e) => this.toggleEditable(e, record.id,record,index)}>编辑</a>
                                <Divider type="vertical" />
                                <Popconfirm title="是否要删除此行" onConfirm={(e) => this.cut(e,record,record.id)}>
                                <a style={{color:"red"}}>删除</a>
                                </Popconfirm>
                            </span>
                            )
                          }
                          if(record.editable){
                            return (
                                <span>
                                    <a onClick={(e) => this.okOne(e, record.id,record,index)}>确定</a>
                                    <Divider type="vertical" />
                                    <a onClick={(e) => this.cancel(e,record.id,record,index)}>取消</a>
                                </span>
                            )
                          }
                    }
                }
            ];
            return (
                <div style={{ padding: '4px 2px' }} className="DeliveryInformationDom">
                    <Row className="title" style={{padding: "12px",textAlign:'left',height: "36px"}}>
                        <Col>
                           <PatientInfo admID={this.state.admID}  />
                        </Col>
                    </Row>
                    <Divider />
                    <Row style={{padding: '0 12px 12px 12px' }}>
                        <Col span={22} style={{marginTop: '10px'}}> 
                            {this.state.selectData && this.state.selectData.map((item, i) => {
                                return (
                                    <div key={item.birthRecordID} style={{marginTop: '10px',display: i > 1 ? 'block' : 'inline-block'}}>
                                        <span>婴儿：{item.childPatName}</span>
                                        <Divider type="vertical" />
                                        <span>分娩时间：{item.childbirthDate}</span>
                                        <Divider type="vertical" />
                                        <span>分娩方式：{item.childbirthMethodDesc}</span>
                                        <span style={{margin: '0 12px', display: i === 0 ? 'inline-block' : 'none'}}>|</span>
                                    </div>
                                )
                            })}
                        </Col>    
                        <Col span={2}>
                            <Button style={{marginRight: '8px',marginTop: '10px'}} onClick={this.addOrd} size='small' type="primary">添加</Button> 
                            <Button style={{marginTop: '10px'}} disabled={this.state.saveFlag} onClick={this.saveAll} size='small' type="primary">保存</Button>
                        </Col>         
                        </Row>
                     {/* <Row style={{textAlign: "right",padding: "6px 98px"}}
                        <Button style={{marginRight: '8px'}} onClick={this.addOrd} size='small' type="primary">添加</Button> 
                        <Button onClick={this.saveAll} size='small' type="primary">保存</Button>
                    </Row> */}
                    <Table
                        columns={leftColumns}
                        pagination={false}
                        // rowClassName={this.setRowClassNames}
                        onRow={this.onClickRightRow}
                        dataSource={this.state.recordData && this.state.recordData.length > 0 ? this.state.recordData : []}
                        rowKey={(row) => {
                            return row.id
                        }}
                        className="clearBackground"
                        bordered
                    />
                    {/* <Row gutter={60} style={{ margin: '0', padding: "20px 20px", textAlign: "center" }}>
                        <Button onClick={this.saveAll} type="primary">保存</Button>
                    </Row> */}
                </div>
            )
        }
    })
export default PostpartumRecords    