// 医嘱权限设置
import React from 'react';
import { Select, Row, Col, Button, Tabs, Popconfirm, message, Icon, Form, DatePicker, Table } from 'antd';
import { $http } from '../../../containers/config/https';
import Moment from 'moment';
import DatePickerFormat from '../../../components/datePicker/DatePickerFormat';

// 组件const
const { Option } = Select;
const TabPane = Tabs.TabPane;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 4 },
    wrapperCol: { span: 19 },
};
const formItemLayout2 = {    // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
};



class MedicalOASetModal extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            dataGroupdocSon: [],  // 添加分组数据医嘱子类table
            dataGroupdocAd: [],  // 添加分组数据医嘱项table
            grouptitle: '--', // 弹框title分组名称
            docSonlData: [],  //医嘱子类下拉
            docAdlData: [],  // 医嘱项下拉
            searachDovcAd: undefined,
        }
        // 医嘱子类table
        this.columnsGroup = [{
            title: '子类名称',
            dataIndex: 'ordSubCatDesc',
            align: "center",
            key: '1',
        }, {
            title: '生效日期',
            dataIndex: 'medGroupItemStartDate',
            align: "center",
            key: '2',
        }, {
            title: '操作',
            key: '4',
            align: "center",
            width: 130,
            render: (text, record) => (
                <span>
                    <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                    <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record, 'son')} >
                        <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                    </Popconfirm>
                </span>
            ),
        }]

        // 医嘱项table
        this.columnsGroup2 = [{
            title: '项目代码',
            dataIndex: 'medCode',
            align: "center",
            key: '1',
        }, {
            title: '项目名称',
            dataIndex: 'medDesc',
            align: "center",
            key: '2',
        }, {
            title: '项目代码价格',
            dataIndex: 'medPrice',
            align: "center",
            key: '3',
        }, {
            title: '生效日期',
            dataIndex: 'medGroupItemStartDate',
            align: "center",
            key: '4',
        }, {
            title: '操作',
            key: '5',
            align: "center",
            width: 130,
            render: (text, record) => (
                <span>
                    <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                    <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record, 'ad')} >
                        <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                    </Popconfirm>
                </span>
            ),
        }]

    }

    componentDidMount() {
        if (this.props.membeOASetModalDate && JSON.stringify(this.props.membeOASetModalDate) !== "{}") {
            let data = this.props.membeOASetModalDate
            this.setState({
                grouptitle: data.medGrpDescripts, // 弹框title分组名称
            })

            // this.searachDovcAd() // 获取医嘱项信息
            this.searachList(data.medGroupID, 'C') // 获取医嘱信息列表
            this.searachList(data.medGroupID, 'I') // 获取医嘱信息列表

        }
    }


    // 实时更新
    componentWillReceiveProps(nextProps) {
        const { grouptitle } = this.state
        const newdata = nextProps.membeOASetModalDate

        if (JSON.stringify(newdata) === "{}") {
            this.props.form.resetFields(); // 清空表单
            return false
        }

        if (grouptitle !== newdata.medGrpDescripts) {
            this.setState({
                grouptitle: newdata.medGrpDescripts, // 弹框title分组名称
            })

            this.searachList(newdata.medGroupID, 'C') // 获取医嘱信息列表
            this.searachList(newdata.medGroupID, 'I') // 获取医嘱信息列表
        }

    }

    searachDovcAdchange = (e) => {
        console.log(e)
        this.setState({
            searachDovcAd: e
        })
    }

    // 获取医嘱项信息
    searachDovcAd = (e) => {

        var data = {
            params: [{
                hospID: this.props.membeOASetModalDate.hospID, // 医院id
                findCode: e.target.value
            }]
        }
        $http.post('urlS', this, {
            code: "01010002",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        docAdlData: res.result.Data, //  医院列表
                    })
                }
            }
        });
    }

    // 获取医嘱信息列表
    searachList = (id, value) => {
        var data = {
            params: [{
                medGroupID: id, // 科室人员分组主键
                itemFlag: value // 医嘱子类及医嘱项标志
            }]
        }
        $http.post('urlS', this, {
            code: "01040053",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    for (var i = 0; i < res.result.medItemAry.length; i++) {
                        res.result.medItemAry[i].key = i;
                    }

                    if (value === 'C') {
                        this.setState({
                            dataGroupdocSon: res.result.medItemAry, //  医嘱子类列表
                            docSonlData: res.result.CBOrderSubCatAry, //  医嘱子类select
                        })
                    }

                    if (value === 'I') {
                        this.setState({
                            dataGroupdocAd: res.result.medItemAry, //  医嘱项列表
                            docSonlData: res.result.CBOrderSubCatAry, //  医嘱子类select
                        })
                    }

                }
            }
        });
    }

    clearnSelect = () => {
        this.setState({
            docAdlData: [], //  医嘱项列表
        })
    }

    // 删除
    handleDelete = (record, str) => {
        let data = {
            "params": [{
                medGroupItemLogID: record.medGroupItemLogID,//人员分组可操作医嘱记录主键
                updateUserID: JSON.parse(window.sessionStorage.userData).userID || "",  //操作人

            }]
        };

        $http.post('urlADS', this, {
            code: "01040056",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success(res.errorMessage);
                    if (str === 'son') {
                        this.searachList(this.props.membeOASetModalDate.medGroupID, 'C') // 获取医嘱信息列表
                    }

                    if (str === 'ad') {
                        this.searachList(this.props.membeOASetModalDate.medGroupID, 'I') // 获取医嘱信息列表
                    }
                }
            }
        });
    }

    // 保存用户信息表单提交
    handleSubmit = (e, str) => {

        e.preventDefault();
        let data

        this.props.form.validateFields((err, values) => {
            if (str === 'son') {
                data = {
                    "params": [{
                        medGroupID: this.props.membeOASetModalDate.medGroupID || '',  //科室人员分组主键
                        medGroupItemLogID: '',  //人员分组可操作医嘱记录主键
                        medGroupItemStartDate: values.stimeSon ? Moment(values.stimeSon).utcOffset(480).format('YYYY-MM-DD') : '',    //生效日期
                        medGroupItemEndDate: values.etimeSon ? Moment(values.etimeSon).utcOffset(480).format('YYYY-MM-DD') : '',    //失效日期
                        ordSubCatID: values.docSonlData || '',  //医嘱子类主键
                        updateUserID: JSON.parse(window.sessionStorage.userData).userID || "",  //操作人

                    }]
                };
            }

            if (str === 'ad') {
                data = {
                    "params": [{
                        medGroupID: this.props.membeOASetModalDate.medGroupID || '',   //科室人员分组主键
                        medGroupItemLogID: '',  //人员分组可操作医嘱记录主键
                        medGroupItemStartDate: values.stimeAd ? Moment(values.stimeAd).utcOffset(480).format('YYYY-MM-DD') : '',    //生效日期
                        medGroupItemEndDate: values.etimeAd ? Moment(values.etimeAd).utcOffset(480).format('YYYY-MM-DD') : '',    //失效日期
                        medID: values.docAdlData || '',  //医嘱项主键
                        updateUserID: JSON.parse(window.sessionStorage.userData).userID || "",  //操作人
                    }]
                };
            }


            $http.post('urlADS', this, {
                code: "01040055",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        message.success(res.errorMessage);
                        if (str === 'son') {
                            this.searachList(this.props.membeOASetModalDate.medGroupID, 'C') // 获取医嘱信息列表
                        }

                        if (str === 'ad') {
                            this.searachList(this.props.membeOASetModalDate.medGroupID, 'I') // 获取医嘱信息列表
                        }


                    }
                }
            });
        })


    }

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form layout="vertical" className="depart-form " >
                <Row >
                    <Col span={24} >
                        <h4>分组名称:{this.state.grouptitle}</h4>
                    </Col>
                </Row>
                <Tabs defaultActiveKey="1" >
                    <TabPane tab="医嘱子类" key="1">
                        <Row className='mT30'>
                            <Col span={12} className="dpW100">
                                <Form.Item label="生效日期："  {...formItemLayout2}  >
                                    {getFieldDecorator('stimeSon', {
                                        initialValue: Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                        rules: [{ required: true, message: '请选择生效日期：' }],
                                    })(
                                        <DatePickerFormat />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={12} className="dpW100">
                                <Form.Item label="失效日期："   {...formItemLayout2}  >
                                    {getFieldDecorator('etimeSon', {
                                        initialValue: undefined,
                                        rules: [],
                                    })(
                                        <DatePickerFormat />
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row >
                            <Col span={24} >
                                <Form.Item label="医嘱子类："  {...formItemLayout} >
                                    {getFieldDecorator('docSonlData', {
                                        initialValue: '',
                                        rules: [{ required: true, message: '请选择医嘱子类' }],
                                    })(
                                        <Select allowClear showSearch filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} placeholder="输入内容回车查询">
                                            {this.state.docSonlData.map(item => <Option title={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                                        </Select>
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row >
                            <Col span={24}>
                                <Row style={{ width: '100%', textAlign: 'center', marginBottom: '10px' }}>
                                    <Button onClick={(event) => { this.handleSubmit(event, 'son') }} style={{ marginRight: '15px', background: 'rgba(66,185,131,1)', color: '#fff' }}>保存</Button>
                                </Row>
                            </Col>

                        </Row>
                        <Row className="mT30">
                            <Col span={24} >
                                <Table bordered dataSource={this.state.dataGroupdocSon} columns={this.columnsGroup} pagination={false} style={{ height: '300px', overflow: 'auto' }} />
                            </Col>
                        </Row>
                    </TabPane>
                    <TabPane tab="医嘱项" key="2">
                        <Row className='mT30'>
                            <Col span={12} className="dpW100">
                                <Form.Item label="生效日期："  {...formItemLayout2}  >
                                    {getFieldDecorator('stimeAd', {
                                        initialValue: Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                        rules: [{ required: true, message: '请选择生效日期' }],
                                    })(
                                        <DatePickerFormat />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={12} className="dpW100">
                                <Form.Item label="失效日期："   {...formItemLayout2}  >
                                    {getFieldDecorator('etimeAd', {
                                        initialValue: undefined,
                                        rules: [],
                                    })(
                                        <DatePickerFormat />
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>

                        <Row>
                            <Col span={24} >
                                <Form.Item label="医嘱项："  {...formItemLayout} >
                                    {getFieldDecorator('docAdlData', {
                                        initialValue: '',
                                        rules: [{ required: true, message: '请选择医嘱项' }],
                                    })(
                                        <Select allowClear showSearch optionFilterProp="title" onInputKeyDown={(event) => { if (event.keyCode == 13) { this.searachDovcAd(event) } }} placeholder="输入内容回车查询" onFocus={(event) => { this.clearnSelect(event) }}  >
                                            {this.state.docAdlData.map(item => <Option title={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                                        </Select>

                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row >
                            <Col span={24}>
                                <Row style={{ width: '100%', textAlign: 'center', marginBottom: '10px' }}>
                                    <Button onClick={(event) => { this.handleSubmit(event, 'ad') }} style={{ marginRight: '15px', background: 'rgba(66,185,131,1)', color: '#fff' }}>保存</Button>
                                </Row>
                            </Col>

                        </Row>
                        <Row className="mB30">
                            <Col span={24} >
                                <Table bordered dataSource={this.state.dataGroupdocAd} columns={this.columnsGroup2} pagination={false} style={{ height: '300px', overflow: 'auto' }} />
                            </Col>
                        </Row>
                    </TabPane>

                </Tabs>


            </Form>
        )
    }
}

const MedicalOASetModalFrom = Form.create()(MedicalOASetModal);

export default MedicalOASetModalFrom