// 手术护士执行
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Button, Table, Checkbox, message, Input, Modal } from 'antd';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import Moment from 'moment';
import store from 'store';
import AnesthesiaModel from './AnesthesiaModel.jsx';
import './style/index.less';

const FormItem = Form.Item;
const formItemLayout = { // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const formItemLayoutCheck = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
}
let userData;
const OperationNurseExecute = Form.create()(
    class extends React.Component {
        constructor() {
            userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
            super();
            this.state = {
                pageSize: 20,
                page: 1,
                total: 0,
                columns: [],
                columnsWidth: '',
                medInfo: {},
                tableData: [],
                data: [],
                selectedRowKeys: [],
                selectedRows: [],
                rowID: '',  //点击医嘱行
                ENObj: {},
                CNObj: {},
                languageObj: {},
                patNo: '',
                operationApplyID: '',
                visible: false
            }
        }

        componentDidMount() {
            this.setState({ rowID: '' });
            // 初始化数据
            this.getTableColumns();
            let self = this
            document.addEventListener("keydown", function (e) {
                self.KeyDowns(e)
            })
            setTimeout(() => { this.input.focus() }, 1000)
            this.handleQuery('')
        }

        componentWillUnmount() {
            setTimeout(() => {
                window.removeEventListener("keydown", this.KeyDowns())
            }, 1000)
            // 组件销毁前将静止让setState修改state的状态，防止内存泄漏
            this.setState = (state, callback) => { return; }
        }

        KeyDowns = (e) => {
            if (e && e.keyCode) {
                let self = this
                let currKey = 0;
                e = e || window.event;
                currKey = e.keyCode || e.which || e.charCode;
                //快捷键保存  shilt/alt/ctrl + s 
                if (currKey == 83 && e.ctrlKey) {
                    self.getOrdID('F')
                    e.preventDefault();
                    return false;
                }
            }
        }

        //获取列表头数据
        getTableColumns = () => {
            let data = {
                params: [{
                    reactCode: ['OperationNurseExecute'],
                    compontName: 'OperationNurseExecute',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let column = res.result.C;
                        if (userData.language == 'EN') {
                            for (let i = 0; i < column.length; i++) {
                                column[i].title = column[i].enDescripts
                            }
                        }
                        for (let i = 0; i < column.length; i++) {
                            // 晶体序列号列改文本框
                            if (column[i].dataIndex == 'crystalsSerialNo') {
                                column[i].render = (text, record, index) => {
                                    return (<Input
                                        value={record.crystalsSerialNo}
                                        ref={ref => this['crystalsSerialNo' + index] = ref}
                                        onChange={(e) => {
                                            let { tableData } = this.state
                                            tableData[index].crystalsSerialNo = e.target.value
                                            this.setState({ tableData })
                                        }}
                                        onPressEnter={this.bindCrystalsSerialNo.bind(this, record.execID, index)}
                                    />)
                                }
                            }
                        }
                        this.setState({
                            columns: column,
                            columnsWidth: res.totalWidth,
                            ENObj: res.result.language.EN,
                            CNObj: res.result.language.CN,
                        })
                    }
                }
            });
        };

        onColumnRef = (ref) => {
            this.columnRef = ref;
        }

        onConsumeRef = (ref) => {
            this.childOperation = ref;
        };

        getOrdID = (flag, e) => {
            var orderIDs = []
            for (var i = 0; i < this.state.selectedRows.length; i++) {
                orderIDs.push(this.state.selectedRows[i].execID)
            }
            if (orderIDs.length <= 0) { message.error("请选择需要操作的记录"); return }
            let data = {
                params: [{
                    ordIDs: orderIDs,//医嘱数组
                    date: "",
                    time: "",
                    userID: userData.userID,
                    code: flag,
                    locID: userData.locID,
                }]
            };
            // return 
            $http.post('urlS', this, {
                code: "04030003",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        message.success('成功');
                        this.setState({
                            data: res.result,
                            selectedRowKeys: [],
                            selectedRows: [],
                        })

                    } else {
                        this.setState({
                            data: [],
                        })
                    }
                    this.handleQuery()
                }
            });
        }

        // 按钮执行
        btnExec = async () => {
            let { selectedRows } = this.state
            for (let i = 0; i < selectedRows.length; i++) {
                if (selectedRows[i].crystalsSerialNo == undefined || selectedRows[i].crystalsSerialNo == '') {
                    continue;
                }
                let data = {
                    params: [{
                        execID: selectedRows[i].execID,
                        crystalsSerialNo: selectedRows[i].crystalsSerialNo,
                    }]
                }
                let res = await React.$asyncPost(this, '04010011', data);
                if (res.errorCode === '0') {
                    if (res.oth) {
                        window.sessionStorage.setItem('patientData', JSON.stringify({
                            patID: selectedRows[i].patID,
                            admID: selectedRows[i].admID
                        }))
                        this.setState({
                            operationApplyID: selectedRows[i].ordOperID,
                            visible: true
                        })
                        break;
                    } else {
                        this.handleExecOrdJT(selectedRows[i].execID, 'N')
                    }
                }
            }
            this.handleQuery('');
        }

        // 读卡
        searchUser = () => {
            var data;
            const formData = this.props.form.getFieldsValue();
            let patNo = formData.patNo
            data = {
                params: [{
                    "number": patNo || '', // 登记号/身份证号
                    "cardTypeID": "",   //卡类型id
                    "cardNo": "",    //卡号
                }]
            }
            if ((patNo === undefined) || (patNo === '')) {
                return false
            }

            $http.post('urlS', this, {
                code: "03040004",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        //检索条件默认
                        this.setState({ medInfo: {} })
                        this.props.form.setFieldsValue({
                            patNo: res.data.patNo,
                            ordStatusDesc: {},
                        }, () => {
                            this.handleQuery();
                        })
                    }
                }
            });
        }

        // 设置行属性
        onRowTabel = (record) => {
            return {
                // 单击行选中
                onRow: (event) => {
                    if (this.state.rowID === "") {
                        this.setState({ rowID: record.execID })
                    } else {
                        if (this.state.rowID !== record.execID) {
                            this.setState({ rowID: record.execID })
                        } else {
                            this.setState({
                                rowID: "",
                            }, () => {
                                this.getOrdID(record.execID);
                            });
                        }
                    }
                }
            }
        }

        // 获取列表数据
        handleQuery = (index = 0) => {
            const formData = this.props.form.getFieldsValue();
            let data = {
                params: [{
                    patNo: formData.patNo || "",
                    locID: userData.locID,
                    ordStartDate: formData.ordStartDate ? Moment(formData.ordStartDate).format('YYYY-MM-DD') : null,
                    ordEndDate: formData.ordEndDate ? Moment(formData.ordEndDate).format('YYYY-MM-DD') : null,
                    ordStatusDesc: this.state.medInfo.ordStatusDesc === 'Y' ? 'Y' : 'N',
                }],
                pagination: [{
                    pageSize: this.state.pageSize,
                    currentPage: this.state.page,
                }]
            };
            $http.post('urlS', this, {
                code: '04010012',
                data: data,
                success: (res) => {
                    if (res.errorCode === "0") {
                        let tableData = res.result?.data || [];
                        for (let i = 0; i < tableData.length; i++) {
                            tableData[i].key = i + 1;
                        }
                        this.setState({
                            total: res.result.total,
                            tableData,
                            selectedRowKeys: [],
                            selectedRows: [],
                        }, () => {
                            if (this.state.medInfo.ordStatusDesc !== 'Y' && tableData && tableData.length >= index) { // 晶体序列号获取焦点（根据传入的下标，默认第一行获取焦点）
                                this['crystalsSerialNo' + index]?.focus();
                            }
                        });
                    } else {
                        this.setState({
                            total: 0,
                            tableData: [],
                            selectedRowKeys: [],
                            selectedRows: [],
                        });
                    }
                }
            });
        }

        // 晶体医嘱绑定序列号
        bindCrystalsSerialNo = (execID, index, e) => {
            let { tableData } = this.state
            let data = {
                params: [{
                    execID,
                    crystalsSerialNo: e.target.value,
                }]
            }
            $http.post('urlS', this, {
                code: "04010011",
                data: data,
                success: function (res) {
                    if (res.errorCode === '0') {
                        if (res.oth) {
                            window.sessionStorage.setItem('patientData', JSON.stringify({
                                patID: tableData[index].patID,
                                admID: tableData[index].admID
                            }))
                            this.setState({
                                operationApplyID: tableData[index].ordOperID,
                                visible: true
                            })
                        } else {
                            this.handleExecOrdJT(execID, index)
                        }
                    }
                }
            })
        }

        // 晶体扫码后执行医嘱
        handleExecOrdJT = (execID, isQuery) => {
            let data = {
                params: [{
                    ordIDs: [execID],
                    date: "",
                    time: "",
                    userID: userData.userID,
                    code: 'F',
                    locID: userData.locID,
                }]
            }
            $http.post('urlDeault', this, {
                code: '04030003',
                data: data,
                success: (res) => {
                    if (isQuery === 'N') return;
                    if (+res.errorCode !== 0) {
                        this.handleQuery(isQuery);
                        // message.error("执行失败:" + res.errorMessage);
                    } else {
                        if (res.errorArr.length !== 0) {
                            message.error(res.errorArr.join(","));
                            this.handleQuery(isQuery);
                        } else {
                            // message.success("执行成功！");
                            this.handleQuery();
                        }
                    }
                }
            })
        }

        // 页码改变的回调，参数是改变后的页码及每页条数 库存单
        onChange = (page, pageSize) => {
            this.setState({ page: page, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                this.handleQuery();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({ page: current, pageSize: size }, () => {
                // 重新调用查询方法
                this.onChange(current, size);
            })
        };

        // 查询条件 --- 登记号
        patNo = (e) => {
            this.setState({ patNo: e.target.value });
        }

        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }

        setConsultLoc = (id, opt) => {
            this.setState({
                locID: id
            }, () => {
                this.searchUser();
            })
        }

        //已执行医嘱
        frozenClick = (e) => {
            let { medInfo } = this.state
            medInfo.ordStatusDesc = medInfo.ordStatusDesc === 'Y' ? 'N' : 'Y'
            this.setState({
                medInfo: medInfo
            }, () => { this.handleQuery(); })
        }

        // 替换晶体弹框确认        
        handleOk = e => {
            this.setState({
                visible: false,
            }, () => this.childOperation.showModal());
        };

        handleCancel = e => {
            this.setState({
                visible: false,
            });
        };

        render() {
            var language = userData.language
            var languageObj = {}
            if (language == "EN") {
                languageObj = this.state.ENObj
            } else {
                languageObj = this.state.CNObj
            }
            let { columns, columnsWidth, patNo, pageSize } = this.state;
            let medInfo = this.state.medInfo ? this.state.medInfo : {}
            const { getFieldDecorator } = this.props.form;
            const rowSelection = {
                onChange: (selectedRowKeys, selectedRows) => {
                    this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows })
                },
                selectedRowKeys: this.state.selectedRowKeys,
            };

            return (
                <div className="ordersOff">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>晶体执行</div>}
                        >
                            <Col span={17}>
                                <Form>
                                    <Row>
                                        <Col span={5}>
                                            <FormItem {...formItemLayout} label={'人员标识'}>
                                                {getFieldDecorator('patNo', {
                                                    initialValue: patNo || undefined,
                                                    rules: [{ required: false, message: '请输入登记号' }]
                                                })(
                                                    <Input onPressEnter={(e) => {
                                                        this.searchUser();
                                                    }} ref={(input) => { this.input = input }}
                                                    />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={4} offset={1} className="time">
                                            <FormItem>
                                                {getFieldDecorator('ordStartDate', {
                                                    initialValue: Moment(Moment().format('YYYY-MM-DD')),
                                                    rules: [{ required: false, message: '开始日期不能为空' }]
                                                })(
                                                    <DatePicker format="YYYY-MM-DD" />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={1} style={{ textAlign: 'center', lineHeight: '37px' }}>
                                            <span>至</span>
                                        </Col>
                                        <Col span={4} className="time">
                                            <FormItem>
                                                {getFieldDecorator('ordEndDate', {
                                                    initialValue: Moment(Moment().format('YYYY-MM-DD')),
                                                    rules: [{ required: false, message: '结束日期不能为空' }]
                                                })(
                                                    <DatePicker format="YYYY-MM-DD" />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={1} >
                                            <FormItem {...formItemLayoutCheck} label=''>
                                                {getFieldDecorator('ordStatusDesc', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '' }]
                                                })(
                                                    <Checkbox style={{ marginLeft: '30px' }} checked={medInfo.ordStatusDesc === 'Y' ? true : false} onChange={(even) => { this.frozenClick(even) }}></Checkbox>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={2} style={{ marginTop: '10px' }}>
                                            <span>已执行</span>
                                        </Col>
                                    </Row>

                                </Form>
                            </Col>
                            <Col span={7}>
                                <Row style={{ margin: '5px 0 18px 80px' }} className="button">
                                    <Button style={{ marginRight: '30px' }} onClick={() => this.handleQuery(0)}>查询</Button>
                                    <Button type="primary" onClick={this.btnExec} style={{ marginRight: '30px' }}>执行</Button>
                                    <Button type="primary" onClick={this.getOrdID.bind(this, "CE")}>撤销执行</Button>
                                </Row>
                            </Col>
                        </Card>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon">
                                    <div></div>晶体列表</div>
                                }
                            >
                                <div className="table-body-height">
                                    <Table
                                        columns={columns.length > 0 ? columns : this.columns}
                                        dataSource={this.state.tableData}
                                        pagination={false}
                                        bordered
                                        rowKey={(row) => {
                                            return row.execID
                                        }}
                                        onRow={this.onRowTabel}
                                        rowSelection={rowSelection}
                                        style={{ height: store.getState().tableHeight.y + 24 + 'px' }}
                                        scroll={{ x: columnsWidth ? columnsWidth : 1200, y: store.getState().tableHeight.y - 26 }}
                                        onHeaderRow={column => {
                                            return {
                                                onDoubleClick: () => {
                                                    this.columnRef.onOpenModel();
                                                },
                                            };
                                        }}
                                    />
                                    <CommonPagination size='small' pageSize current={this.state.page} total={this.state.total} search='search'
                                        onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
                                        loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='OperationNurseExecute'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getTableColumns}
                    />
                    <AnesthesiaModel
                        onRef={this.onConsumeRef}
                        operationID={this.state.operationApplyID}
                        activeKey={'1'}
                        handleQuery={() => this.handleQuery(0)}
                    />
                    <Modal
                        title="晶体替换"
                        visible={this.state.visible}
                        onOk={this.handleOk}
                        onCancel={this.handleCancel}
                    >
                        <p>当前晶体与申请晶体不匹配，是否替换</p>
                    </Modal>
                </div>
            )
        }
    }
);

export default OperationNurseExecute;