/*
* 添加医嘱模版
* */

import React, { Component } from 'react';
import { Input, Form, Select, Modal, DatePicker, Radio, Table, Card, Row, Checkbox, message } 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 RadioGroup = Radio.Group;

class AddPackageModal extends Component {

    constructor(props) {
        super(props);
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var date = new Date()
        this.state = {
            dataSource: [],
            userData: userData,
            checked: 1,
            span: {},
            orderSpan: {},
            startDate:moment(date).format(dayFormat),
            activeFlag:'Y'
        }
        this.alias = React.createRef();
    }

    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {
            this.loadData()
            this.loadCommonModal()
        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }

    componentDidMount() {
        // this.initData()
        this.loadUseLevel()
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    loadCommonModal() {
        let data = {
            params: [{
                compontName: "DoctorAdviceModal",
                type: "C",
                reactCode: ['DoctorAdviceModal']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                    }, () => {
                        this.initData()
                    })
                }
            }
        })
    }

    initData() {
        this.columns = [
            {
                title: this.setMessage('DoctorAdviceModalLevel', 'descripts'),
                dataIndex: 'authRangeDesc',
                width: 180,
                align: 'center',
                render: (value, data, index) => {
                    if (index === 0) {
                        this.state.span = {};
                    }
                    const obj = {
                        children: value,
                        props: {}
                    }
                    if (Util.isEmpty(this.state.span[data.authRangeID])) {
                        obj.props.rowSpan = this.state.orderSpan[data.authRangeID];
                        this.state.span[data.authRangeID] = 1;
                    } else {
                        obj.props.rowSpan = 0;
                    }
                    return obj;
                },
            }, {
                title: this.setMessage('DoctorAdviceModalTemplateName', 'descripts'),
                dataIndex: 'ordSetDesc',
                width: 180,
                align: 'center',
            }, {
                title: this.setMessage('DoctorAdviceModalAlias', 'descripts'),
                dataIndex: 'ordSetAlias',
                width: 180,
                align: 'center',
            }, {
                title: this.setMessage('DoctorAdviceModaloperator', 'descripts'),
                dataIndex: 'userName',
                width: 120,
                align: 'center',
            }, {
                title: this.setMessage('DoctorAdviceModalStatus', 'descripts'),
                dataIndex: 'status',
                width: 120,
                align: 'center',
            }
        ]
    }

    //国际化
    setMessage(name, message) {
        return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : ''
    }

    loadData() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                locID: this.state.userData.locID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                activeFlag: this.state.activeFlag,
                selfFlag: this.state.activeFlag,
                searchCode: this.state.inputData,

            }]
        }
        $http.post('urlDeault', this, {
            code: "03050060",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    let orderSpan = {};
                    res.data.otherList.map(item => {
                        orderSpan[item.authRangeID] = Util.isEmpty(orderSpan[item.authRangeID]) ? 1 : orderSpan[item.authRangeID] + 1;
                    });
                    this.setState({
                        dataSource: res.data.otherList,
                        orderSpan: orderSpan
                    })
                }
            }
        });
    }

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

    //清空输入框
    cleanInput() {
        var date = new Date()
        this.props.form.resetFields();
        this.setState({
            descripts: undefined,
            alias: undefined,
            authRangeID: undefined,
            // startDate: '',
            stopDate: '',
            ordDose: undefined,
            startDate:moment(date).format(dayFormat)
        })
    }

    changeDate(name, e) {
        this.setState({
            [name]: e
        })
    }

    loadUseLevel() {
        var params = {
            params: [{}]
        }
        $http.post('urlDeault', this, {
            code: "03050073",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        levelData: res.data
                    })
                }
            }
        });
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    ordSetID: record.ordSetID,
                    record: record
                });
            },
            onDoubleClick: () => {
                this.onSubmit()
            }
        };
    }

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

    loadtableData(e) {
        if (e.keyCode == '13') {
            this.loadData(1)
        }
    }

    changeChecked(e) {
        this.setState({
            checked: e.target.value,
            ordSetID: undefined,
            record: ''
        })
    }

    changeCheckBox(name, e) {
        this.setState({
            [name]: e.target.checked ? 'Y' : 'N'
        }, () => {
            this.loadData()
        })
    }

    //输入别名enter
    onKeyDownAlias(e) {
        if (e.keyCode == '13') {
            if (Util.isEmpty(this.state.descripts)) {
                message.error('名称不能为空',this.state.userData && this.state.userData.messageTime)
                return
            }
            this.loadAliasName()
        }
    }

    loadAliasName() {
        var params = {
            params: [{
                descripts: this.state.descripts
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040117",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        alias: this.state.descripts + '_' + res.result
                    })
                    this.alias.current.focus()
                }
            }
        });
    }


    //提交
    onSubmit() {
        let { onSubmit } = this.props;
        var { record } = this.state;
        var params = {}
        if (Util.isEmpty(this.state.checked)) {
            message.error(this.setMessage('DoctorAdviceModalSelect', 'descripts'),this.state.userData && this.state.userData.messageTime)
            return
        }

        if (this.state.checked == 1) {
            if (Util.isEmpty(this.state.descripts)) {
                message.error(this.setMessage('DoctorAdviceModalUsage', 'descripts'),this.state.userData && this.state.userData.messageTime)
                return
            }
            if (Util.isEmpty(this.state.authRangeID)) {
                message.error(this.setMessage('DoctorAdviceModalUsage', 'descripts'),this.state.userData && this.state.userData.messageTime)
                return
            }
            if (Util.isEmpty(this.state.startDate)) {
                message.error(this.setMessage('DoctorAdviceModalTime', 'descripts'),this.state.userData && this.state.userData.messageTime)
                return
            }
            params = {
                userID: this.state.userData.userID,
                locID: this.state.userData.locID,
                hospID: this.state.userData.hospID,
                code: this.state.descripts,
                descripts: this.state.descripts,
                alias: this.state.alias,
                authRangeID: this.state.authRangeID,
                startDate: this.state.startDate ? moment(this.state.startDate).format(dayFormat) : '',
                stopDate: this.state.stopDate ? moment(this.state.stopDate).format(dayFormat) : '',
                ordDose: this.state.ordDose
            }
        } else {
            if(Util.isEmpty(this.state.ordSetID)){
                message.error('请先选择套餐，再进行添加',this.state.userData && this.state.userData.messageTime)
                return
            }
            params = {
                userID: this.state.userData.userID,
                locID: this.state.userData.locID,
                hospID: this.state.userData.hospID,
                code: record ? record.ordSetCode : '',
                descripts: record ? record.ordSetDesc : '',
                alias: record ? record.ordSetAlias : '',
                authRangeID: record ? record.authRangeID : '',
                startDate: record ? record.startDate : '',
                stopDate: record ? record.stopDate : '',
                ordSetID: this.state.ordSetID,
            }
        }

        onSubmit && onSubmit(params, this.state.checked, this.state.record);
    }

    render() {
        var baseTempTypeOption = []
        this.state.levelData && this.state.levelData.map((item, index) => {
            baseTempTypeOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        return <div>
            <Modal className='template-modal'
                title={this.setMessage('DoctorAdviceModalado', 'descripts')}
                maskClosable={false}
                okText={this.state.userData.language == 'EN' ? 'Submit' : '确定'}
                cancelText={this.state.userData.language == 'EN' ? 'Cancel' : '取消'}
                visible={this.props.isShow}
                onCancel={this.closeModal.bind(this)}
                onOk={this.onSubmit.bind(this)}>
                <div /** style={{ background: '#F1F1F1' }}*/>
                    <RadioGroup defaultValue={this.state.checked} onChange={this.changeChecked.bind(this)}>
                        <Radio value={1}>{this.setMessage('DoctorAdviceModalatn', 'descripts')}
                            <Card>
                                <Row gutter={15}>
                                    <span><span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                                        {this.setMessage('DoctorAdviceModalpn', 'descripts')}<Input placeholder={this.setMessage('DoctorAdviceModalenter', 'descripts')} style={{ width: 180 }}
                                            value={this.state.descripts} 
                                            onKeyDown={this.onKeyDownAlias.bind(this)}
                                            onBlur={this.loadAliasName.bind(this)}
                                            onChange={Util.commonInputChange.bind(this, 'descripts')} /></span>
                                    <span style={{ marginLeft: 10 }}>
                                        {this.setMessage('DoctorAdviceModalpa', 'descripts')}<Input placeholder={this.setMessage('DoctorAdviceModalfif', 'descripts')} style={{ width: 180 }} maxLength={15}
                                            value={this.state.alias}  ref={this.alias}
                                            onChange={Util.commonInputChange.bind(this, 'alias')} /></span>
                                    <span style={{ marginLeft: 10 }}><span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                                        {this.setMessage('DoctorAdviceModalUse', 'descripts')}
                                        <Select placeholder={this.setMessage('DoctorAdviceModalenter', 'descripts')} style={{ width: 180 }} value={this.state.authRangeID}
                                            onChange={Util.handleSelectChange.bind(this, 'authRangeID')}>
                                            {baseTempTypeOption}
                                        </Select></span><br />

                                    <div style={{ marginTop: 5, display: 'flex' }}>
                                        {/* <div>添加到模板：<Input placeholder='请输入要添加的模版' style={{ width: 180 }}
                                            value={this.state.ordDose}
                                            onChange={Util.commonInputChange.bind(this, 'ordDose')} /></div> */}
                                        <div><span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                                            {this.setMessage('DoctorAdviceModalEdate', 'descripts')}
                                            <DatePicker style={{ width: 180 }} format="YYYY-MM-DD"
                                                placeholder={this.setMessage('DoctorAdviceModalsdate', 'descripts')} value={this.state.startDate ? moment(this.state.startDate, dayFormat) : ''}
                                                onChange={this.changeDate.bind(this, 'startDate')} /></div>
                                        <div style={{ marginLeft: 10 }}>
                                            {this.setMessage('DoctorAdviceModalexp', 'descripts')}
                                            <DatePicker format="YYYY-MM-DD" placeholder={this.setMessage('DoctorAdviceModalsdate', 'descripts')}
                                                value={this.state.stopDate ? moment(this.state.stopDate, dayFormat) : ''}
                                                onChange={this.changeDate.bind(this, 'stopDate')} style={{ width: 180 }} /></div>
                                    </div>
                                </Row>
                            </Card>
                        </Radio>
                        <Radio value={2}>{this.setMessage('DoctorAdviceModalahp', 'descripts')}
                            <Table columns={this.columns}
                                dataSource={this.state.dataSource}
                                onRow={this.onClickRow}
                                rowClassName={this.setRowClassName}
                                scroll={{ y: 200 }}
                                bordered
                                title={() => {
                                    return <div>
                                        <Input placeholder={this.setMessage('DoctorAdviceModalnas', 'descripts')} style={{ width: 240 }}
                                            onKeyDown={this.loadtableData.bind(this)}
                                            onChange={Util.commonInputChange.bind(this, 'inputData')} />
                                        <Checkbox style={{ marginLeft: 10 }} checked={this.state.activeFlag == 'Y'?true:false}
                                            onChange={this.changeCheckBox.bind(this, 'activeFlag')} />{this.setMessage('DoctorAdviceModalsv', 'descripts')}
                                    </div>
                                }}
                                rowKey={(data) => {
                                    return data.ordTempletID
                                }}
                                pagination={false}></Table>
                        </Radio>
                    </RadioGroup>


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

export default Form.create()(AddPackageModal);