// 添加草药模板
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 AddHeabTemplate 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,
            orderSetDetailData: [],
            radioValue: 1,
            userData:userData
        };
        this.columns = [
            {
                title: '级别',
                dataIndex: 'ordTempletTypeDesc',
                key: '1',
                align: 'center',
                width: '100px',
            },
            {
                title: '名称',
                dataIndex: 'ordTempletDesc',
                width: '100px',
                align: 'center',
                key: '2',
            },
            {
                title: '别名',
                dataIndex: 'ordTempletAlias',
                width: '100px',
                align: 'center',
                key: '3',
            },
            {
                title: '状态',
                dataIndex: 'ordTempletStatus',
                width: '100px',
                align: 'center',
                key: '4',
                render(ordTempletStatus){
					let config = {
						'Y': '生效',
                        'N': '失效',
					}
					return config[ordTempletStatus];
                },
            }
        ]
    }

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

    // 获取下拉框数据
    getSelectData = () => {
        let data = {
            params: [
                {
                    orderTemplTypeFlag: '1'
                }
            ]
        }
        $http.post('urlS', this, {
            code: "03050017",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({selectData: res.orderTemplType})
                }
            }
        })
    }

    // 确认操作
    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 ? orderSetDetailData.map(item=> {
            return {
                ordTempletID: rowId ? rowId : '', // 医嘱模板id
                ordTempletDetailID: '', // 医嘱模板明细id
                ordTempletDetailSeqNo: item.cmOrderSetDetailSeqNo ? item.cmOrderSetDetailSeqNo : '', // 序号
                ordTempletDetailTemplItemTypeCode: "01", // 模板明细类型Code
                ordTempletDetailItemID: item.medID ? item.medID : '', // 名称ID
                ordTempletDetailQty: item.dose ? item.dose : '', // 剂量
                ordTempletDetailQtyUnitDr: item.doseUnitID ? item.doseUnitID : '', // 剂量单位
            }
        }) : [];
        if (rowId) {
            let compileObj = {}
            compileObj.ordTempletID = rowId
            compileObj.detailData = arr;
            data.params.push(compileObj);
            $http.post('urlADS', this, {
                code: '03050012',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        // 成功提示
                        message.success("添加到历史模板成功",this.state.userData && this.state.userData.messageTime)
                        this.resetFields();
                        this.handleCancel();
                    }
                }
            })
        } else {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    let obj = JSON.parse(JSON.stringify(values))
                    obj.ordTempletStartDate = obj.ordTempletStartDate ? Moment(obj.ordTempletStartDate).format("YYYY-MM-DD") : '';
                    obj.ordTempletStopDate = obj.ordTempletStopDate ? Moment(obj.ordTempletStopDate).format("YYYY-MM-DD") : '';
                    obj.ordTempletCatID = '';
                    obj.ordTempletCatCode = '02';
                    obj.detailData = arr;
                    data.params.push(obj);
                    $http.post('urlADS', this, {
                        code: '03050012',
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                // 成功提示
                                message.success("添加新模板成功",this.state.userData && this.state.userData.messageTime);
                                this.resetFields();
                                this.handleCancel();
                            }
                        }
                    })
                }
            })
        }
    }

    // 打开弹窗
    showModal = (orderSetDetailData) => {
        this.setState({visible: true, orderSetDetailData}, () => {
            if (!(this.state.slelectData&&this.state.slelectData.length > 0)) {
                this.getSelectData();
            }
            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, pageSize, page} = this.state;
        let data = {
            params: [{
                templetCatCode: '02',
                status: statusCheckbox ? 'Y' : 'N',
                input: name,
            }],
            pagination:[{
                pageSize,
                currentPage: page
            }]
        }
        $http.post('urlS', this, {
            code: '03050056',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.Data ? res.result.Data : [];
                    for (var i = 0; i < arr.length; i++) {
                        arr[i].key = i + 1
                    }
                    this.setState({tableData: arr, total: res.result.TotalCount}, () => {
                        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.ordTempletID})
                } else {
                    if (this.state.rowId !== record.ordTempletID) {
                            this.props.form.resetFields();
                            this.setState({rowId: record.ordTempletID})
                    } else {
                            this.setState({rowId: ''})
                    }
                }
           }
       }
    }

    setRowClassName = (record) => {
        return record.ordTempletID === 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} = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemInput  = {
            labelCol: {span: 8},
            wrapperCol: {span: 16}
        };

        // 级别
        let authRangeOption = selectData&&selectData.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={800}
                    className="add-modal"
                >
                    <div style={{height: '500px'}}>
                        <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={8}>
                                            <Form.Item label="名称：" {...formItemInput} className="rules-position">
                                                {getFieldDecorator('ordTempletDesc', {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '名称不能为空' }]
                                                })(
                                                    <Input placeholder="请输入" disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="模板别名：" {...formItemInput}>
                                                {getFieldDecorator('ordTempletAlias', {
                                                    initialValue: undefined,
                                                })(
                                                    <Input placeholder="请输入" disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="使用级别：" {...formItemInput} className="rules-position">
                                                {getFieldDecorator('ordTempletTypeID', {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '使用级别不能为空' }]
                                                })(
                                                    <Select showSearch optionFilterProp="seatchprop" placeholder="请选择" disabled={radioValue === 2 ? true : false}>
                                                        {authRangeOption}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={8}>
                                            <Form.Item label="生效日期：" {...formItemInput} className="rules-position">
                                                {getFieldDecorator('ordTempletStartDate', {
                                                    initialValue: Moment(),
                                                    rules: [{ required: true, message: '生效日期不能为空' }]
                                                })(
                                                    <DatePicker placeholder="请输入" allowClear={false} disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="失效日期：" {...formItemInput}>
                                                {getFieldDecorator('ordTempletStopDate', {
                                                    initialValue: undefined,
                                                })(
                                                    <DatePicker placeholder="请输入" disabled={radioValue === 2 ? true : false} />
                                                )}
                                            </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
                                            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 AddHeabTemplateForm = Form.create()(AddHeabTemplate);
export default AddHeabTemplateForm;
