/*
* 自备药
* */

import React, { Component } from 'react';
import { Input, Form, Select, Modal, Button, Table, message, Card, Row, Col } from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import '../style/index.less';
import moment from 'moment';

const Option = Select.Option;
const FormItem = Form.Item;

class BringMedicineModal extends Component {

    constructor(props) {
        super(props);
        var date = new Date();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var patientData = JSON.parse(sessionStorage.getItem('patientData'))
        var newDate = date.setMonth(date.getMonth() - 1);
        this.state = {
            leftData: [],
            rightData: [],
            userData: userData,
            patientData: patientData,
            total: 0,
            page: 1,
            pageSize: 10,
            codePage: 1,
            ids: [],
            totalCount: 0,
            date: date,
            admDateFrom: moment(newDate).format(dayFormat),
        }
    }
    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {
            this.initData();
            this.loadData();
            this.loadSelectData()
        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }

    componentDidMount() {
    }

    initData() {
        this.columns = [
            {
                title: '序号',
                dataIndex: 'admDate',
                width: 50,
                align: 'center',
                render: (text, data, index) => <span style={{ width: 50 }}>{index + 1}</span>
            }, {
                title: '科室',
                dataIndex: 'descripts',
                width: 120,
                align: 'center',
            }, {
                title: '状态',
                dataIndex: 'status',
                width: 120,
                align: 'center',
            },
        ]
    }

