// 科室常用手术维护
import React from 'react';
import { Card, Row, Col, Form, Table, Select, Input, Button, message, Switch, DatePicker, } from 'antd';
import CommonPagination from 'components/pagination/index';
import PublicModalTable from 'pages/common/PublicModalTable';
import { $http } from 'containers/config/https';
// import './style/index.less';
import store from 'store';
import moment from 'moment';

const { Option } = Select;
const formItemInput = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 10 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span: 10 },
    wrapperCol: { span: 14 },
};
const LocFrequentOper = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                brandListData: [],
                rowKey: "",
                page: 1,
                degreesList: [],
                pageSize: 10,
                top: '',
                left: '',
                searchCode: '',
                modalRowId: '',
                operationDesc: '',
                operationID: '',
                total: '',
                ruleList: [],
                languageData:[],
                modalData: [],
                status: 'Valid'
            }
            
            this.modalColumns = [
                {
                    title: 'ICD编码',
                    dataIndex: 'ICDCode',
                    width: 80,
                    align: 'left',
                }, {
                    title: '手术名称',
                    dataIndex: 'descripts',
                    width: 200,
                    align: 'left',
                }, {
                    title: '手术级别',
                    dataIndex: 'categoryDesc',
                    width: 200,
                    align: 'left',
                }
            ];
            this.myRef1 = React.createRef();
        }

        componentDidMount() {
            // 初始化数据
            this.getTableData()
            this.getTableColumns()
        }
        // 常用手术维护table
        getTableColumns = () => {
            let data = {
                params: [{
                    "reactCode": ["LocFrequentOper"],
                    "compontName": "LocFrequentOper",
                    "type": "C"
                }]
            }
            $http.post('urlS', this, {
                code: "01040073",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setState({
                            languageData: res.result.C || [],  // 国际化语言包
                        })
                    }
                }
            });
        }


        // 键盘操作名称模态框数据
        handlePublicModalTableOnKeydown = (e) => {
            var e = window.event || e;
            let scroll_height = 26;
            let id = '';
            let oneArr = this.state.modalData && this.state.modalData.length > 0 ? this.state.modalData : [];
            switch (e.keyCode) {
                case 13:
                    if (this.state.modalRowId) {
                        let obj = {}
                        for (var i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                obj = i > 0 ? oneArr[i] : oneArr[0];
                                break;
                            }
                        }
                        this.confirmSelection(obj);
                    } else {
                        message.info("报错")
                    }
                    break;
                case 38: //上
                    if (this.state.modalRowId) {
                        for (var i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
                                break;
                            }
                        }
                        this.setState({ modalRowId: id })
                        setTimeout(() => {
                            var gundong = document.getElementById("gundong");
                            gundong.scrollTop = gundong.scrollTop - scroll_height;
                        }, 100)
                    } else {
                        this.setState({ modalRowId: oneArr[0].key })
                    }
                    break;
                case 40: //下
                    if (this.state.modalRowId) {
                        for (let i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
                                break;
                            }
                        }
                        this.setState({ modalRowId: id })
                        setTimeout(() => {
                            var gundong = document.getElementById("gundong");
                            gundong.scrollTop = gundong.scrollTop + scroll_height;
                        }, 100)
                    } else {
                        this.setState({ modalRowId: oneArr[0].key })
                    }
                    break;
            }
        };
        // 操作弹框
        onClickRowPublic = (record) => {
            return {
                onDoubleClick: () => {
                    this.confirmSelection(record);
                }
            }
        }
        // 双击选中行数据的回调
        confirmSelection = (record) => {
            console.log("record", record)
            this.props.form.setFieldsValue({ operationDesc: record.descripts })
            this.setState({ operationDesc: record.descripts, operationID: record.id }, () => {
                this.child.handleCancel();
            })
        }
        setRowClassNamePublic = (record) => {
            return record.key === this.state.modalRowId ? 'clickRowStyle' : '';
        }

        onRef = (ref) => {
            this.child = ref;
        }
        // 修改名称列表条数以及列数
        compilePage = (page, pageSize) => {
            this.setState({ page, pageSize }, () => {
                //this.getModalListData()
            })
        }
        // 名称回车事件
        nameOnPressEnter = (e) => {
            if (!e.target.value) {
                message.info("请输入名称回车搜索")
                return;
            }
            let top = document.getElementById('name-input').getBoundingClientRect().top + 40 + 'px';
            let left = document.getElementById('name-input').getBoundingClientRect().left + 'px';
            this.setState({
                top: top,
                left: left,
                searchCode: e.target.value
            }, () => {
                this.getModalListData("show");
            });
        }
        // 获取手术列表数据
        getModalListData = (isShow) => {
            let { searchCode } = this.state;
            let data = {
                params: [
                    {
                        search: searchCode,
                    }
                ]
            }
            $http.post('urlS', this, {
                code: "04160033",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.data ? res.result.data : [];
                        for (var i = 0; i < arr.length; i++) {
                            arr[i].key = i + 1
                        }
                        this.setState({ modalData: arr, modalRowId: arr && arr.length > 0 ? arr[0].key : '' }, () => {
                            isShow === 'show' ? this.child.showModal() : '';
                        })
                    } else {
                        this.setState({ modalData: [] });
                        isShow === 'show' ? this.child.showModal() : '';
                    }
                },
                error: function () {
                    this.setState({ modalData: [] });
                    isShow === 'show' ? this.child.showModal() : '';
                }
            })
        }
        // 名称失焦操作
        handleOnBlur = (e) => {
            if (this.state.operationID) {
                let arr = this.state.modalData ? JSON.parse(JSON.stringify(this.state.modalData)) : '';
                let status = false;
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i].operationDesc === e.target.value) {
                        status = true;
                        break;
                    }
                }
                if (!status) {
                    this.setState({ operationID: '', operationDesc: undefined })
                }
            } else {
                this.setState({ operationID: '', operationDesc: undefined })
            }
        }
        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态
            this.setState = (state, callback) => { return; }
        }


        // 查询
        handleQuery = () => {
            this.setState({ page: 1, pageSize: 10 }, () => {
                //查询
                this.getTableData();
            })
        }
        // 获取科室常用手术
        getTableData = () => {
            let { pageSize, page, status } = this.state
            var data = {
                params: [{
                    status
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }

            $http.post('urlS', this, {
                code: "04160032",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setState({
                            brandListData: res.result.data,
                            total: res.result.total
                        });
                    } else {
                        this.setState({
                            brandListData: []
                        });
                    }
                }
            });
        }
        
        //修改/保存科室常用手术列表
        saveData = () => {
            let seqNo = this.props.form.getFieldValue('seqNo');
            let startDate = this.props.form.getFieldValue('startDate');
            let stopDate = this.props.form.getFieldValue('stopDate');
            if (this.state.operationID === "") {
                message.error("手术不能为空")
                return
            }
            let {operationID,brandObj} = this.state
            var data = {
                params: [{
                    id: brandObj && brandObj.id ? brandObj.id : '',
                    operationID: operationID,
                    seqNo: seqNo ? seqNo : '',
                    startDate: startDate ? moment(startDate).format('YYYY-MM-DD') : '',
                    stopDate: stopDate ? moment(stopDate).format('YYYY-MM-DD') : '',
                }]
            }
            $http.post('urlS', this, {
                code: "04160031",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        message.success(res.errorMessage)
                        this.setState({ rowKey: '', brandObj: {}, operationID: '' }, () => {
                            this.props.form.setFieldsValue({ operationDesc: '', seqNo: '', startDate: '', stopDate: ''})
                        });
                        this.getTableData()
                    } else {
                        //message.error(res.errorMessage)
                    }
                }
            });
        }        
       
        // 科室表格行的类名
        setLocClassName = (record) => {
            return record.id === this.state.rowLocKey ? 'clickRowStyle' : '';
        };

        // 角色表格行的类名
        setRowClassName = (record) => {
            return record.id === this.state.rowKey ? 'clickRowStyle' : '';
        };
        // 设置角色行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({ rowKey: record.id, brandObj: record, operationID: record.operationID }, () => {
                            this.props.form.setFieldsValue({ operationDesc: record.operationDesc ? record.operationDesc : '', seqNo: record.seqNo ? record.seqNo + '' : '', startDate: record.startDate ? moment(record.startDate,'YYYY-MM-DD') : null, stopDate: record.stopDate ? moment(record.stopDate,'YYYY-MM-DD') : null})
                        });

                    } else {
                        if (this.state.rowKey !== record.id) {
                            this.setState({ rowKey: record.id, brandObj: record, operationID: record.operationID }, () => {
                                this.props.form.setFieldsValue({ operationDesc: record.operationDesc ? record.operationDesc : '', seqNo: record.seqNo ? record.seqNo + '' : '', startDate: record.startDate ? moment(record.startDate,'YYYY-MM-DD') : null, stopDate: record.stopDate ? moment(record.stopDate,'YYYY-MM-DD') : null})
                            });
                        } else {
                            this.setState({ rowKey: '', brandObj: {}, operationID: '' }, () => {
                                this.props.form.setFieldsValue({ operationDesc: '', seqNo: '', startDate: null, stopDate: null})
                            });
                        }
                    }
                }
            }
        };
        // 页码改变的回调，参数是改变后的页码及每页条数 出库单
        onChange = (page, pageSize) => {
            this.setState({ page: page, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                this.getTableData();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({ page: current, pageSize: size }, () => {
                // 重新调用查询方法
                this.onChange(current, size);
            })
        };
        // 状态下拉选择
        handleChange = (val) => {
            this.setState({status: val})
        }
        render() {
            const { getFieldDecorator } = this.props.form;
            let { brandObj, left, top, modalData, operationDesc,languageData } = this.state;
            let param = {
                width: '700px',
                height: 300,
                top: top,
                left: left,
                columns: this.modalColumns,
                data: modalData,
                isOnRow: true,
                TableClassName: 'tab-placeholder',
                rowClassName: true,
            }
            return (
                <div className="LocFrequentOper">
                    <Col span={12}>                        
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{'手术列表'}</div>}
                        >
                            <div style={{paddingBottom: '5px'}}>
                                <Row>
                                    <Col offset={14} span={6}>
                                    状态：<Select value={this.state.status} style={{ width: 120 }} onChange={this.handleChange}>
                                        <Option value="All">全部</Option>
                                        <Option value="Valid">有效</Option>
                                        <Option value="Invalid">无效</Option>
                                    </Select>
                                    </Col>
                                    <Col offset={1} span={2}>
                                        <Button onClick={this.getTableData}>查询</Button>
                                    </Col>
                                </Row>
                            </div>
                            <div>
                                <Table
                                    columns={languageData?languageData:this.columns}
                                    dataSource={this.state.brandListData}
                                    pagination={false}
                                    bordered
                                    scroll={{ y: store.getState().tableHeight.y - 13 }}
                                    style={{ height: (store.getState().tableHeight.y + 27) }}
                                    rowKey={record => record.key}
                                    className="tableDetailHeight"
                                    onRow={this.onClickRow}
                                    rowClassName={this.setRowClassName}
                                />
                                <CommonPagination size='small' current={this.state.page} total={this.state.total} search='search'
                                    onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.brandListData}
                                    onChange={this.onChange.bind(this)} />
                            </div>
                        </Card>
                    </Col>
                    <Col span={12}>
                        <Row >
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{'添加手术'}</div>}
                            >
                                <div style={{ height: (store.getState().tableHeight.y + 178) }}  >
                                    <Row>
                                        <div id="name-input">
                                            <Form.Item label={'手术名称：'} {...formItemInput}>
                                                {getFieldDecorator('operationDesc', {
                                                    initialValue: brandObj && brandObj.operationDesc ? brandObj.operationDesc : (operationDesc ? operationDesc : undefined),
                                                    rules: [{ required: true, message: '请选择手术' }]
                                                })(

                                                    <Input
                                                        onPressEnter={this.nameOnPressEnter}
                                                        placeholder="输入后回车检索"
                                                        onBlur={this.handleOnBlur}
                                                        autoComplete="off"
                                                        allowClear
                                                        ref={this.myRef1}
                                                    />

                                                )}
                                            </Form.Item>
                                        </div>
                                        <div
                                            tabIndex={1}
                                            onKeyDown={this.handlePublicModalTableOnKeydown}
                                            style={{ outline: 'none' }}
                                        >
                                            <PublicModalTable
                                                onClickRowPublic={this.onClickRowPublic}
                                                setRowClassNamePublic={this.setRowClassNamePublic}
                                                param={param}
                                                onRef={this.onRef}
                                                compilePage={this.compilePage}
                                                id="gundong"
                                            />
                                        </div>
                                    </Row>
                                    <Row >
                                        <Form.Item label={'序号'} {...formItemInput}>
                                            {getFieldDecorator('seqNo', {
                                                initialValue: brandObj && brandObj.seqNo ? brandObj.seqNo : undefined,
                                                //rules: [{ required: '请选择晶体度数' }]
                                            })(
                                                <Input />
                                            )}
                                        </Form.Item>
                                    </Row>
                                    <Row>
                                        <Form.Item label={'开始日期：'} {...formItemInput}>
                                            {getFieldDecorator('startDate', {
                                                initialValue: brandObj && brandObj.startDate ? moment(brandObj.startDate, 'YYYY-MM-DD') : moment(),
                                                rules: [{ required: true, message: '请选择生效日期' }]
                                            })(
                                                <DatePicker> </DatePicker>
                                            )}
                                        </Form.Item>
                                    </Row>
                                    <Row>
                                        <Form.Item label={'失效日期：'} {...formItemInput}>
                                            {getFieldDecorator('stopDate', {
                                                initialValue: brandObj && brandObj.stopDate ? moment(brandObj.stopDate, 'YYYY-MM-DD') : undefined,
                                            })(
                                                <DatePicker> </DatePicker>
                                            )}
                                        </Form.Item>
                                    </Row>
                                    <Row >
                                        <Col offset={11} span={2}>
                                            <Button type='primary' style={{ margin: '0 20px' }} onClick={this.saveData}>{'保存'}</Button>
                                        </Col>                                            
                                    </Row>
                                </div>
                            </Card>
                        </Row>
                    </Col>
                </div>
            )
        }
    }
);
export default LocFrequentOper;