// 住院发药综合查询
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Icon, Table, Switch, message, Pagination } from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import '../../hospitalPharmacies/style/index.less';
var serialNumber = 0; //入库单序列号

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
};

const HPDrugComprehensiveInquiry = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                SelectData: {},
                inOpLocDr: '',
                vendor: '',
                detailsId: '',//入库单ID
                detailsListData: [], //入库单明细数据
                HPDrugData: [], //入库单数据
                pageSize: 10,
                page: 1,
                pageSize2: 10,
                page2: 1,
                total: 0,
                detailTotal: 0,
                noData: false,
                detailWidthTotal: '',
                columns: [],
                modalColumns: [],
                modificationList: false,  //默认隐藏修改表头弹窗
                showDetailPopup: false,  //默认隐藏修改表头弹窗
                listLength: '',  //列表长度
                parameterCode: ''

            }
            // 入库单的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '药品代码',
                    dataIndex: 'stockCode',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 2,
                    title: '药品名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                    width: '9%'
                },
                {
                    key: 3,
                    title: '数量',
                    dataIndex: 'qty',
                    align: "center",
                    width: '15%'
                },
                {
                    key: 4,
                    title: '金额',
                    dataIndex: 'amt',
                    align: "center",
                    width: '6%'
                },
                {
                    key: 5,
                    title: '规格',
                    dataIndex: 'stockSpec',
                    align: "center",
                    width: '6.5%'
                },
                {
                    key: 6,
                    title: '剂型',
                    dataIndex: 'formDesc',
                    align: "center",
                    width: '6%'
                },
                {
                    key: 7,
                    title: '生产厂家',
                    dataIndex: 'manfDesc',
                    align: "center",
                    width: '6.5%'
                },
                {
                    key: 8,
                    title: '单位',
                    dataIndex: 'unitDesc',
                    align: "center",
                    width: '6%'
                },
                {
                    key: 9,
                    title: '发药数量',
                    dataIndex: 'dispQty',
                    align: "center",
                    width: '15.5%'
                },
                {
                    key: 10,
                    title: '发药金额',
                    dataIndex: 'dispAmt',
                    align: "center",
                    width: '5%'
                },
                {
                    key: 11,
                    title: '退药数量',
                    dataIndex: 'retQty',
                    align: "center",
                    width: '5%'
                },
                {
                    key: 12,
                    title: '退药金额',
                    dataIndex: 'retAmt',
                    align: "center",
                    width: '5%'
                }
            ];
            // 入库单详细表头
            this.modalColumns = [
                {
                    key: 1,
                    title: '科室',
                    dataIndex: 'ordLocDesc',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 2,
                    title: '登记号',
                    dataIndex: 'patNO',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 3,
                    title: '姓名',
                    dataIndex: 'patName',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 4,
                    title: '性别',
                    dataIndex: 'sexDesc',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 5,
                    title: '年龄',
                    dataIndex: 'age',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 6,
                    title: '床号',
                    dataIndex: 'bedNO',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 7,
                    title: '处方号',
                    dataIndex: 'ordPrescNo',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 8,
                    title: '剂量',
                    dataIndex: 'ordDoseQty',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 9,
                    title: '剂型',
                    dataIndex: 'formDesc',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 10,
                    title: '单位',
                    dataIndex: 'unitDesc',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 11,
                    title: '售价',
                    dataIndex: 'sp',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 12,
                    title: '数量',
                    dataIndex: 'qty',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 13,
                    title: '金额',
                    dataIndex: 'spAmt',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 14,
                    title: '频次',
                    dataIndex: 'ordFreqDesc',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 15,
                    title: '发药时间',
                    dataIndex: 'dispTime',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 16,
                    title: '开方医生',
                    dataIndex: 'ordDocName',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 17,
                    title: '开方时间',
                    dataIndex: 'ordTime',
                    align: "center",
                    width: '150px'
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getDetailTableColumns();
            this.getDetailListTableColumns();
        }

        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let data = {
                params: [{
                    compontName: 'HPDrugComprehensiveInquiry',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return {
                                ...item,
                                key: index + 1,
                                title: <div onDoubleClick={() => {
                                    this.setState({ parameterCode: 'HPDrugComprehensiveInquiry' }, () => {
                                        this.columnRef.onOpenModel();
                                    })
                                }}>{item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({ columns: filterArr, detailWidthTotal: res.totalWidth })
                    }
                }
            })
        };

        // 获取明系列表头数据
        getDetailListTableColumns = () => {
            let data = {
                params: [{
                    compontName: 'HPDrugComprehensiveInquiryDeta',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return {
                                ...item,
                                key: index + 1,
                                title: <div onDoubleClick={() => {
                                    this.setState({ parameterCode: 'HPDrugComprehensiveInquiryDeta' }, () => {
                                        this.columnRef.onOpenModel();
                                    })
                                }}>{item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({ modalColumns: filterArr, listLength: res.totalWidth })
                    }
                }
            })
        };

        //清空表格内容
        handleReset = () => {
            this.setState({ HPDrugData: [], detailsListData: [], total: 0, detailsId: '' });
            this.props.form.resetFields();
        };

        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02040043",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({ SelectData: res })
                    }
                }
            })
        }

        handleQuery = () => {
            this.setState({ page: 1 }, () => {
                this.getHPDrugList()
            })
        };

        // 获取住院发药综合查询列表数据
        getHPDrugList = () => {
            let leftList = document.querySelectorAll('.tableHPDHeight  .ant-table-body');
            if (leftList.length > 0) {
                leftList[0].style.height = store.getState().tableHeight.y - 371 + 'px';
            }
            this.setState({ detailsId: '', loading: true });
            this.props.form.validateFields((err, val) => {
                let obj = JSON.parse(JSON.stringify(val));
                if (err == null) {
                    let data = {
                        params: [{
                            ...obj,
                            startDate: obj.startDate ? Moment(obj.startDate).format('YYYY-MM-DD') : undefined,
                            endDate: obj.endDate ? Moment(obj.endDate).format('YYYY-MM-DD') : undefined
                        }],
                        pagination: [
                            {
                                pageSize: this.state.pageSize,
                                currentPage: this.state.page,
                                sort: "ID",
                                dir: "asc",
                            }
                        ],
                    };
                    $http.post('urlS', this, {
                        code: "02040047",
                        data: data,
                        success: function (res) {
                            if (res.rows.length > 0) {
                                for (let i = 0; i < res.rows.length; i++) {
                                    res.rows[i].key = i;
                                }
                                this.setState({ HPDrugData: res.rows, total: res.total, page2: 1, loading: false, retAndDisp: res.rows[0].retAndDisp }, () => {
                                    serialNumber = 0;
                                    this.getHPDrugDetails(this.state.retAndDisp);
                                });

                            } else {
                                this.setState({ detailsListData: [], HPDrugData: [] });
                                if (!this.state.noData) {
                                    message.error("没数据");
                                } else {
                                    this.setState({ noData: false })
                                }
                            }
                        },
                        error: function (err) {
                            message.error(err.errorMessage)
                        }
                    });
                }
            });

        };
        // 获取入库单明细
        getHPDrugDetails(id) {
            let { retAndDisp } = this.state;
            let listData = document.querySelectorAll('.tableDetailHPDHeight  .ant-table-body');
            if (listData.length > 0) {
                listData[0].style.height = store.getState().tableHeight.y - 294 + 'px';
            }
            this.setState({ detailsLoading: true })
            let data = {
                params: [{
                    retAndDisp
                }],
                pagination: [
                    {
                        pageSize: this.state.pageSize2,
                        currentPage: id ? 1 : this.state.page2,
                        sort: "ID",
                        dir: "asc",
                    }
                ]
            };
            $http.post('urlS', this, {
                code: "02040048",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        serialNumber = this.state.detailsId ? this.state.detailsId : 0;
                        for (let i = 0; i < res.rows.length; i++) {
                            res.rows[i].key = i;
                        }
                        this.setState({ detailsListData: res.rows, detailTotal: res.total, detailsLoading: false });
                    } else {
                        this.setState({ detailsListData: [], detailTotal: 0, detailsLoading: false });
                    }
                },
                error: function () {
                    this.setState({ detailsListData: [], detailTotal: 0, detailsLoading: false });
                }
            })
        }

        //点击行，渲染当前行样式
        setRowClassName = (record) => {
            serialNumber = serialNumber + 1;
            if (record) {
                if (serialNumber == 1) return 'clickRowStyle';
                else if (this.state.detailsId == record.key) return 'clickRowStyle';
                else return '';
                // return this.state.detailsId == record.key ? 'clickRowStyle ': '';
            } else {
                return '';
            }
        };

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

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

        // 页码改变的回调，参数是改变后的页码及每页条数 入库单详情
        onChange2 = (page, pageSize) => {
            this.setState({ page2: page, pageSize2: pageSize }, () => {
                // 重新调用查询方法
                this.getHPDrugDetails();
            });
        };

        onShowSizeChange2 = (current, size) => {
            this.setState({ page2: current, pageSize2: size }, () => {
                // 重新调用查询方法
                this.onChange2(current, size);
            })
        };
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };

        render() {
            const { getFieldDecorator } = this.props.form;
            const { modalColumns, columns, listLength, detailWidthTotal } = this.state;
            let userInfo = this.state.userInfo ? this.state.userInfo : {};
            //入库科室列表
            let inOpLocDrSelect = [];
            this.state.SelectData.loc && this.state.SelectData.loc.map((item, i) => {
                inOpLocDrSelect.push(<Option value={item.id} key={i} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
            });

            // 就诊科室、医生科室
            let admAndDocLocOption = [];
            this.state.SelectData.admLoc && this.state.SelectData.admLoc.map((item, i) => {
                admAndDocLocOption.push(<Option value={item.id} key={i} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
            });

            return (
                <div className="HPDrugComprehensiveInquiry">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>查询条件</div>}
                        >
                            <Col span={21}>
                                <Form>
                                    <Row >
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label="发药科室">
                                                {getFieldDecorator('recLocID', {
                                                    initialValue: this.state.userInfo.locID ? this.state.userInfo.locID : undefined,
                                                    rules: [{ required: true, message: '发药科室不能为空' }]
                                                })(
                                                    <Select allowClear optionFilterProp="seatchprop" showSearch>
                                                        {inOpLocDrSelect}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label="病区">
                                                {getFieldDecorator('wardID', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '病区不能为空' }]
                                                })(
                                                    <Select allowClear optionFilterProp="seatchprop" showSearch>
                                                        {this.state.SelectData.ward && this.state.SelectData.ward.map((item, i) => {
                                                            return <Option value={item.id} key={i} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label="就诊科室">
                                                {getFieldDecorator('admLocID', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '就诊科室不能为空' }]
                                                })(
                                                    <Select allowClear optionFilterProp="seatchprop" showSearch>
                                                        {admAndDocLocOption}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label="医生科室">
                                                {getFieldDecorator('docLocID', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '医生科室不能为空' }]
                                                })(
                                                    <Select allowClear optionFilterProp="seatchprop" showSearch>
                                                        {admAndDocLocOption}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label="发药类别">
                                                {getFieldDecorator('dispCatID', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '发药类别不能为空' }]
                                                })(
                                                    <Select allowClear>
                                                        {this.state.SelectData.dispCat && this.state.SelectData.dispCat.map((item, i) => {
                                                            return <Option value={item.dispCatID} key={i}>{item.dispCatDesc}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label="发药人">
                                                {getFieldDecorator('dispUserID', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '发药人不能为空' }]
                                                })(
                                                    <Select allowClear optionFilterProp="seatchprop" showSearch>
                                                        {this.state.SelectData.locUser && this.state.SelectData.locUser.map((item, i) => {
                                                            return <Option value={item.id} key={i} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label="起初日期">
                                                {getFieldDecorator('startDate', {
                                                    initialValue: Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                    rules: [{ required: true }]
                                                })(
                                                    <DatePicker style={{ width: '100%' }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label="截至日期">
                                                {getFieldDecorator('endDate', {
                                                    initialValue: Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                    rules: [{ required: true }]
                                                })(
                                                    <DatePicker style={{ width: '100%' }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={3} style={{ textAlign: 'center' }} >
                                <Row style={{ marginBottom: '18px' }} className="button">
                                    <Button onClick={this.handleQuery}>查询</Button>
                                </Row>
                                <Row style={{ marginBottom: '18px' }}>
                                    <Button type="primary" onClick={this.handleReset}>清屏</Button>
                                </Row>
                            </Col>

                        </Card>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>发药综合查询列表</div>}
                                extra={<span style={{ color: '#666' }} className='span' onClick={() => {
                                    this.setState({ parameterCode: 'HPDrugComprehensiveInquiry' }, () => {
                                        this.columnRef.onOpenModel();
                                    })
                                }}><Icon type="setting" title="列权限设置" /></span>}
                            >
                                <div>
                                    <Table
                                        columns={columns.length > 0 ? columns : this.columns}
                                        dataSource={this.state.HPDrugData}
                                        pagination={false}
                                        bordered
                                        scroll={{ x: detailWidthTotal ? detailWidthTotal : 1500, y: 210 }}
                                        style={{ height: '250px' }}
                                        rowKey={record => record.key}
                                        rowClassName={this.setRowClassName}
                                        className="tableHPDHeight"
                                        onRow={(record) => {
                                            return {
                                                onClick: () => {
                                                    serialNumber = 9999;
                                                    this.setState({ detailsId: record.key, page2: 1, retAndDisp: record.retAndDisp }, () => {
                                                        this.getHPDrugDetails(this.state.retAndDisp)
                                                    });
                                                },

                                            };
                                        }}
                                    />
                                    <CommonPagination size='small' current={this.state.page} total={this.state.total} search='search'
                                        onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.HPDrugData}
                                        loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>明细</div>}
                                extra={<span style={{ color: '#666' }} className='span' onClick={() => {
                                    this.setState({ parameterCode: 'HPDrugComprehensiveInquiryDeta' }, () => {
                                        this.columnRef.onOpenModel();
                                    })
                                }}><Icon type="setting" title="列权限设置" /></span>}
                            >
                                <div>
                                    <Table
                                        columns={modalColumns ? modalColumns : this.modalColumns}
                                        dataSource={this.state.detailsListData}
                                        pagination={false}
                                        bordered
                                        scroll={{ x: 2550, y: store.getState().tableHeight.y - 414 }}
                                        style={{ height: (store.getState().tableHeight.y - 376) }}
                                        rowKey={record => record.key}
                                        className="tableDetailHPDHeight"
                                    />
                                    <CommonPagination size='small' current={this.state.page2} total={this.state.detailTotal} search='search'
                                        onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={true} dataSource={this.state.detailsListData}
                                        loading={this.state.detailsLoading} onChange={this.onChange2.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName={this.state.parameterCode}
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={() => {
                            if (this.state.parameterCode == 'HPDrugComprehensiveInquiry') {
                                this.getDetailTableColumns()
                            } else if (this.state.parameterCode == 'HPDrugComprehensiveInquiryDeta') {
                                this.getDetailListTableColumns()
                            }
                        }
                        }
                    />
                </div>
            )
        }
    }
);
export default HPDrugComprehensiveInquiry;