/*
 * Creator:     ML
 * CreatDate:   2020-09-22
 * descripts：  目录关联诊断信息 明细
 * */
import React from 'react';
import { Form, Input, Select, Button, message, Row, Modal, Divider, Popconfirm, DatePicker, Pagination, Table, Col } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import CommonPagination from 'components/pagination/index';
import store from 'store';
import { Util } from 'tools/index';
const { Option } = Select;
class DiagnosticClassificDeatils extends React.Component {
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            userData,
            info: {},
            ICD: "",
            diaID: "",
            total: 0,//医嘱项表格总数据
            page: 1,//页数
            pageSize: 50,//显示数
            search: "search",
            size: "large",
            dataSource: [],
            locList: [] //科室下拉框
        };
    }

    componentDidMount() {
        this.props.onAttRef(this);
        this.initData();
        this.getLocList();
    }

    getLocList = () => {
        const { userData } = this.state;
        let data = {
            params: [{
                hospID: userData.hospID
            }],
        }
        $http.post('urlS', this, {
            code: '04020008',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        locList: res.result.Data,
                    })
                }
            }
        })
    }

    initData() {
        this.columns = [
            {
                title: '诊断代码',
                dataIndex: 'diagnosisCode',
                width: 120,
                align: 'center'
            },
            {
                title: '诊断内容',
                dataIndex: 'diagnosisDesc',
                width: 220,
                align: 'center'
            },
            {
                title: '科室',
                dataIndex: 'locDesc',
                width: 120,
                align: 'center'
            },
            {
                title: '生效日期',
                dataIndex: 'startDate',
                width: 120,
                align: 'center'
            },
            {
                title: '生效日期',
                dataIndex: 'stopDate',
                width: 120,
                align: 'center'
            },
        ]
    }

    getInfo = (info, directID, data) => {
        this.clearInfo()
        this.setState({
            directID,
            OrdDaRowId: info.diagnosisID,
            dataSource: data,
            rowID: '',
            record: '',
            info: {},
            // OrdDaRowId: '',
            // ICD: info.nationDiaID,
            // diaID: info.diaID
        })
    }
    clearInfo = (n) => {
        this.props.form.resetFields();
        this.setState({
            // info: {},
        }, () => {
            if (n) this.setState({ OrdDaRowId: "" })
        })
    }
    saveAtt = () => {
        const { info, ICD, diaID, directID } = this.state
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = {
                    params: [{
                        locID: values.locID ? values.locID : "",
                        ID: info && info.ID ? info.ID : "",
                        directID: info && info.directID ? info.directID : directID,
                        diagnosisID: this.state.OrdDaRowId || "",
                        startDate: values.startDate ? moment(values.startDate).format('YYYY-MM-DD') : undefined,
                        stopDate: values.stopDate ? moment(values.stopDate).format('YYYY-MM-DD') : "",
                        userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                    }]
                }
                $http.post('urlS', this, {
                    code: '03050257',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            if (info && info.ID) {
                                message.success(this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntUpdateCompleted ? this.setMessage('BlacklistConfigurationTableIntUpdateCompleted', 'descripts') : '更新成功')
                                this.props.handleQuery()
                                this.props.handleInfo(info && info.directID ? info.directID : directID)
                            } else {
                                message.success(this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntAddedSuccessfully ? this.setMessage('BlacklistConfigurationTableIntAddedSuccessfully', 'descripts') : '添加成功')
                                this.props.handleQuery()
                                this.props.handleInfo(info && info.directID ? info.directID : directID,)
                            }
                        }
                    }
                })

            }
        })
    }
    del = (info) => {
        let data = {
            params: [{
                ID: info && info.ID ? info.ID : "",
                userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
            }]
        }
        $http.post('urlS', this, {
            code: '03050258',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success(this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntSuccessfullyDeleted ? this.setMessage('BlacklistConfigurationTableIntSuccessfullyDeleted', 'descripts') : '删除成功')
                    this.props.handleQuery()
                    this.props.handleInfo(info && info.directID ? info.directID : '')
                    this.clearInfo("1")
                    this.setState({
                        rowID: undefined,
                        info: {}
                    })
                }
            }
        })
    }
    //国际化
    setMessage(name, message) {
        return this.props.localeProvider ? this.props.localeProvider[name][message] : ''
    }
    //详细信息页面上下移动
    handleOnKeydown = (e) => {
        var e = window.event || e;
        let id = '';
        const { ordDetailData } = this.state
        let oneArr = ordDetailData && ordDetailData.length > 0 ? ordDetailData : [];
        switch (e.keyCode) {
            case 13:
                e.preventDefault();
                if (this.state.OrdDaRowId) {
                    this.setState({
                        visible: false,
                    })
                    let obj = {}
                    for (var i = 0; i < oneArr.length; i++) {
                        if (oneArr[i].medCode === this.state.OrdDaRowId) {
                            obj = i > 0 ? oneArr[i] : oneArr[0];
                            break;
                        }
                    }
                    // console.log("当前",obj)
                    this.setState({
                        visible: false,
                        OrdDaRowId: obj.medCode,
                    })
                    this.checkNowData(obj)
                    // this.confirmSelection(obj);
                } else {
                    message.info("请选择一条需要操作的数据")
                }
                break;
            case 38: //上
                if (this.state.OrdDaRowId) {
                    for (var i = 0; i < oneArr.length; i++) {
                        if (oneArr[i].medCode === this.state.OrdDaRowId) {
                            id = i > 0 ? oneArr[i - 1].medCode : oneArr[0].medCode;
                            break;
                        }
                    }
                    this.setState({ OrdDaRowId: id })
                } else {
                    this.setState({ OrdDaRowId: oneArr[0].medCode })
                }
                break;
            case 40: //下
                if (this.state.OrdDaRowId) {
                    for (let i = 0; i < oneArr.length; i++) {
                        oneArr[i].disblock = false
                        if (oneArr[i].medCode === this.state.OrdDaRowId) {
                            id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].medCode : oneArr[i + 1].medCode;
                            break;
                        }
                    }
                    this.setState({ OrdDaRowId: id })
                } else {
                    this.setState({ OrdDaRowId: oneArr[0].medID })
                }
                break;
        }
    }

    // 修改page和pageSize 跳转至---
    onChange = (e) => {
        this.setState({ page: e, pageSize: this.state.pageSize }, () => {
            // 重新调用查询方法
            let { values } = this.state;
            this.openNameDetail();
        })
    }
    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
        this.setState({ page: 1, pageSize: pageSize }, () => {
            // 重新调用查询方法
            let { values } = this.state;
            // if (this.state.outPatData && this.state.outPatData.length > 0) {
            this.openNameDetail("search");
            // }
        })
    }
    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }

    handleTemDaCancel = () => {
        this.setState({
            OrdDaShow: false,
            page: 1,
            pageSize: 50
        })
    }
    //名称/规格信息明细 回车
    openNameDetail = (n) => {
        // console.log(e, fieldName, key,data)
        const { ordTempId, page, pageSize, rightData } = this.state;
        let ordDetailValue = this.props.form.getFieldValue("diagnosisDesc")
        if (!ordDetailValue) {
            message.warning("请输入检索名称")
            return
        }

        if (ordDetailValue && ordDetailValue) {
            // debugger;
            //获取医嘱项信息
            let data = {}
            data = {
                params: [{
                    hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                    desc: ordDetailValue ? ordDetailValue : "",
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }
            $http.post('urlS', this, {
                code: '03050031',
                data: data,
                success: function (res) {
                    // debugger;
                    if (+res.errorCode === 0 && res.result.data && res.result.data.length > 0) {
                        for (var i = 0; i < res.result.data.length; i++) {
                            res.result.data[i].key = i
                        }
                        this.setState({
                            OrdDaRowId: res.result.data[0].id,
                            ordDetailData: res.result.data,
                            total: res.result.totalCount,
                            search: n && n || ""
                        }, () => {
                            this.setState({
                                OrdDaShow: true,
                            })
                        })
                    } else {
                        this.setState({
                            searchLoading: false,
                        })
                    }
                }
            })
        }
    }
    //文本框数据修改
    handleFieldChange = (e, fieldName,) => {
        if (e.target.value) {
            this.setState({
                ordDetailValue: e.target.value
            })
            this.props.form.setFieldsValue({
                diagnosisDesc: e.target.value
            });
        }
    }
    //设置医嘱项表row颜色
    setOrdDaRowClassName = (record) => {
        return record.id === this.state.OrdDaRowId ? 'clickRowStyle' : '';
    }
    //点击医嘱项表行信息
    onClickOrdDaRow = (record) => {
        return {
            onClick: () => {
                if (this.state.OrdDaRowId === "") {
                    this.setState({
                        OrdDaRowId: record.id,
                    });
                } else {
                    if (this.state.OrdDaRowId !== record.id) {
                        this.setState({
                            OrdDaRowId: record.id,
                        });
                    } else {
                        this.setState({
                            OrdDaRowId: "",
                        });
                    }
                }
            },
            onDoubleClick: () => {
                this.checkNowData(record)
            }
        };
    }
    checkNowData = (record) => {
        const { rightData, nowRowID } = this.state
        // console.log("信息带回", record, "rightData", rightData, "nowRowID", nowRowID)
        this.setState({
            OrdDaRowId: record.id,
            // ordDetailValue:record.medDesc,
            isAdd: true,
            diagnosisDesc: record.diagDesc
        })
        this.props.form.setFieldsValue({
            diagnosisDesc: record.diagDesc
        });
        this.setState({
            // ordTemPrice:record.medPrice,
            editDis: false,
            addInfo: true
        })
        this.handleTemDaCancel()
    }

    onClickRow = (record) => {
        return {
            onClick: () => {
                if (record.ID !== this.state.rowID) {
                    this.setState({
                        rowID: record.ID,
                        record: record,
                        info: record,
                        OrdDaRowId: record.diagnosisID,
                    })
                } else {
                    this.setState({
                        rowID: '',
                        record: '',
                        info: {},
                        OrdDaRowId: '',
                    })
                }
            }
        }
    }

    setRowClassName = (record) => {
        return record.ID == this.state.rowID ? 'clickRowStyle' : ''
    }

    render() {
        const { info, OrdDaShow, directID, locList } = this.state;

        const { getFieldDecorator } = this.props.form;

        const formLayout = {
            labelCol: { span: 9 },
            wrapperCol: { span: 15 },
        }
        const formLayoutDiag = {
            labelCol: { span: 5 },
            wrapperCol: { span: 17 },
        }

        //右侧查询医嘱项明细表
        const OrdDaColumns = [
            {
                align: "center",
                title: '编码',
                dataIndex: 'diagCode',
                key: '1'
            },
            {
                align: "center",
                title: '名称*规格',
                dataIndex: 'diagDesc',
                key: '2'
            },
            // {
            //   align: "center",
            //   title: '大类',
            //    dataIndex: 'medCatDesc',
            //    key: '3'
            // },
            // {
            //   align: "center",
            //   title: '子类',
            //   dataIndex: 'medSubCatDesc',
            //   key: '4'
            // },
            // {
            //   align: "center",
            //   title: '供应商',
            //   dataIndex: '',
            //   key: '5'
            // },
            // {
            //   align: "center",
            //   title: '产地',
            //   dataIndex: '',
            //   key: '6',
            //  },
        ];

        let locOption = locList && locList.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        return (
            <div>
                <Form layout={'horizontal'}>
                    {/*<Row >*/}
                    {/*    <Col span={6}>*/}
                    {/*        <Form.Item label={this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntCycle ?*/}
                    {/*            this.setMessage('BlacklistConfigurationTableIntCycle', 'descripts') : '诊断'} {...formLayoutDiag}>*/}
                    {/*            {getFieldDecorator('diagnosisDesc', {*/}
                    {/*                initialValue: info && info.diagnosisDesc ? info.diagnosisDesc : undefined,*/}
                    {/*                rules: [{*/}
                    {/*                    required: true, message: this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntCycle ?*/}
                    {/*                        this.setMessage('BlacklistConfigurationTableIntCycle', 'message') : '请选择诊断'*/}
                    {/*                }],*/}
                    {/*            })(*/}
                    {/*                <Input onPressEnter={this.openNameDetail} placeholder="输入诊断回车搜索" disabled={!Util.isEmpty(this.state.rowID)}></Input>*/}
                    {/*            )}*/}
                    {/*        </Form.Item>*/}
                    {/*    </Col>*/}

                    {/*    <Col span={5}>*/}
                    {/*        <Form.Item label="科室" {...formLayoutDiag}>*/}
                    {/*            {getFieldDecorator('locID', {*/}
                    {/*                initialValue: info && info.locID ? info.locID : undefined,*/}
                    {/*            })(*/}
                    {/*                <Select placeholder="请选择科室" showSearch optionFilterProp="seatchprop" allowClear>*/}
                    {/*                    {locOption}*/}
                    {/*                </Select>*/}
                    {/*            )}*/}
                    {/*        </Form.Item>*/}
                    {/*    </Col>*/}

                    {/*    <Col span={4} className="starDataDom">*/}
                    {/*        <Form.Item label={this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntEffectiveDate ? this.setMessage('BlacklistConfigurationTableIntEffectiveDate', 'descripts') : '生效日期'} {...formLayout}>*/}
                    {/*            {getFieldDecorator('startDate', {*/}
                    {/*                initialValue: info && info.startDate ? moment(info.startDate, "YYYY-MM-DD") : moment(),*/}
                    {/*                rules: [{ required: true, message: this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntEffectiveDate ? this.setMessage('BlacklistConfigurationTableIntEffectiveDate', 'message') : '请选择开始日期' }],*/}
                    {/*            })(*/}
                    {/*                <DatePicker style={{ width: '100%' }} disabled={!Util.isEmpty(this.state.rowID)} disabledDate={(curDate) => {*/}
                    {/*                    return curDate && curDate > moment().endOf('day');*/}
                    {/*                }} />*/}
                    {/*            )}*/}
                    {/*        </Form.Item>*/}
                    {/*    </Col>*/}

                    {/*    <Col span={4} >*/}
                    {/*        <Form.Item label={this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntExpirationDate ?*/}
                    {/*            this.setMessage('BlacklistConfigurationTableIntExpirationDate', 'descripts') : '失效日期'} {...formLayout}>*/}
                    {/*            {getFieldDecorator('stopDate', {*/}
                    {/*                initialValue: info && info.stopDate ? moment(info.stopDate, "YYYY-MM-DD") : undefined,*/}
                    {/*                rules: [{ required: false, message: '' }],*/}
                    {/*            })(*/}
                    {/*                <DatePicker style={{ width: '100%' }} />*/}
                    {/*            )}*/}
                    {/*        </Form.Item>*/}
                    {/*    </Col >*/}

                    {/*    <Col span={4} style={{ marginTop: 4 }}>*/}
                    {/*        <Button*/}
                    {/*            disabled={!directID}*/}
                    {/*            type="primary"*/}
                    {/*            onClick={this.saveAtt}>保存</Button>*/}

                    {/*        {*/}
                    {/*            (info && !info.ID) || !directID ? <Button disabled type="danger" style={{ marginLeft: 5 }}>{this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntDelete ?*/}
                    {/*                this.setMessage('BlacklistConfigurationTableIntDelete', 'descripts') : '删除'}</Button>*/}
                    {/*                : <Popconfirm title={this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntWhether ? this.setMessage('BlacklistConfigurationTableIntWhether', 'descripts') : '是否要删除该配置'} onConfirm={() => this.del(info)}>*/}
                    {/*                    <Button type="danger" style={{ marginLeft: 5 }}>{this.props.localeProvider && this.props.localeProvider.BlacklistConfigurationTableIntDelete ? this.setMessage('BlacklistConfigurationTableIntDelete', 'descripts') : '删除'}</Button>*/}
                    {/*                </Popconfirm>*/}
                    {/*        }*/}
                    {/*        <Button disabled={!directID} style={{ marginLeft: 5 }} type="primary" onClick={() => this.clearInfo("1")}>清空</Button>*/}
                    {/*    </Col>*/}
                    {/*</Row>*/}

                    <div style={{ marginTop: 10 }}>
                        <Table columns={this.columns}
                               dataSource={this.state.dataSource}
                               bordered
                               onRow={this.onClickRow}
                               rowClassName={this.setRowClassName}
                               rowKey={(data) => {
                                   return data.ID
                               }}
                               scroll={{ y: 650 }}
                               pagination={false}>
                        </Table>
                    </div>
                </Form>
                <div
                    tabIndex={1}
                    // onKeyDown={this.handleOnKeydown}
                    style={{ outline: 'none' }}
                    className="ordTempDateil"
                >
                    <Modal
                        key='3'
                        width='800px'
                        visible={OrdDaShow}
                        closable={false}
                        title={false}
                        centered={true}
                        pagination={false}
                        footer={null}
                        onCancel={this.handleTemDaCancel}>
                        <Table
                            columns={OrdDaColumns}
                            pagination={false}
                            rowClassName={this.setOrdDaRowClassName}
                            onRow={this.onClickOrdDaRow}
                            rowKey={record => record.key}
                            // expandedRowRender={expandedRowRender}
                            dataSource={this.state.ordDetailData}
                            style={{
                                height: '500px',
                                overflow: 'auto'
                            }}
                        />
                        <CommonPagination size={this.state.size} current={this.state.page}
                            //  pageSize={this.state.pageSize}
                                          total={this.state.total} search={this.state.search}
                                          onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.ordDetailData}
                                          onChange={this.onChange.bind(this)} />
                    </Modal>
                </div>
            </div>
        )
    }
};
const DiagnosticClassificDeatil = Form.create()(DiagnosticClassificDeatils);
export default DiagnosticClassificDeatil;