    loadSelectData() {
        var params = {
            params: [{
                logonHospID: this.state.userData.hospID,
                logonGroupID: this.state.userData.groupID,
                subCatFlag: 'Y',
                hospFlag: 'Y',
                priorityFlag: 'Y',
                unitFlag: 'Y',
                freFlag: 'Y',
                usageFlag: 'Y',
                durationFlag: 'Y',
                sexFlag: 'Y'
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010037",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        subCat: res.result.subCat,
                        hosp: res.result.hosp,
                        priority: res.result.priority,
                        unit: res.result.unit,
                        fre: res.result.fre,
                        usage: res.result.usage,
                        duration: res.result.duration,
                        sex: res.result.sex,
                    })
                }
            }
        });
    }

    loadData() {
        var params = {
            params: [{
                amdID: this.state.patientData ? this.state.patientData.admID : '',
            }]
        }
        $http.post('urlDeault', this, {
            code: "03060015",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data
                    })
                }
            }
        });
    }

    closeModal(name) {
        let { onHide } = this.props;
        onHide && onHide();
        this.cleanInput();
    }

    //清空输入框
    cleanInput() {
        this.props.form.resetFields();
        this.setState({
            detailData:{}
        })
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                if(!Util.isEmpty(record.medID)){
                    message.error('已审核的自备药不能修改！',this.state.userData && this.state.userData.messageTime)
                    return
                }
                this.setState({
                    admID: record.id,
                    detailData: record
                });
            }
        };
    }

    onSelectChange(ids,data) {
        var params = []
        var newCode = []
        for(var i=0;i<data.length;i++){
            params.push({
               medID:data[i].medID,
               ordSetID:''
            })
            newCode.push(data[i].medID)
        }
        var code = {
            params:[{
                admID: (this.state.patientData ? this.state.patientData.admID : ''),
                orders:params
            }]
        }
        this.setState({
            ids,
            data:code,
            newCode:newCode
        })
    }

    //点击行，渲染当前行样式 
    setRowClassName = (record) => {
        return record.id === this.state.admID ? 'clickRowStyle' : '';
    }

    saveMechicine() {
        let { validateFields } = this.props.form;
        validateFields({ force: true }, (err, params) => {
            if (err) {
                return;
            }
            params['userID'] = this.state.userData.userID
            params['admID'] = this.state.patientData ? this.state.patientData.admID : ''
            params['descripts'] = params.mecDescripts
            params['id'] = this.state.detailData ? this.state.detailData.id : ''
            var data = {
                params: [params]
            }
            $http.post('urlDeault', this, {
                code: "03060014",
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        message.success('保存成功！',this.state.userData && this.state.userData.messageTime)
                        this.loadData()
                        this.cleanInput()
                    }
                }
            });
        });
    }
    //提交
    onSubmit() {
        let { onSubmit } = this.props;
        onSubmit && onSubmit(this.state.data,this.state.newCode);
    }

    render() {
        var { subCat, priority, unit, fre, usage, duration, sex, ids } = this.state;
        let { getFieldDecorator } = this.props.form;
        const rowSelection = {
            ids,
            onChange: this.onSelectChange.bind(this),
            selectedRowKeys: ids,
            getCheckboxProps: record => ({
                disabled: Util.isEmpty(record.medID)?true:false, 
              }),
        }
        let formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 15 }
        };

        let formItemSexLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 15 }
        };

        let searchColConfig = {
            xs: { span: 24 },
            sm: { span: 12 },
            md: { span: 8 },
            lg: { span: 10 }
        }
        var date = new Date()

        //医嘱子类
        var subCatOption = [];
        subCat && subCat.map((item, index) => {
            subCatOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //医嘱优先级
        var priorityOption = []
        priority && priority.map((item, index) => {
            priorityOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //计价单位
        var unitOption = []
        unit && unit.map((item, index) => {
            unitOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //频次
        var freOption = []
        fre && fre.map((item, index) => {
            freOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //用法
        var usageOption = []
        usage && usage.map((item, index) => {
            usageOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //疗程
        var durationOption = []
        duration && duration.map((item, index) => {
            durationOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //性别
        var sexOption = []
        sex && sex.map((item, index) => {
            sexOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        return <div>
            <Modal className='bring-medicine-body'
                title={'自备药'}
                maskClosable={false}
                visible={this.props.isShow}
                onCancel={this.closeModal.bind(this)}
                // footer={null}
                onOk={this.onSubmit.bind(this)}
                >
                <div>
                    <div style={{ width: '25%', float: 'left' }}>
                        {/* <Button size='small' type='primary' onClick={this.addBringMedicine.bind(this)}>添加</Button> */}
                        <Table columns={this.columns} style={{ marginTop: 5 }}
                            dataSource={this.state.dataSource}
                            rowSelection={rowSelection}
                            scroll={{ y: '35vh' }}
                            rowKey={(data) => {
                                return data.id
                            }}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassName}
                            pagination={false}></Table>
                    </div>

                    <div style={{ width: '74%', float: 'right' }}>
                        <Card title={<span >自备药申请</span>}>
                            <Form>
                                <Row gutter={20}>
                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="医嘱子类">
                                            {getFieldDecorator('subCatID', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.subCatID,
                                                rules: [{ required: true, message: '医嘱子类不能为空' }],
                                            })(
                                                <Select placeholder="请选择医嘱子类"
                                                    filterOption={(input, option) =>
                                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                        || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    }
                                                    allowClear showSearch
                                                    getPopupContainer={triggerNode => triggerNode.parentNode}>
                                                    {subCatOption}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="医嘱代码">
                                            {getFieldDecorator('code', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.code,
                                                rules: [{ required: true, message: '医嘱代码不能为空' }],
                                            })(
                                                <Input placeholder='请输入医嘱代码' disabled={Util.isEmpty(this.state.detailData) ? false : true} />
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="医嘱描述">
                                            {getFieldDecorator('mecDescripts', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.descripts,
                                                rules: [{ required: true, message: '医嘱描述不能为空' }],
                                            })(
                                                <Input placeholder='请输入医嘱描述' disabled={Util.isEmpty(this.state.detailData) ? false : true}/>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="计价单位">
                                            {getFieldDecorator('unitID', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.unitID,
                                                rules: [{ required: true, message: '计价单位不能为空' }],
                                            })(
                                                <Select placeholder='请选择计价单位' filterOption={(input, option) =>
                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }

                                                    allowClear showSearch>
                                                    {unitOption}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemSexLayout} label="频次">
                                            {getFieldDecorator('freqID', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.freqID,
                                            })(
                                                <Select placeholder='请选择频次' filterOption={(input, option) =>
                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                                    allowClear showSearch>
                                                    {freOption}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemSexLayout} label="用法">
                                            {getFieldDecorator('usageID', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.usageID,
                                            })(
                                                <Select placeholder='请选择用法' filterOption={(input, option) =>
                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                                    allowClear showSearch>
                                                    {usageOption}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemSexLayout} label="疗程数">
                                            {getFieldDecorator('durQty', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.durQty,
                                            })(
                                                <Input placeholder='请输入疗程数' />
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="疗程单位">
                                            {getFieldDecorator('durationID', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.durationID,
                                            })(
                                                <Select placeholder='请选择疗程单位' filterOption={(input, option) =>
                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                                    allowClear showSearch>
                                                    {durationOption}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="剂量规格">
                                            {getFieldDecorator('spec', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.spec,
                                                rules: [{ required: true, message: '剂量规格不能为空' }],
                                            })(
                                                <Input placeholder='请输入剂量规格' />
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="等效数量">
                                            {getFieldDecorator('doseQty', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.doseQty,
                                                rules: [{ required: true, message: '等效数量不能为空' }],
                                            })(
                                                <Input placeholder='请输入等效数量' />
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="等效单位">
                                            {getFieldDecorator('doseUnitID', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.doseUnitID,
                                                rules: [{ required: true, message: '等效单位不能为空' }],
                                            })(
                                                (
                                                    <Select placeholder='请选择等效单位' filterOption={(input, option) =>
                                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                        || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    }

                                                        allowClear showSearch>
                                                        {unitOption}
                                                    </Select>
                                                )
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="默认数量">
                                            {getFieldDecorator('dose', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.dose,
                                            })(
                                                <Input placeholder='请输入默认数量' />
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col {...searchColConfig}>
                                        <FormItem {...formItemLayout} label="药品批号">
                                            {getFieldDecorator('drugBatchNo', {
                                                initialValue: Util.isEmpty(this.state.detailData) ? undefined : this.state.detailData.drugBatchNo,
                                            })(
                                                <Input placeholder='请输入药品批号' />
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <div style={{ display: 'flex', textAlign: 'center', marginLeft: '40%' }}>
                                    <Button style={{ marginLeft: 20 }} onClick={this.cleanInput.bind(this)}>清空</Button>
                                    <Button type='primary' style={{ marginLeft: 10 }} onClick={this.saveMechicine.bind(this)}>保存</Button>
                                </div>
                            </Form>
                        </Card>
                    </div>

                </div>
            </Modal></div>
    }
}

export default Form.create()(BringMedicineModal);