/*
* 添加医嘱模板
* */

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 AddTemplateModal extends Component {

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

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

    componentDidMount() {
        this.loadLevelMsg()
    }

    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: 'ordTempletTypeDesc',
                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.ordTempletTypeID])) {
                //         obj.props.rowSpan = this.state.orderSpan[data.ordTempletTypeID];
                //         this.state.span[data.ordTempletTypeID] = 1;
                //     } else {
                //         obj.props.rowSpan = 0;
                //     }
                //     return obj;
                // },
            }, {
                title: this.setMessage('DoctorAdviceModalTemplateName', 'descripts'),
                dataIndex: 'ordTempletDesc',
                width: 250,
                align: 'center',
            }, {
                title: this.setMessage('DoctorAdviceModalAlias', 'descripts'),
                dataIndex: 'ordTempletAlias',
                width: 250,
                align: 'center',
            }, {
                title: this.setMessage('DoctorAdviceModalStatus', 'descripts'),
                dataIndex: 'ordTempletStatus',
                width: 170,
                align: 'center',
                render: (texr, data) => {
                    return <span>{data.ordTempletStatus == 'Y' ? this.setMessage('DoctorAdviceModalValid', 'descripts') :
                        (data.ordTempletStatus == 'N' ? this.setMessage('DoctorAdviceModalInvalid', 'descripts') : '')}</span>
                }
            },
        ]
    }

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

    loadData() {
        var params = {
            params: [{
                templetCatCode: '01',
                input: this.state.inputData,
                status: this.state.checkBox ? 'Y' : 'N'
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050056",
            data: params,
            success: function (res) {
                // let orderSpan = {};
                // res.result.Data.map(item => {
                //     orderSpan[item.ordTempletTypeID] = Util.isEmpty(orderSpan[item.ordTempletTypeID]) ? 1 : orderSpan[item.ordTempletTypeID] + 1;
                // });
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.Data,
                        // orderSpan: orderSpan
                    })
                }
            }
        });
    }

    loadLevelMsg() {
        var params = {
            params: [{
                orderTemplTypeFlag: "1",
            }],
        }
        $http.post('urlS', this, {
            code: '03050017',
            data: params,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        baseTempType: res.orderTemplType,
                    })
                }
            }
        })
    }

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

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

    //清空输入框
    cleanInput() {
        var date = new Date()
        this.setState({
            ordTempletID: undefined,
            ordTempletDesc: undefined,
            ordTempletTypeID: undefined,
            ordTempletAlias: undefined,
            ordTempletStartDate: moment(date).format(dayFormat),
            ordTempletStopDate: ''
        })
        this.props.form.resetFields();
    }

    changeRegistrTime(date, dateStr) {
        this.setState({
            admDateFrom: dateStr[0],
            admDateTo: dateStr[1]
        })
    }

    changeCheckBox(e) {
        this.setState({
            checkBox: e.target.checked
        }, () => {
            this.loadData()
        })
    }

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

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

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

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

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

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

    //提交
    onSubmit() {
        let { onSubmit } = this.props;
        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.ordTempletDesc)) {
                message.error(this.setMessage('DoctorAdviceModalentry', 'descripts'), this.state.userData && this.state.userData.messageTime)
                return
            }
            if (Util.isEmpty(this.state.ordTempletTypeID)) {
                message.error(this.setMessage('DoctorAdviceModalUsage', 'descripts'), this.state.userData && this.state.userData.messageTime)
                return
            }
            if (Util.isEmpty(this.state.ordTempletStartDate)) {
                message.error(this.setMessage('DoctorAdviceModalTime', 'descripts'), this.state.userData && this.state.userData.messageTime)
                return
            }
            params = {
                ordTempletID: '',
                ordTempletDesc: this.state.ordTempletDesc,
                ordTempletTypeID: this.state.ordTempletTypeID,
                ordTempletCatCode: "01",
                ordTempletAlias: this.state.ordTempletAlias,
                ordTempletStartDate: this.state.ordTempletStartDate ? moment(this.state.ordTempletStartDate).format(dayFormat) : '',
                ordTempletStopDate: this.state.ordTempletStopDate ? moment(this.state.ordTempletStopDate).format(dayFormat) : ''

            }
        } else {
            if (Util.isEmpty(this.state.ordTempletID)) {
                message.error('请先选择模板，再进行添加', this.state.userData && this.state.userData.messageTime)
                return
            }
            params = {
                ordTempletID: this.state.ordTempletID,
            }
        }

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

    render() {
        //使用级别
        var baseTempTypeOption = []
        this.state.baseTempType && this.state.baseTempType.map((item, index) => {
            baseTempTypeOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })
        return <div>
            <Modal className='template-modal'
                title={this.setMessage('DoctorAdviceModalAdd', 'descripts')}
                maskClosable={false}
                visible={this.props.isShow}
                okText={this.state.userData.language == 'EN' ? 'Submit' : '确定'}
                cancelText={this.state.userData.language == 'EN' ? 'Cancel' : '取消'}
                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('DoctorAdviceModalNew', 'descripts')}
                            <Card>
                                <Row gutter={15}>
                                    <span><span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                                        {this.setMessage('DoctorAdviceModaltemp', 'descripts')}
                                        <Input placeholder={this.setMessage('DoctorAdviceModalenter', 'descripts')} style={{ width: 180 }}
                                            value={this.state.ordTempletDesc}
                                            onBlur={this.loadAliasName.bind(this)}
                                            onKeyDown={this.onKeyDownAlias.bind(this)}
                                            onChange={Util.commonInputChange.bind(this, 'ordTempletDesc')} /></span>
                                    <span style={{ marginLeft: 10 }}>
                                        {this.setMessage('DoctorAdviceModalTempAlias', 'descripts')}
                                        <Input placeholder={this.setMessage('DoctorAdviceModalfif', 'descripts')} style={{ width: 180 }} maxLength={15}
                                            value={this.state.ordTempletAlias} ref={this.alias}
                                            onChange={Util.commonInputChange.bind(this, 'ordTempletAlias')} /></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.ordTempletTypeID}
                                            onChange={Util.handleSelectChange.bind(this, 'ordTempletTypeID')}>
                                            {baseTempTypeOption}
                                        </Select></span><br />
                                    <div style={{ marginTop: 5, display: 'flex' }}>
                                        <div><span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                                            {this.setMessage('DoctorAdviceModalEdate', 'descripts')}
                                            <DatePicker placeholder={this.setMessage('DoctorAdviceModalsdate', 'descripts')} style={{ width: 180 }}
                                                value={this.state.ordTempletStartDate ? moment(this.state.ordTempletStartDate, dayFormat) : ''}
                                                onChange={this.changeStartDate.bind(this, 'ordTempletStartDate')} /></div>
                                        <div style={{ marginLeft: 10 }}>
                                            {this.setMessage('DoctorAdviceModalexp', 'descripts')}
                                            <DatePicker placeholder={this.setMessage('DoctorAdviceModalsdate', 'descripts')}
                                                value={this.state.ordTempletStopDate ? moment(this.state.ordTempletStopDate, dayFormat) : ''}
                                                onChange={this.changeStartDate.bind(this, 'ordTempletStopDate')} style={{ width: 180 }} /></div>
                                    </div>
                                </Row>
                            </Card>
                        </Radio>
                        <Radio value={2}>{this.setMessage('DoctorAdviceModalath', '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.checkBox}
                                            onChange={this.changeCheckBox.bind(this)} />{this.setMessage('DoctorAdviceModalsv', 'descripts')}
                                    </div>
                                }}
                                rowKey={(data) => {
                                    return data.ordTempletID
                                }}
                                pagination={false}></Table>
                        </Radio>
                    </RadioGroup>


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

export default Form.create()(AddTemplateModal);