/**
 * 添加成套医嘱
 */
/*
* 引用模版
* */

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

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

class ShowCompleteMedicalModal extends Component {

    constructor(props) {
        super(props);
        var date = new Date();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var titleData = JSON.parse(sessionStorage.getItem('titleData'))
        this.state = {
            userData: userData,
            titleData: titleData,
            totalCount: 0,
            date: date,
            startDate: moment(date).format(dayFormat),
            coefficientData: [],
            categoryData: {}
        }
        this.alias = React.createRef();
    }

    componentDidMount() {
        this.loadUseLevel()
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        if (JSON.stringify(nextProps.coefficientData) !== JSON.stringify(prevState.coefficientData)) {
            return {
                coefficientData: nextProps.coefficientData
            }
        }
        if (JSON.stringify(nextProps.categoryData) !== JSON.stringify(prevState.categoryData)) {
            return {
                categoryData: nextProps.categoryData
            }
        }
        return null
    }

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

    closeModal() {
        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,
            ordDose: undefined,
            startDate: moment(date).format(dayFormat),
            stopDate: ''
        })
    }

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

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

    //输入别名enter
    onKeyDownAlias(e) {
        var obj = this.props.form.getFieldsValue()
        if (e.keyCode == '13') {
            if (Util.isEmpty(obj.descripts)) {
                message.error('名称不能为空')
                return
            }
            this.loadAliasName()
        }
    }

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

    //提交
    onSubmit() {
        let { validateFields } = this.props.form;
        validateFields({ force: true }, (err, params) => {
            if (err) {
                return
            }
            params.ordSetID = this.props.cpmpleteData ? this.props.cpmpleteData.ordSetID : ''
            let { onSubmit } = this.props;

            onSubmit && onSubmit(params);
        });
    }

    render() {
        const { coefficientData, categoryData } = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 15 },
        }
        var levelDataOption = []
        this.state.levelData && this.state.levelData.map((item, index) => {
            levelDataOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        });
        return (
            <div>
                <Modal
                    className="complete-modal"
                    title={!Util.isEmpty(this.props.cpmpleteData) ? '修改成套医嘱(西药及其他)' : '添加成套医嘱(西药及其他)'}
                    maskClosable={false}
                    visible={this.props.isShow}
                    onCancel={this.closeModal.bind(this)}
                    onOk={this.onSubmit.bind(this)}
                >
                    <div>
                        <Row gutter={40}>
                            <Col span={12}>
                                <FormItem  {...formItemLayout} label='名称'>
                                    {getFieldDecorator('descripts', {
                                        initialValue: this.state.descripts ? this.state.descripts :
                                            (Util.isEmpty(this.props.cpmpleteData) ? undefined : this.props.cpmpleteData.ordSetDesc),
                                        rules: [{ required: true, message: '名称不能为空' }],
                                    })(
                                        <Input placeholder='请输入名称，按回车键生成别名'
                                            onKeyDown={this.onKeyDownAlias.bind(this)}
                                            onChange={Util.commonInputChange.bind(this, 'descripts')} />
                                    )}
                                </FormItem>
                            </Col>

                            <Col span={12}>
                                <FormItem  {...formItemLayout} label='别名'>
                                    {getFieldDecorator('alias', {
                                        initialValue: this.state.alias ? (this.state.alias) :
                                            (Util.isEmpty(this.props.cpmpleteData) ? undefined : this.props.cpmpleteData.ordSetAlias),
                                    })(
                                        <Input placeholder='请输入别名' ref={this.alias}
                                            // value={this.state.alias}
                                            onChange={Util.commonInputChange.bind(this, 'alias')} />
                                    )}
                                </FormItem>
                            </Col>

                            <Col span={12}>
                                <FormItem  {...formItemLayout} label='使用级别'>
                                    {getFieldDecorator('authRangeID', {
                                        initialValue: this.state.authRangeID ? this.state.authRangeID :
                                            (Util.isEmpty(this.props.cpmpleteData) ? undefined : this.props.cpmpleteData.authRangeID),
                                        rules: [{ required: true, message: '使用级别不能为空' }],
                                    })(
                                        <Select style={{ width: '100%' }} onChange={Util.handleSelectChange.bind(this, 'authRangeID')}>
                                            {levelDataOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>

                            {categoryData?.interfaceType === 'finance' && ( // 仅财务使用的医嘱套餐优惠界面展示系数相关数据
                                <>
                                    <Col span={12}>
                                        <FormItem  {...formItemLayout} label="系数类型">
                                            {getFieldDecorator('coefficientType', {
                                                initialValue: Util.isEmpty(this.props.cpmpleteData) ? undefined : this.props.cpmpleteData.coefficientType,
                                            })(
                                                <Select placeholder="请选择" style={{ width: '100%' }} >
                                                    {React.$SelectOptions(coefficientData)}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={12}>
                                        <FormItem  {...formItemLayout} label="系数或金额">
                                            {getFieldDecorator('free', {
                                                initialValue: Util.isEmpty(this.props.cpmpleteData) ? undefined : this.props.cpmpleteData.free,
                                            })(
                                                <Input placeholder="请输入" style={{ width: '100%' }} />
                                            )}
                                        </FormItem>
                                    </Col>
                                </>
                            )}
                            {/* <Col span={12}>
                            <FormItem  {...formItemLayout} label='添加到模版'>
                                {getFieldDecorator('ordDose', {
                                    initialValue: this.state.ordDose,
                                })(
                                    <Input placeholder='请选择要添加的模版'
                                        onChange={Util.commonInputChange.bind(this, 'ordDose')} />
                                )}
                            </FormItem>
                        </Col> */}
                            <Col span={12}>
                                <FormItem  {...formItemLayout} label='生效日期'>
                                    {getFieldDecorator('startDate', {
                                        initialValue:
                                            (Util.isEmpty(this.props.cpmpleteData) ? moment(this.state.startDate, dayFormat) :
                                                moment(this.props.cpmpleteData.startDate, dayFormat)),
                                        rules: [{ required: true, message: '生效日期不能为空' }],
                                    })(
                                        <DatePicker
                                            format="YYYY-MM-DD"
                                            placeholder="请选择生效日期"
                                            style={{ width: '100%' }}
                                            onChange={this.changeDate.bind(this, 'startDate')}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem  {...formItemLayout} label='失效日期'>
                                    {getFieldDecorator('stopDate', {
                                        initialValue:
                                            (!Util.isEmpty(this.props.cpmpleteData && this.props.cpmpleteData.stopDate) ? moment(this.props.cpmpleteData.stopDate, dayFormat) : ''),
                                    })(
                                        <DatePicker
                                            format="YYYY-MM-DD"
                                            placeholder="请选择失效日期"
                                            style={{ width: '100%' }}
                                            onChange={this.changeDate.bind(this, 'stopDate')}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </div>
                </Modal>
            </div>
        )
    }
}

export default Form.create()(ShowCompleteMedicalModal);