//外部药品目录对照
import React from 'react';
import { Table, Input, Button, Select, Divider, Popconfirm, message, Pagination, DatePicker, Row, Col, Modal } from 'antd';
import '../../assets/css/system.css';
import store from '../../store';
import { $http } from '../../containers/config/https';
import PublicModalTable from '../common/PublicModalTable';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const Option = Select.Option;
export default class ExternalDrugLinkCharge extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modalRowData: {},
            // 主菜单列表数据
            tableData: [],
            linkID: '',
            showUploadrecord: false,
            //自定义下拉框的值
            drugItemData: [],
            drugItemID: '',
            drugItemDesc: '',
            showInsuTable: false,
            num: '1',
            hospSelect: [],
            visStatus: false,
            insuItemDescInput: '',
            insuItemDescInput: true,
            //医院下拉框的值
            hospList: [],
            //传入的收费项ID
            itmID: '',
            downFlag: false,
            code: '',
            desc: '',

            // 抽屉显示
            visible: false,
            // 主菜单分页数据
            total: 0,
            page: 1,
            pageSize: 10,
            flag: '',
            title: '',
            // 是否显示loading
            showLoading: true,
            // 表格loading
            loading: true,
            hospID: '',
        }
        this.columns = [
            {
                title: "对照表ID",
                dataIndex: "id",
                width: '10%',
                align: 'center',
                key: 'id',
            },
            {
                title: '机构字典代码',
                dataIndex: 'compOrgCode',
                width: '15%',
                align: 'center',
                key: 'compOrgCode',
            },
            {
                title: "机构字典名称",
                dataIndex: "compOrgDescripts",
                width: '15%',
                align: 'center',
                key: 'compOrgDescripts',
            },
            {
                title: "收费项代码",
                dataIndex: 'hospDataCode',
                width: '15%',
                align: 'center',
                key: 'hospDataCode',
            },
            {
                title: '收费项名称',
                dataIndex: 'hospDataDescripts',
                width: '15%',
                align: 'center',
                key: 'hospDataDescripts',

            },
            {
                title: '医院',
                dataIndex: 'hosp',
                width: '10%',
                align: 'center',
                key: 'hosp',
            },
            {
                title: '生效日期',
                dataIndex: 'startDate',
                width: '10%',
                align: 'center',
                key: 'startDate',
            },
            {
                title: '失效日期',
                dataIndex: 'endDate',
                width: '10%',
                align: 'center',
                key: 'endDate',
            }
        ]
        this.drugColumns = [
            {
                title: "药品目录id",
                dataIndex: "drugId",
                width: '10%',
                align: 'center',
                key: '1',
            },
            {
                title: '药品目录代码',
                dataIndex: 'drugCode',
                width: '20%',
                align: 'center',
                key: '2',
            },
            {
                title: "药品目录名称",
                dataIndex: "drugDesc",
                width: '20%',
                align: 'center',
                key: '3',
            },
            {
                title: "规格",
                dataIndex: "spec",
                width: '20%',
                align: 'center',
                key: '4',
            },
            {
                title: "企业",
                dataIndex: "manfDesc",
                width: '20%',
                align: 'center',
                key: '5',
            },
            {
                title: "批准文号",
                dataIndex: "approvalNo",
                width: '20%',
                align: 'center',
                key: '6',
            }
        ]
    }



    componentDidMount() {
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.setState({
            // 初始化列表数据
            hospID: sessionInfo.hospID,
            itmID: this.props.itmID
        }, () => {
            this.handleQuery();
            this.handleHospSelect();
            this.handleDrugQuery();
            // 初始化设置table的高度以及表体的高度
            document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
        })

    }

    // 查询关联信息
    handleQuery = () => {
        let { itmID, hospID } = this.state;
        let data = {}
        data = {
            params: [{
                itmID: itmID,
                hospID: hospID
            }]
        }

        $http.post('urlS', this, {
            code: '05100326',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result.data) {
                    this.setState({ tableData: res.result.data, loading: false })
                } else {
                    this.setState({ tableData: [], total: 0, loading: false })
                }
            }
        })
    }

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

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }

    onRef = ref => {
        this.child = ref
    }


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

    /***下拉框***/
    //医院下拉框
    handleHospSelect = () => {
        let data = {}
        data = {
            params: [{
            }]
        }
        $http.post('urlS', this, {
            code: '01040078',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.data) {
                    let hospSelect = []
                    for (var i = 0; i < res.data.length; i++) {
                        hospSelect.push(<Option key={res.data[i].id} alias={res.data[i].descriptsSPCode}>{res.data[i].descripts}</Option>)
                    }
                    this.setState({
                        hospSelect: hospSelect
                    })
                }
            }
        })
    }

    /***双向绑定***/
    onChangeHospID = (value) => {
        this.setState({
            hospID: value
        });
    }

    onChangeText = (e) => {
        this.setState({
            drugItemID: '',
            drugItemDesc: e.target.value

        });
    }

    //关联表
    //改变行的颜色通过className
    setInsuLinkItemRowClassName = (record) => {
        return record.id === this.state.linkID ? 'clickRowStyle' : '';
    }

    //点击行进行ID赋值
    onClickInsuLinkItemRow = (record) => {
        if (this.state.linkID === "") {
            this.setState({
                linkID: record.id,

            });
        } else {
            if (this.state.linkID !== record.id) {
                this.setState({
                    linkID: record.id,
                });
            } else {
                this.setState({
                    linkID: '',
                });
            }
        }
    }

    //外部药品明细
    handleDrugQuery = (title) => {
        let { } = this.state;
        let data = {}
        data = {
            params: [{
                drugCode: title,
                drugDesc: title
            }]
        }

        $http.post('urlS', this, {
            code: '05100327',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result.data) {
                    this.setState({ drugItemData: res.result.data, loading: false })
                }
            }
        })
    }



    //添加对照
    handleAdd = () => {
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let { itmID, drugItemID, hospID } = this.state;
        if (drugItemID === "") {
            message("请用选择的医保目录的信息");
            return false;
        }
        let data = {}
        data = {
            params: [{
                itmID: itmID,
                drugItemID: drugItemID,
                hospID: hospID,
                userID: sessionInfo.userID,
            }]
        }
        $http.post('urlADS', this, {
            code: "05100328",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('对照成功');
                    // 刷新列表数据*/
                    this.handleQuery();
                }
            },
            error: function (error) {
                message.error('对照失败：' + error);
            }
        })
    }

    // 取消对照
    handleDetele = () => {
        let { linkID } = this.state;
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let data = {
            params: [{
                id: linkID,
                userID: sessionInfo.userID,
            }]
        }
        $http.post('urlADS', this, {
            code: '05100329',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('取消对照成功');
                    // 刷新列表数据
                    this.handleQuery()
                }
            },
            error: function (error) {
                message.error('删除失败：' + error);
            }
        })
    }

    // 操作弹框
    onClickRowPublic = (record) => {
        return {
            // 单击行选中
            onClick: () => {
                if (this.state.drugItemID === '') {
                    // 保存行数据以及ID
                    this.setState({ drugItemID: record.drugId })
                } else {
                    if (this.state.drugItemID !== record.drugId) {
                        this.setState({ drugItemID: record.drugId })
                    }
                }
            },
            onDoubleClick: () => {
                this.confirmSelection(record);
            }
        }
    }

    setRowClassNamePublic = (record) => {
        return record.id === this.state.drugItemID ? 'clickRowStyle' : '';
    }

    // 双击选中行数据的回调
    confirmSelection = (record) => {
        //this.resetFields();
        this.setState({ drugItemID: record.drugId, drugItemDesc: record.drugDesc, modalRowData: record }, () => {
            // 关闭弹窗
            this.child.handleCancel();
        })
    }


    // 描述回车事件
    insuItemOnPressEnter = (e) => {
        let top = 0;
        let left = document.getElementById('insuItemInput').getBoundingClientRect().left;
        this.setState({
            top: top,
            left: left
        });
        this.handleDrugQuery(e.target.value);
        this.child.showModal();
    }

    render() {
        let { height } = this.props;
        let param = {
            width: '600px',
            top: this.state.top,
            left: this.state.left,
            columns: this.drugColumns,
            data: this.state.drugItemData,
            isOnRow: true,
            TableClassName: 'tab-placeholder',
            rowClassName: true
        }
        return (
            <div style={{ marginTop: '12px' }} >
                < div >
                    <Row>
                        <Col span={24}>
                            外部药品信息：<Input style={{ width: "200px", marginRight: '10px' }} placeholder="回车检索" onChange={this.onChangeText} value={this.state.drugItemDesc} onPressEnter={this.insuItemOnPressEnter} id="insuItemInput" />
                            医院： <Select
                                showSearch
                                allowClear
                                placeholder="对照可选医院"
                                optionFilterProp="children"
                                style={{ width: "200px", marginRight: '10px' }}
                                value={this.state.hospID != '' ? this.state.hospID : JSON.parse(window.sessionStorage.userData).hospID}
                                onChange={this.onChangeHospID}
                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            >{this.state.hospSelect}</Select>
                        </Col>
                    </Row>
                    <Row style={{ marginTop: '10px' }}>
                        <Col span={24}>
                            <Button type="primary" onClick={this.handleQuery}>查询</Button>
                            <Button type="primary" onClick={this.handleAdd} style={{ marginLeft: '30px' }}>对照</Button>
                            <Button type="primary" onClick={this.handleDetele} style={{ marginLeft: '30px', background: 'rgba(255,0,0,1)', color: '#ffffff' }}>取消对照</Button>
                        </Col>
                    </Row>
                </div>
                <div className="mT20 table-body-height">
                    <Table
                        style={{ height: height ? (height + 50 + 'px') : store.getState().tableHeight.y - 25 + 'px' }}
                        dataSource={this.state.tableData}
                        columns={this.columns}
                        pagination={false}
                        scroll={{ x: 1500, y: height ? height : store.getState().tableHeight.y - 75 }}
                        bordered
                        rowClassName={this.setInsuLinkItemRowClassName}
                        onRow={(record) => {
                            return {
                                onClick: (event) => {
                                    this.onClickInsuLinkItemRow(record)
                                },
                            };
                        }}
                    />
                    <PublicModalTable
                        onClickRowPublic={this.onClickRowPublic}
                        setRowClassNamePublic={this.setRowClassNamePublic}
                        param={param}
                        onRef={this.onRef}
                    />
                </div>
            </div>

        )
    }
}
