//等效单位维护
import React from 'react';
import {
    Form,Row,Input,Col,Button,Select,Card,Table,Pagination,message
} from 'antd';
import '../../../assets/css/App.css'
import { $http } from '../../../containers/config/https';
const FormItem = Form.Item;
const Option = Select.Option;

const FormHandel = Form.create()(
    class extends React.Component {
        constructor(props) {
            super(props)
            this.state = { 
                doseUom:'',
                doseQty:'',
                defaultQty:'',
                uomData:[],
                total: 0,
                page: 1,
                pageSize: 10,
                selectKey:'',
                findFlag:'0',
            }

            this.columns = [
                {
                    key: 'doseUom',
                    title: '等效单位',
                    dataIndex: 'doseUom',
                    width: "33%",
                    align: 'center'
                },{
                    key: 'doseQty',
                    title: '等效数量',
                    dataIndex: 'doseQty',
                    width: "33%",
                    align: 'center'
                },{
                    key: 'defaultQty',
                    title: '默认数量',
                    dataIndex: 'defaultQty',
                    width: "33%",
                    align: 'center'
                }];
        }

        componentDidMount() {
            this.props.onRef(this);
            this.loadInfo(); //获取下拉框信息
        }

        //获取下拉框信息
        loadInfo(){
            var params = [{}]
            $http.post('urlS', this, {
                code: "02020013",
                data: params,
                success: function (res) {
                    if (res.errorCode === '0') {
                        var j=0
                        for(j = 0; j < res.uom.length; j++) {
                            this.state.uomData.push(<Option value={res.uom[j].id} key={j}>{res.uom[j].descripts}</Option>)
                        }
                    }
                }
            });
        }

        //处理多个input的公共方法
        onChangeInput(name, e){
            this.setState({
                [name]: e.target.value
            })
        }

        ///处理多个select下拉的公共方法
        selectOnChange=(name,value,option)=>{
            if(value){
                this.setState({
                    [name]:value,
                })
            }else{
                this.setState({
                    [name]:'',
                })
            }
        }
        // 查询
        handleQuery = () => {
            if((parseInt(this.state.medItemID)>0)||(parseInt(this.state.saveAsMedID)>0)){
                let data = {}
                data={
                    params: [{
                        medID: this.state.medItemID ? this.state.medItemID : this.state.saveAsMedID ,
                    }],
                    pagination:[{
                        pageSize: this.state.pageSize,
                        currentPage: this.state.page,
                        sort: "ID",
                        dir: "desc"
                    }]
                }
                $http.post('urlS', this, {
                    code: "02020015",
                    data: data,
                    success: function (res) {
                        if (res.errorCode === '0') {
                            for(var i = 0; i < res.result.rows.length; i++) {
                                res.result.rows[i].key = i + 1;
                            }
                            this.setState({
                                data: res.result.rows, 
                                total: res.result.total,
                                selectKey: '',
                                selectID: '',
                                doseUom:'',
                                doseQty:'',
                                defaultQty:'',
                            })
                            this.props.form.resetFields();
                        }
                    }
                });
            }else{

            }
        }

        // 保存
        handleSave = () => {
            if(this.state.doseUom===""){
                message.warning('等效单位不能为空!!');
                return;
            }
            if(Number(this.state.doseQty)===0){
                message.warning('等效数量不能为0!!');
                return;
            }
            if(parseInt(this.state.medItemID)>0){
                let data = {}
                data={
                    params: [{
                        medID: this.state.medItemID,
                        ID: this.state.selectID,
                        doseUom: this.state.doseUom,
                        doseQty: this.state.doseQty,
                        defaultQty: this.state.defaultQty,
                    }],
                }
                $http.post('urlS', this, {
                    code: "02020014",
                    data: data,
                    success: function (res) {
                        if (res.errorCode === '0') {
                            message.success('保存成功');
                            this.handleQuery();
                        }
                    }
                });
            }else{
                let obj= {
                    key:0,
                    ID: "",
                    defaultQty: this.state.defaultQty,
                    doseQty: this.state.doseQty,
                    doseUom: "",
                    doseUomDr: this.state.doseUom,
                }
                for (var i = 0; i < this.state.uomData.length; i++) {
                    if (this.state.uomData[i].props.value === this.state.doseUom) {
                        obj.doseUom = this.state.uomData[i].props.children;
                        break;
                    }
                }
                let arr=this.state.data;
                let total = this.state.total ;
                if (this.state.selectKey) {
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i].key === this.state.selectKey) {
                            obj.key = arr[i].key ;
                            arr[i] = obj ;
                        }
                    }
                }else {
                    total = total + 1;
                    obj.key = total;
                    arr.push(obj);
                }
                this.setState({
                    data:arr,
                    total:total,
                    findFlag:'1',
                },() =>{
                    this.Clear();
                })
                // message.warning('请先保存医嘱项信息!');
                // return;
            }
        }

        //删除
        handleDelete = ()=>{
            if ((parseInt(this.state.selectID)>0)&&(parseInt(this.state.medItemID)>0)){
                let data = {}
                data={
                    params: [{
                        ID: this.state.selectID,
                        userDr:1,
                        hospDr:1,
                    }],
                }
                $http.post('urlS', this, {
                    code: "02020016",
                    data: data,
                    success: function (res) {
                        if (res.errorCode === '0') {
                            message.success('删除成功');
                            this.handleQuery();
                        }
                    }
                });
            }else if (this.state.selectKey>0){
                let arrData = [];
                let arr=this.state.data;
                let total = this.state.total - 1;
                let count = 0;
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i].key != this.state.selectKey) {
                        count++;
                        arr[i].key = count;
                        arrData.push(arr[i]);
                    }
                }
                this.setState({
                    data:arrData,
                    total:total,
                    findFlag:'1',
                },() =>{
                    this.Clear();
                })
            }else{
                message.warning('请先选择记录再删除信息!');
                return;
            }
        }
        
        // 清空
        Clear = () => {
            this.setState({
                selectKey:'',
                selectID: '',
                doseUom:'',
                doseQty:'',
                defaultQty:'',
            })
            this.props.form.resetFields();
        }
        // 页码改变的回调，参数是改变后的页码及每页条数
        PageChange = (page, pageSize)=> {
            this.setState({page: page, pageSize: pageSize}, () => {
                // 重新调用查询方法
                this.handleQuery();
            });
        }

        // 条数改变的回调
        onShowSizeChange = (current, size) => {
        this.setState({page: current, pageSize: size}, () => {
                // 重新调用查询方法
                this.handleQuery();
            });
        }

        setRowClassName = (record) => {
            return record.key === this.state.selectKey ? 'clickRowStyle' : '';
            // return record.ID === this.state.selectID ? 'clickRowStyle' : '';
        }
    
        onClickRow = (record) => {
            return {
                onClick: () => {
                    this.Clear();
                    if(this.state.selectKey===""){
                        this.setState({
                            selectKey: record.key,
                            selectID: record.ID,
                            doseUom:record.doseUomDr,
                            doseQty:record.doseQty,
                            defaultQty:record.defaultQty,
                        });
                    }else{
                        if(this.state.selectKey!==record.key){
                            this.setState({
                                selectKey: record.key,
                                selectID: record.ID,
                                doseUom:record.doseUomDr,
                                doseQty:record.doseQty,
                                defaultQty:record.defaultQty,
                            });
                        }else{
                            this.Clear();
                        }
                    }
                },
                onDoubleClick: () => {
                    
                }
            };
        }

        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            let formItemLayout = {
                labelCol: { span: 12 },
                wrapperCol: { span: 12 }
            };
            return (
                <div>
                    <Form>
                        <Row style={{paddingTop:'10px'}}>
                        <Card bodyStyle={{padding:'10px'}}>
                            <Col span={6}>
                            <FormItem {...formItemLayout} label='等效单位'>
                                {getFieldDecorator('DoseUom', {
                                    initialValue:this.state.doseUom,
                                    rules: [{ required: true, message: '等效单位是必填项,请选择！' }]
                                    })(
                                        <Select
                                            allowClear={true}
                                            showSearch 
                                            optionFilterProp="children" 
                                            onChange={this.selectOnChange.bind(this,"doseUom")}
                                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                        >
                                        {this.state.uomData}
                                        </Select>
                                    )}
                            </FormItem>
                            </Col>
                            <Col span={5}>
                            <FormItem {...formItemLayout} label='等效数量'>
                                {getFieldDecorator('DoseQty', {
                                    initialValue:this.state.doseQty,
                                    rules: [{ required: true, message: '等效数量是必填项,请选择！' }]
                                    })(
                                        <Input 
                                            onChange={this.onChangeInput.bind(this,"doseQty")}
                                        />
                                    )}
                            </FormItem>
                            </Col>
                            <Col span={5}>
                            <FormItem {...formItemLayout} label='默认数量'>
                                {getFieldDecorator('DefaultQty', {
                                    initialValue:this.state.defaultQty,
                                    rules: [{ required: false, message: '默认数量是必填项,请选择！' }]
                                    })(
                                        <Input 
                                            onChange={this.onChangeInput.bind(this,"defaultQty")}
                                        />
                                    )}
                            </FormItem>
                            </Col>
                            <Col span={8}>
                                <Button style={{ marginLeft: '20px',marginTop:'2px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleQuery}>查询</Button>
                                <Button style={{ marginLeft: '20px',marginTop:'2px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleSave}>保存</Button>
                                <Button style={{ marginLeft: '20px',marginTop:'2px', background: 'rgba(255,0,0,1)',color:'#ffffff'}}  onClick={this.handleDelete}>删除</Button>
                            </Col>
                            </Card>
                        </Row>
                        <Row type="flex" justify="space-between">
                            <Card bodyStyle={{padding:'10px'}}>
                                <div>
                                    <Table
                                        dataSource={this.state.data}
                                        columns={this.columns}
                                        rowClassName={this.setRowClassName}
                                        pagination={false}
                                        bordered
                                        onRow={this.onClickRow}
                                        style={{height:'260px',width:'550px'}}
                                        scroll={{ x:this.state.TableWidth, y: '215px' }}
                                    
                                    />
                                    {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                                    <Pagination
                                        showTotal={() => this.showTotal(this.state.total)}
                                        size="small"
                                        showQuickJumper
                                        showSizeChanger
                                        defaultCurrent={1}
                                        current={this.state.page}
                                        total={this.state.total}
                                        onChange={this.PageChange}
                                        onShowSizeChange={this.onShowSizeChange}
                                        style={{textAlign: "right", marginTop: '5px'}}
                                    />
                                </div>
                            </Card>
                        </Row>
                    </Form>
                </div>
            )
        }
    }
);
export default FormHandel;