//门诊发药配置
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Checkbox, Table, Input, message, Pagination  } from 'antd';
import CommonPagination from 'components/pagination/index';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import './style/index.less';

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

const outpatientDispensing = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                SelectData: {},
                inOpLocDr:'',
                vendor: '',
                detailsId: '',//列表ID
                WaListData: [], //列表数据
                pageSize: 10,
                page: 1,
                rowId: '', //行选中高亮id
                total:0,
                warehouseListId: '',
                locData: '',
                ordLocData: [],
                DoctorAdvice: [],
                listId: '',
                deleteState: false,
                selected: []
            };
            // 配药表头
            this.columns = [
                {
                    key: 1,
                    title: '开单科室',
                    dataIndex: 'orderLocDesc',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 2,
                    title: '接收科室',
                    dataIndex: 'recLocDesc',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 3,
                    title: '医嘱项',
                    dataIndex: 'medDesc',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 4,
                    title: '用法',
                    dataIndex: 'usageDesc',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 5,
                    title: '默认发药类型',
                    dataIndex: 'defaTypeDesc',
                    align: "center",
                    width: '20%'
                },
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getdefaultData();
        }

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

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

        // 获取门诊发药列表
        getDispenList=()=>{
            this.setState({loading: true})
            let ordLoc = this.props.form.getFieldValue('ordLoc');
            let meditem = this.props.form.getFieldValue('meditem');
            let recLoc = this.props.form.getFieldValue('recLoc');
            let data = {
                params: [{
                    recLocID: recLoc ? recLoc : '',
                    ordLocID: ordLoc ? ordLoc : '',
                    medID: meditem ? meditem : '',
                }],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                        sort:"ID",
                        dir:"asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02030016",
                data: data,
                success: function (res) {
                    if(res.result.rows.length > 0){
                        for(let i = 0; i < res.result.rows.length; i++){
                            res.result.rows[i].key = i;
                        }
                        this.setState({ WaListData: res.result.rows, total: res.result.total, loading: false});

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

        };

        // 保存
        approveDetermine=()=>{
            let ordLoc = this.props.form.getFieldValue('ordLoc');
            let meditem = this.props.form.getFieldValue('meditem');
            let recLoc = this.props.form.getFieldValue('recLoc');
            let type = this.props.form.getFieldValue('type');
            let usege = this.props.form.getFieldValue('usage');
            var arr = this.state.selected;
            if(arr){
                if(arr.medDesc !== meditem){
                    arr.medID = meditem;
                };
                if(arr.orderLocDesc !== ordLoc){
                    arr.orderLocID = ordLoc;
                }
            }
            let data = {
                params: [{
                    dispConfID: this.state.detailsId ? this.state.detailsId : '',
                    recLocID: recLoc ? recLoc : '',
                    ordLocID:arr.orderLocID ? arr.orderLocID : '' ,
                    medID: arr ? arr.medID : meditem,
                    usageID: usege ? usege : '',
                    defaTypeID: type ? type : ''
                }]
            };
                $http.post('urlS', this, {
                    code: "02030015",
                    data: data,
                    success: function (res) {
                        if(+res.errorCode == '0'){
                            this.props.form.setFieldsValue({
                                ordLoc:'',
                                recLoc:'',
                                meditem:'',
                                usage: '',
                                type: ''
                            });
                            this.setState({detailsId: '',rowId: ''});
                            this.getDispenList();
                            message.success(res.errorMessage);
                        }
                    },
                    error: function (err) {
                        message.error('保存失败');
                    }
                });


        };

        //获取选中列表数据
        getListDate = (vlue) => {
            this.setState({selected: vlue});
            this.props.form.setFieldsValue({
                ordLoc:vlue.orderLocDesc,
                recLoc:vlue.recLocID,
                meditem:vlue.medDesc,
                usage:vlue.usageID,
                type:vlue.defaTypeID
            });

        };

        //删除
        removeDispensing = () => {
            let data = {
                params: [{
                    dispConfID: this.state.detailsId ? this.state.detailsId : '',
                }]
            };
            if(this.state.detailsId){
                $http.post('urlS', this, {
                    code: "02030017",
                    data: data,
                    success: function (res) {
                        this.setState({detailsId: '',rowId: '',deleteState: true});
                        this.props.form.setFieldsValue({
                            ordLoc:'',
                            recLoc:'',
                            meditem:'',
                            usage: '',
                            type: ''
                        });
                        this.getDispenList();
                        message.info('删除成功');
                    },
                    error: function (err) {
                        message.error('删除失败')
                    }
                })
            }else {
                message.error('请选择删除门诊发药信息')
            }
        };

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

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

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

        //添加样式高亮
        setRowClassName=(record)=>{
            return record.dispConfID === this.state.rowId ? 'clickRowStyle' : '';
        };

        //获取开单科室
        handleSearch = (v) => {
            let data = {
                params: [{
                    alias: v,
                }]
            };
            //指定科室下拉
            if(v){
                $http.post('urlS', this, {
                    code: "02030007",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({ordLocData: res.result})
                        }
                    }
                })
            }
        };

        //获取医嘱ID下拉
        getDoctorAdvice = (id) => {
            let data = {
                params: [{
                    alias: id,
                }]
            };
            //指定科室下拉
            if(id){
                $http.post('urlS', this, {
                    code: "02020070",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({DoctorAdvice: res.result})
                        }
                    }
                })
            }
        };

        render() {
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.state.userInfo ? this.state.userInfo: {};
            //科室列表
            let recLocSelect = [];
            let inOpTypeDrSelect = [];
            let usageData = [];
            let ordLocList = [];
            let DoctorAdviceList = [];
            this.state.SelectData.errorCode == 0 && this.state.SelectData.recLoc.map((item, i) => {
                recLocSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.SelectData.errorCode == 0 && this.state.SelectData.type.map((item, i) => {
                inOpTypeDrSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.SelectData.errorCode == 0 && this.state.SelectData.usage.map((item, i) => {
                usageData.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.ordLocData.length > 0 && this.state.ordLocData.map((item, i) => {
                ordLocList.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.DoctorAdvice.length > 0 && this.state.DoctorAdvice.map((item, i) => {
                DoctorAdviceList.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });


            return (
                <div className="PrepareWin">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>门诊发药配置</div>}
                        >
                            <Col span={20}>
                                <Form>
                                    <Row >
                                        <Row>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="开单科室">
                                                    {getFieldDecorator('ordLoc',{
                                                        initialValue: undefined,
                                                        rules:[{ required : false, message: '开单科室不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch onSearch={this.handleSearch}
                                                                notFoundContent={null}
                                                                defaultActiveFirstOption={false}
                                                                showArrow={false}
                                                                filterOption={false}
                                                        >
                                                            {ordLocList}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="接收科室">
                                                    {getFieldDecorator('recLoc',{
                                                        initialValue: undefined,
                                                        rules:[{required: true,message: '接收科室不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch >
                                                            {recLocSelect}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="医嘱项ID">
                                                    {getFieldDecorator('meditem',{
                                                        initialValue: undefined,
                                                        rules:[{required: true,message: '医嘱项ID不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch
                                                                onSearch={this.getDoctorAdvice.bind(this)}
                                                                notFoundContent={null}
                                                                defaultActiveFirstOption={false}
                                                                showArrow={false}
                                                                filterOption={false}
                                                        >
                                                            {DoctorAdviceList}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="用法">
                                                    {getFieldDecorator('usage',{
                                                        initialValue: undefined,
                                                        rules: [{ required: false, message: '用法不能为空' }],
                                                    })(
                                                        <Select allowClear={true} showSearch >
                                                            {usageData}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="默认发药类型">
                                                    {getFieldDecorator('type',{
                                                        initialValue: undefined,
                                                        rules:[{required: true,message: '默认发药类型不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch>
                                                            {inOpTypeDrSelect}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={3}>
                                <Row style={{marginBottom: '18px',paddingLeft: '40px',marginTop: '4px'}}>
                                    <Button style={{marginRight: '30px'}} onClick={this.getDispenList}>查询</Button>
                                    <Button type="primary" onClick={this.handleReset}>清屏</Button>
                                </Row>
                                <Row style={{paddingLeft: '40px'}}>
                                    <Button type="primary"  style={{marginRight: '30px'}} onClick={this.approveDetermine}>保存</Button>
                                    <Button type="primary"  onClick={this.removeDispensing}>删除</Button>
                                </Row>
                            </Col>

                        </Card>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>配置明细列表</div>}
                            >
                                <div>
                                    <Table
                                        columns={this.columns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        scroll={{ y: store.getState().tableHeight.y - 18 }}
                                        style={{height: store.getState().tableHeight.y - 24}}
                                        rowKey={record => record.key}
                                        rowClassName={this.setRowClassName}
                                        onRow={(record) => {
                                            return {
                                                onClick: () => {
                                                    this.setState({detailsId: record.dispConfID});

                                                    if (this.state.rowId === '') {
                                                        // 保存行数据以及id
                                                        this.setState({rowId: record.dispConfID});
                                                        this.getListDate(record);
                                                    } else {
                                                        if (this.state.rowId !== record.dispConfID) {
                                                            this.setState({rowId: record.dispConfID});
                                                            this.getListDate(record);
                                                        } else {
                                                            this.setState({rowId: '',selected: [], detailsId: ''});
                                                            this.props.form.setFieldsValue({
                                                                ordLoc:'',
                                                                recLoc:'',
                                                                meditem:'',
                                                                usage: '',
                                                                type: ''
                                                            });
                                                        }
                                                    }
                                                },

                                            };
                                        }}
                                    />
                                    <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                                      onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.WaListData}
                                                      loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>

                </div>
            )
        }
    }
);
export default outpatientDispensing;
