//护士执行打印配置
import React from 'react';
import { Form, Card, Row, Col, Icon, Table, Button, Select, Input, Checkbox, message, Pagination, Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
import { Util } from '../../tools';
import PublicModalTable from '../common/PublicModalTable.jsx';
import './style/NursePrint.less';
import store from 'store';
const Option = Select.Option;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
};
const formItemAddLayout = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
};
let user;
const NursePrint = Form.create()(
    class extends React.Component {
        constructor(props) {
            super(props);
            user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
            this.state = {
                data: [],//表格数据
                columnData: [],//列数据
                dataSource: [],
                hospID: '',
                hospListData: [],//医院数据
                column: [],
                columnListData: [],
                docterPage: 1,
                docterPageSize: 10,
                doctorData: [],
                doctorTotal: 0,
                componentColumnID: '',
                doctorValue: '', //
                docterTop: 0,
                docterLeft: 0,
                docterAndNurse: 'docter', // 回车点击的是科主任还是护士长
                nursePage: 1,
                nursePageSize: 10,
                nurseData: [],
                nurseTotal: 0,
                nurseRowData: {},
                nurseTop: 0,
                nurseLeft: 0,
                receiptFlag: '',
                rowId: "",           //左侧行id
                rowID: "",            //右侧行id

            };

            this.columns = [
                {
                    key: 1,
                    title: 'code',
                    dataIndex: 'code',
                    align: "center",
                },
                {
                    key: 2,
                    title: 'descripts',
                    dataIndex: 'descripts',
                    align: "center",
                }
            ];
            this.columnData = [
                {
                    key: 1,
                    title: 'descripts',
                    dataIndex: 'descripts',
                    align: "center",
                }
            ]
        };
        componentDidMount() {
            this.handleQuery();
            this.loadColumn();
            // 初始化设置table的高度以及表体的高度
            document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';


        }
        onRef = (ref) => {
            this.child = ref;
        }

        // 保存用户信息表单提交
        handleSubmit = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {  //!err
                    let data = {
                        params: [{
                            ...values,
                            execPrintConfigID: this.state.rowID ? this.state.rowID : "",
                            execSheetID: this.state.rowId,
                            componentColumnID: this.state.componentColumnID,
                            updateUserID: JSON.parse(window.sessionStorage.userData).userID || "",
                        }]
                    };
                    $http.post('urlS', this, {
                        code: "04030013",
                        data: data,
                        success: function (res) {
                            // let errorCode = res.errorCode;
                            if (+res.errorCode === 0) {
                                // //重置表单
                                this.handleReset();
                                // this.handleSeach();
                                if (this.state.rowID) {
                                    message.success("修改成功");
                                    this.handleSeach();
                                } else {
                                    message.success("保存成功");
                                    this.handleSeach();
                                }
                                this.setState({componentColumnID: ''})
                            }
                        }
                    });
                }

            });
        }
        //3.18.1.3.删除护士执行单据打印配置
        handleDelete = () => {
            let data = {
                params: [{
                    updateUserID: JSON.parse(window.sessionStorage.userData).userID || "",
                    execPrintConfigID: this.state.rowID,
                }]
            }
            $http.post('urlADS', this, {
                code: '04030014',
                data: data,
                success: function (res) {
                    if (res.errorCode === '0') {
                        message.success('删除成功');
                        this.handleSeach()
                    }
                }
            })
        }
        //查询列头数据
        loadColumn = () => {
            let data = {
                params: [{
                    compontName: "NurPrintConfig",
                    type: "C",
                }]
            }
            $http.post('urlDeault', this, {
                code: "01040073",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        this.setState({
                            column: res.result.C,
                            tableWidth: res.totalWidth,
                        })
                    }
                }
            })

        }


        // 查询
        handleSeach = () => {
            let data = {
                params: [{
                    execSheetID: this.state.rowId,
                }]
            };
            $http.post('urlS', this, {
                code: "04030015",
                data: data,
                success: function (res) {
                    //console.log(res)
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setState({
                            dataSource: res.result.Data,
                        })
                    } else {
                        this.setState({
                            dataSource: [],

                        })
                    }
                }
            });
        }

        // 查询
        handleQuery = (hospID) => {
            let data = {
                params: [{
                    hospID: hospID ? hospID : user.hospID,
                }]
            };
            $http.post('urlS', this, {
                code: "04010008",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        for (var i = 0; i < res.result.length; i++) {
                            res.result[i].key = i;
                        }
                        this.setState({
                            data: res.result.sheetListData.result,
                            hospListData: res.result.hospListData,
                            columnListData: res.result.columnListData
                        })
                    } else {
                        this.setState({
                            data: [],

                        })
                    }
                }
            });
        }
        // 查询条件 ---医院  
        onChangeLoc = (value) => {
            this.setState({ hospID: value }, () => {
                this.handleQuery(this.state.hospID);
            });
        }

        // compileDoctorPage = (page, pageSize) => {
        //     this.setState({ docterPage: page, docterPageSize: pageSize }, () => {
        //         this.getDocterListData()
        //     })
        // }

        // 护士长操作弹框
        onClickRowNurse = (record) => {
            return {
                onDoubleClick: () => {
                    this.confirmSelectionNurse(record);
                }
            }
        }
        // 获取医生列表数据
        getDocterListData(values) {
            let { docterPage, docterPageSize } = this.state;
            let data = {
                params: [
                    {
                        input: values,
                    }
                ],
                pagination: [
                    {
                        currentPage: docterPage,
                        pageSize: docterPageSize
                    }
                ]

            }
            $http.post('urlS', this, {
                code: "01040003",
                data: data,
                success: function (res) {
                    // console.log(res)
                    if (+res.errorCode === 0) {
                        for (var i = 0; i < res.Data.length; i++) {
                            res.Data[i].key = i
                        }
                        this.setState({ doctorData: res.Data, doctorTotal: res.TotalCount })
                    }
                }
            })
        }

        // 获取科主任信息
        getDoctorData = (e) => {
            this.setState({ docterAndNurse: 'docter' });
            let top = document.getElementById('director-dr').getBoundingClientRect().top + 10 + 32 + 'px';
            let left = document.getElementById('director-dr').getBoundingClientRect().left + 8 + 'px';
            this.setState({
                docterTop: top,
                docterLeft: left,
                docterPage: 1,
                docterPageSize: 10,
                doctorValue: e.target.value
            }, () => {
                this.setState({ doctorData: this.state.columnListData, doctorTotal: this.state.columnListData.length })
            });
            this.child.showModal();
        }
        // 科主任操作弹框
        onClickRowDoctor = (record) => {
            return {
                onDoubleClick: () => {
                    this.confirmSelectionDoctor(record);
                }
            }
        }
        // 双击选中科主任行数据的回调
        confirmSelectionDoctor = (record) => {
            //console.log('45646545',record)
            this.setState({ componentColumnID: record.id }, () => {
                this.props.form.setFieldsValue({ componentColumnDesc: record.descripts })
                // 关闭弹窗
                this.child.handleCancel();
                //this.handleOnSelect(9)
            })
        }


        // 当科主任失去焦点后
        onBlurDirector = (e) => {
            let doctorRowData = this.state.doctorRowData
            let descripts = doctorRowData && doctorRowData.descripts ? doctorRowData.descripts : (this.state.userInfo && this.state.userInfo.componentColumnDesc ? this.state.userInfo.componentColumnDesc : '')
            if (e.target.value !== descripts) {
                this.props.form.setFieldsValue({ componentColumnDesc: undefined });
            }
        }

        // 显示分页总条数
        // showTotal(total) {
        //     return `共 ${total} 条`;
        // }
        //点击行，渲染当前行样式
        onClickRow = (record) => {
            return {
                onClick: () => {
                    if (this.state.rowId === "") {
                        this.setState({
                            rowId: record.id
                        }, () => {
                            this.handleSeach();
                        });
                    } else {
                        if (this.state.rowId !== record.id) {
                            this.setState({
                                rowId: record.id,
                            }, () => {
                                this.handleSeach();
                            });
                        } else {
                            this.setState({
                                rowId: "",
                            });
                        }
                    }
                    this.setState({
                        id: this.state.rowId
                    })
                },

            };
        }

        //设置点击row颜色 --左侧表格
        setRowClassName = (record) => {
            return record.id === this.state.rowId ? 'clickRowStyle' : '';
        }
        //右边点击行，渲染当前行样式
        onClickRow1 = (record) => {
            return {
                onClick: () => {
                    if (this.state.rowID === "") {
                        this.setState({
                            rowID: record.execPrintConfigID,
                            // doctorRowData:record,
                            userInfo: record,
                            componentColumnID: record.componentColumnID
                        });
                    } else {
                        if (this.state.rowID !== record.execPrintConfigID) {
                            this.setState({
                                rowID: record.execPrintConfigID,
                                // doctorRowData:record,
                                userInfo: record,
                                componentColumnID: record.componentColumnID
                            })
                        } else {
                            this.setState({
                                rowID: "",
                                userInfo: {},
                                componentColumnID: ''
                            },() => this.props.form.resetFields());
                        }
                    }

                },

            };
        }

        //设置点击row颜色 --左侧表格
        setRowClassName1 = (record) => {
            return record.execPrintConfigID === this.state.rowID ? 'clickRowStyle' : '';
        }

        //重置表单
        handleReset = () => {
            this.props.form.resetFields();
            this.setState({ rowID: '', userInfo: {} })
        };
        onChange = (e) => {
            const checked = e.target.checked
            checked ? this.setState({ receiptFlag: 'Y' }) : this.setState({ receiptFlag: 'N' })
            // console.log(`checked = ${e.target.checked}`);console.log(checked,"hhhh");

        }
        render() {
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.state.userInfo ? this.state.userInfo : {};
            let param = {
                width: 490,
                top: this.state.docterAndNurse === 'docter' ? this.state.docterTop : this.state.nurseTop,
                left: this.state.docterAndNurse === 'docter' ? this.state.docterLeft : this.state.nurseLeft,
                height: 400,
                columns: this.columns,
                data: this.state.docterAndNurse === 'docter' ? this.state.doctorData : this.state.nurseData,
                isOnRow: true,
                // showPagination: true,
                // total: this.state.docterAndNurse === 'docter' ? this.state.doctorTotal : this.state.nurseTotal,
                // page: this.state.docterAndNurse === 'docter' ? this.state.docterPage : this.state.nursePage
            }
            return (
                <div>
                    <div className='detail1'>
                        <Row>
                            <Col span={7}>
                                <Card
                                    size="small"
                                    title={<span><Icon type="search" />打印列设置</span>}
                                    headStyle={{ background: 'rgb(66, 185, 131)' }}
                                >
                                    <div style={{ height: store.getState().tableHeight.y - 81 + 'px', overflow: 'auto' }} className="detail-left" style={{ height: '801px' }}>
                                        <Row>
                                            <Col span={24}>
                                                <div>
                                                    <Select allowClear showSearch value={this.state.hospID} onChange={this.onChangeLoc} optionFilterProp="seatchprop" style={{ width: '200px', margin: '23px 15px 0 0' }} >
                                                        {this.state.hospListData && this.state.hospListData.map(item => {
                                                            return <Option key={item.id} value={item.id} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                    <Button onClick={this.handleQuery} style={{ margin: '23px 15px 0 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
                                                </div>
                                                <br />
                                                <Table
                                                    dataSource={this.state.data}
                                                    columns={this.columnData}
                                                    pagination={false}
                                                    showHeader={false}
                                                    rowKey={(row) => {
                                                        return row.id
                                                    }}
                                                    onRow={this.onClickRow}
                                                    rowClassName={this.setRowClassName}
                                                    loading={this.state.loading}
                                                    bordered
                                                />

                                            </Col>
                                        </Row>
                                        <Row >
                                            <Col span={12} style={{ paddingLeft: 10 }}>
                                                <Checkbox
                                                    onChange={this.onChange}
                                                >门诊打印检验回执单</Checkbox>
                                            </Col>
                                        </Row>
                                    </div>
                                </Card>
                            </Col>
                            <Col span={17}>
                                <Card
                                    size="small"
                                    title={<span><Icon type="search" />打印列</span>}
                                    headStyle={{ background: 'rgb(66, 185, 131)' }}

                                >
                                    <div style={{ height: store.getState().tableHeight.y - 81 + 'px' }} style={{ height: '715px' }}>
                                        <Form>
                                            {/* 第一行 */}
                                            <Row gutter={16} style={{ margin: '23px 15px 0 0' }}>
                                                <Col span={5}>
                                                    <Form.Item {...formItemLayout} label="序号">
                                                        {getFieldDecorator('configColumnSeqNo', {
                                                            initialValue: userInfo.configColumnSeqNo ? userInfo.configColumnSeqNo : undefined,
                                                            getValueFromEvent: (event) => {
                                                                return event.target.value.replace(/[^0-9]/g, '')
                                                            },
                                                        })(
                                                            <Input />
                                                        )}
                                                    </Form.Item>
                                                </Col>
                                                <Col span={5}>
                                                    <Form.Item {...formItemLayout} label="打印列名">
                                                        {getFieldDecorator('configColumnDesc', {
                                                            initialValue: userInfo.configColumnDesc ? userInfo.configColumnDesc : undefined,
                                                        })(
                                                            <Input />
                                                        )}
                                                    </Form.Item>
                                                </Col>
                                                <Col span={5}>
                                                    <Form.Item {...formItemLayout} label=" 打印列宽">
                                                        {getFieldDecorator('configColumnWidth', {
                                                            initialValue: userInfo.configColumnWidth ? userInfo.configColumnWidth : undefined,
                                                            getValueFromEvent: (event) => {
                                                                return event.target.value.replace(/[^0-9]/g, '')
                                                            },
                                                        })(
                                                            <Input />
                                                        )}
                                                    </Form.Item>
                                                </Col>
                                                <Col span={5} id="director-dr">
                                                    <Form.Item  {...formItemLayout} label="医嘱关联">
                                                        {getFieldDecorator('componentColumnDesc', {
                                                            initialValue: userInfo.componentColumnDesc ? userInfo.componentColumnDesc : undefined,
                    
                                                        })(
                                                            <Input placeholder="回车检索医嘱关联相关信息" ref={this.myRef9} onPressEnter={this.getDoctorData} onBlur={this.onBlurDirector} />
                                                        )}
                                                    </Form.Item>
                                                </Col>
                                                <Col span={4} style={{ textAlign: 'right' }}>
                                                    <Button
                                                        onClick={this.handleSubmit} icon="save"
                                                        style={{ background: 'rgba(247,128,93,1)', color: '#fff' }}>
                                                        保存
                                                    </Button>
                                                    <Button icon="delete" onClick={this.handleDelete} style={{ background: 'rgba(255,255,255,1)', marginTop: '3px', marginLeft: '7px' }}>刪除</Button>
                                                </Col>
                                            </Row>
                                        </Form>
                                        <Table
                                            style={{ marginTop: '2px' }}
                                            dataSource={this.state.dataSource}
                                            columns={this.state.column}
                                            pagination={false}
                                            rowKey={(row) => {
                                                return row.execPrintConfigID
                                            }}
                                            onRow={this.onClickRow1}
                                            rowClassName={this.setRowClassName1}
                                            bordered
                                        />

                                    </div>
                                </Card>
                            </Col>
                        </Row>
                    </div>
                    <PublicModalTable
                        onClickRowPublic={this.state.docterAndNurse === 'docter' ? this.onClickRowDoctor : this.onClickRowNurse}
                      //  compilePage={this.state.docterAndNurse === 'docter' ? this.compileDoctorPage: undefined}
                        param={param} onRef={this.onRef}
                    />
                </div>
            )
        }
    }
)
export default NursePrint;