// 医嘱套餐
import React from 'react';
import {Modal, Form, Checkbox, Input, Row, Col, DatePicker, Table, Select, message, Pagination, Radio} from 'antd';
import Moment from 'moment';
import { $http } from 'containers/config/https';

let {Option} = Select;

class AddHeabSetMeal extends React.Component {
    constructor(props) {
        super(props);
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            visible: false,
            statusCheckbox: true, // 仅显示生效
            tableData: [], //表格数据
            name: undefined, // 名称/别名
            rowId: '',
            selectData: [],
            total: 0,
            page: 1,
            pageSize: 10,
            radioValue: 1,
            departmentInformation: [], // 科室下拉框数据
            orderSetDetailData: [],
            userData:userData
        };
        this.columns = [
            {
                title: '级别',
                dataIndex: 'cmOrderSetUserRangeDesc',
                key: '1',
                align: 'center',
                width: '100px',
            },
            {
                title: '名称',
                dataIndex: 'cmOrderSetDesc',
                width: '100px',
                align: 'center',
                key: '2',
            },
            {
                title: '别名',
                dataIndex: 'cmOrderSetAlias',
                width: '100px',
                align: 'center',
                key: '3',
            },
            {
                title: '状态',
                dataIndex: 'cmOrderSetStatus',
                width: '100px',
                align: 'center',
                key: '4',
                render(cmOrderSetStatus){
					let config = {
						'Y': '生效',
                        'N': '失效',
					}
					return config[cmOrderSetStatus];
                },
            }
        ]
    }

    componentDidMount() {
        this.props.onRef(this)
    }

    // 获取下拉框数据
    getSelectData = () => {
        let data = {
            params: [
                {
                    comPrincipleFlag: '1',
                    herbalFormFlag: '1',
                    frequenceFlag: '1',
                    usageFlag: '1',
                    durationFlag: '1',
                    authRangeFlag: '1',
                    usageExplainFlag: '1',
                    decoctMethodFlag: '1'
                }
            ]
        }
        $http.post('urlS', this, {
            code: "03050018",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({selectData: res})
                }
            }
        })
    }

    // 3.13.23.获取科室信息
	getDepartmentInformation = () => {
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let data = {
            params: [
                {
                    hospID: user.hospID,
                    type: 'D'
                }
            ]
        }
        $http.post('urlS', this, {
            code: "04020008",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ departmentInformation: res.result.Data})
                } else {
                    this.setState({ departmentInformation: [] })
                }
            }
        })
	}

    // 确认操作
    handleOk = () => {
        let {rowId, orderSetDetailData} = this.state;
        if (!(orderSetDetailData&&orderSetDetailData.length > 0)) {
            message.info("请先添加、引用或者点击处方列表查询处方明细",this.state.userData && this.state.userData.messageTime);
            // this.handleCancel();
            return;
        }
        let data = {
            params: []
        }
        let arr = orderSetDetailData ? JSON.parse(JSON.stringify(orderSetDetailData)).map(item => {
            return {
                cmOrderSetID: rowId ? rowId : '',
                cmOrderSetDetailID: '',
                cmOrderSetDetailMedItemID: item.medID, // 医嘱项id
                cmOrderSetDetailDoseQty: item.dose, // 
                cmOrderSetDetailDecoctMethodID: item.decoctMethodID, // 
                cmOrderSetDetailComPrincipleID: item.comPrincipleID, 
            }
        }) : [];
        if (rowId) {
            let compileObj = {};
            compileObj.cmOrderSetID = rowId;
            compileObj.detailData = arr&&arr.length > 0 ? arr : undefined;
            data.params.push(compileObj)
            $http.post('urlADS', this, {
                code: '03050025',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        // 成功提示
                        message.success("添加到历史套餐成功",this.state.userData && this.state.userData.messageTime);
                        this.handleCancel();
                        this.resetFields();
                    }
                }
            })
        } else {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    values.cmOrderSetID = '';
                    values.cmOrderSetStartDate = values.cmOrderSetStartDate ? Moment(values.cmOrderSetStartDate).format('YYYY-MM-DD') : undefined; // 生效日期
                    values.cmOrderSetStopDate = values.cmOrderSetStopDate ? Moment(values.cmOrderSetStopDate).format('YYYY-MM-DD') : undefined; // 失效日期
                    values.detailData = arr&&arr.length > 0 ? arr : undefined;
                    data.params.push(values)
                    $http.post('urlADS', this, {
                        code: '03050025',
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                // 成功提示
                                message.success("添加到新套餐成功");
                                this.handleCancel();
                                this.resetFields();
                            }
                        }
                    })
                }
            })
        }
    }

    // 打开弹窗
    showModal = (orderSetDetailData) => {
        this.setState({visible: true, orderSetDetailData}, () => {
            if (!(this.state.slelectData&&this.state.slelectData.length > 0)) {
                this.getSelectData();
            }
            if (!(this.state.departmentInformation&&this.state.departmentInformation.length > 0)) {
                this.getDepartmentInformation();
            }
            this.getTableData();
        })
    }

    // 关闭弹窗
    handleCancel = () => {
        this.setState({visible: false})
    }

    // 仅显示生效
    handleStatusCheckbox = (e) => {
        this.setState({statusCheckbox: e.target.checked}, () => {
            this.getTableData();
        })
    }

    // 模板名称/别名
    handleOnChangeName = (e) => {
        this.setState({name: e.target.value})
    }

    // 模板名称/别名回车查询
    nameOnPressEnter = () => {
        this.getTableData();
    }

    // 获取列表数据
    getTableData = () => {
        let {statusCheckbox, name} = this.state;
        let data = {
            params: [
                {
                    userSelf: 'N', // 个人标志
                    status: statusCheckbox ? 'Y' : 'N', // 生效标志
                    input: name, // 搜索框内容
                }
            ]
        }
        $http.post('urlS', this, {
            code: "03050024",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = [];
                    for(var i = 0; i < res.result.length; i++) {
                        arr.push(...res.result[i].data)
                    }
                    this.setState({tableData: arr, total: arr.length}, () => {
                        this.resetFields()
                    })
                }
            }
        })
    }

    // 操作行
    handleOnRow = (record) => {
        return {
            // 单击行选中
            onClick: () => {
                if (this.state.radioValue === 1) {
                    message.info("请切换为添加到历史套餐",this.state.userData && this.state.userData.messageTime)
                    return;
                }
                if (this.state.rowId === '') {
                    // 保存行数据以及ID
                    this.props.form.resetFields();
                    this.setState({rowId: record.cmOrderSetID, radioValue: 2})
                } else {
                    if (this.state.rowId !== record.cmOrderSetID) {
                            this.props.form.resetFields();
                            this.setState({rowId: record.cmOrderSetID, radioValue: 2})
                    } else {
                        this.setState({rowId: '', radioValue: 1})
                    }
                }
           }
       }
    }

    setRowClassName = (record) => {
        return record.cmOrderSetID === this.state.rowId ? 'clickRowStyle' : '';
    }

    // 重置表单
    resetFields() {
        this.setState({rowId: '', radioValue: 1});
        this.props.form.resetFields();
    }

    handlePaginationOnChange = (page, pageSize) => {
        this.setState({page, pageSize}, () => {
            this.getTableData()
        })
    }

    handlePaginationOnShowSizeChange = (page, pageSize) => {
        this.setState({page: 1, pageSize}, () => {
            this.getTableData()
        })
    }

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

    radioOnChange = (e) => {
        this.setState({
            radioValue: e.target.value,
        }, () => {
            if (e.target.value === 1) {
                this.setState({rowId: ''});
            } else {
                this.props.form.resetFields();
            }
        });
    }

    render() {
        let {visible, statusCheckbox, tableData, name, selectData, page, total, radioValue, departmentInformation} = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemInput  = {
            labelCol: {span: 8},
            wrapperCol: {span: 16}
        };

         // 剂型
         let herbalFormOption = selectData.herbalForm&&selectData.herbalForm.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })

        // 频次
        let frequenceOption = selectData.frequence&&selectData.frequence.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        
        // 用药方法
        let usageOption = selectData.usage&&selectData.usage.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })

        // 服用要求
        let usageExplainOption = selectData.usageExplain&&selectData.usageExplain.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })

        // 执行科室
        let departmentOption = departmentInformation&&departmentInformation.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })

        // 级别
        let authRangeOption = selectData.authRange&&selectData.authRange.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        return(
            <div>
                <Modal
                    title="添加套餐"
                    visible={visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    width={900}
                    className="add-modal"
                >
                    <div style={{height: '600px'}}>
                        <Radio.Group onChange={this.radioOnChange} value={radioValue} style={{width: '100%', height: '100%'}}>
                            <div>
                                <div className="radio-inner" style={{background: radioValue === 1 ? 'rgba(208, 233, 255, 1)' : 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', paddingLeft: '6px'}}>
                                    <Radio value={1}>添加到新套餐</Radio>
                                </div>
                                <Form style={{padding: '12px 12px 0 12px'}}>
                                    <Row>
                                        <Col span={6}>
                                            <Form.Item label="名称：" {...formItemInput} className="rules-position">
                                                {getFieldDecorator('cmOrderSetDesc', {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '名称不能为空' }]
                                                })(
                                                    <Input placeholder="请输入" disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="别名：" {...formItemInput}>
                                                {getFieldDecorator('cmOrderSetAlias', {
                                                    initialValue: undefined,
                                                })(
                                                    <Input placeholder="请输入" disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="使用级别：" {...formItemInput} className="rules-position">
                                                {getFieldDecorator('cmOrderSetUserRangeID', {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '使用级别不能为空' }]
                                                })(
                                                    <Select showSearch optionFilterProp="seatchprop" placeholder="请选择" disabled={radioValue === 2 ? true : false}>
                                                        {authRangeOption}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="执行科室" {...formItemInput}>
                                                {getFieldDecorator('cmOrderSetRecLocID', {
                                                    initialValue: undefined,
                                                })(
                                                    <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" disabled={radioValue === 2 ? true : false}>
                                                        {departmentOption}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={6}>
                                            <Form.Item label="生效日期：" {...formItemInput} className="rules-position">
                                                {getFieldDecorator('cmOrderSetStartDate', {
                                                    initialValue: Moment(),
                                                    rules: [{ required: true, message: '生效日期不能为空' }]
                                                })(
                                                    <DatePicker style={{width: '100%'}} format="YYYY-MM-DD" allowClear disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="失效日期：" {...formItemInput}>
                                                {getFieldDecorator('cmOrderSetStopDate', {
                                                    initialValue: undefined,
                                                })(
                                                    <DatePicker style={{width: '100%'}} format="YYYY-MM-DD" allowClear disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="用药副数" className="rules-position" {...formItemInput}>
                                                {getFieldDecorator('cmOrderSetDurQty', {
                                                    initialValue: undefined,
                                                    // rules: [{ required: true, message: '用药副数不能为空' }]
                                                    rules: [{ required: true, message: '用药副数不能为空' },{ pattern: /^[1-9]\d*$/, message: '用药副数只能为正整数, 如1、2、3、4' }]
                                                })(
                                                    <Input type="number" className="input-number" placeholder="请输入" disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="使用剂型" {...formItemInput}>
                                                {getFieldDecorator('cmOrderSetHerbalFormID', {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '使用剂型不能为空' }]
                                                })(
                                                    <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" disabled={radioValue === 2 ? true : false}>
                                                        {herbalFormOption}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={6}>
                                            <Form.Item label="使用频次" {...formItemInput}>
                                                {getFieldDecorator('cmOrderSetFreqID', {
                                                    initialValue: undefined,
                                                })(
                                                    <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" disabled={radioValue === 2 ? true : false}>
                                                        {frequenceOption}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="每次用量" {...formItemInput}>
                                                {getFieldDecorator('cmOrderSetDoseQty', {
                                                    initialValue: undefined,
                                                })(
                                                    <Input placeholder="请输入" disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="用药方法" {...formItemInput}>
                                                {getFieldDecorator('cmOrderSetUsageID', {
                                                    initialValue: undefined,
                                                })(
                                                    <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" disabled={radioValue === 2 ? true : false}>
                                                        {usageOption}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="服用要求" {...formItemInput}>
                                                {getFieldDecorator('cmOrderSetUsageExplainID', {
                                                    initialValue: undefined,
                                                })(
                                                    <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" disabled={radioValue === 2 ? true : false}>
                                                        {usageExplainOption}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row> 
                                    <Row>
                                        <Col span={6}>
                                            <Form.Item label="添加到模板：" {...formItemInput}>
                                                {getFieldDecorator('locTypeID', {
                                                    initialValue: undefined,
                                                })(
                                                    <Select showSearch optionFilterProp="seatchprop" placeholder="请选择" disabled={radioValue === 2 ? true : false}>
                                                        
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Form>
                            </div>
                            <div>
                                <div className="radio-inner" style={{background: radioValue === 2 ? 'rgba(208, 233, 255, 1)' : 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', paddingLeft: '6px'}}>
                                    <Radio value={2}>添加到历史套餐</Radio>
                                </div>
                                <div style={{padding: '12px'}}>
                                    <Input placeholder="输入模板名称/别名查询" style={{width: '70%', marginRight: '8px'}} value={name} onChange={this.handleOnChangeName} onPressEnter={this.nameOnPressEnter} />
                                    <Checkbox checked={statusCheckbox} onChange={this.handleStatusCheckbox}>仅显示生效</Checkbox>
                                    <div style={{marginTop: '12px'}}>
                                        <Table
                                            columns={this.columns}
                                            dataSource={tableData}
                                            bordered
                                            rowKey={(data) => {
                                                return data.cmOrderSetID
                                            }}
                                            pagination={false}
                                            onRow={this.handleOnRow}
                                            rowClassName={this.setRowClassName}
                                            scroll={{ y: 170 }}
                                        />
                                        <Pagination
                                            showTotal={() => this.showTotal(total)}
                                            size="small"
                                            showQuickJumper
                                            showSizeChanger
                                            current={page}
                                            total={total}
                                            onChange={this.handlePaginationOnChange}
                                            onShowSizeChange={this.handlePaginationOnShowSizeChange}
                                            style={{ textAlign: "right", marginTop: '13px' }}
                                        />
                                    </div>
                                </div>
                            </div>
                        </Radio.Group>
                    </div>
                </Modal>
            </div>
        )
    }
};
const AddHeabSetMealForm = Form.create()(AddHeabSetMeal);
export default AddHeabSetMealForm;
