//限制用药维护
import React from 'react';
import {
    Form,Row,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 = { 
                data:[],
                relation:'',
                operType:'',
                pointer:'',
                pointerDesc:'',
                operate:'',
                level:'',
                relationData:[],
                operTypeData:[],
                operateData:[],
                levelData:[],
                pointerData:[],
                total: 0,
                page: 1,
                pageSize: 10,
                findFlag:'0',
            }
            this.columns = [
                // {
                //     key: 'relation',
                //     title: '关系',
                //     dataIndex: 'relation',
                //     width: "15%",
                //     align: 'center'
                // },
                {
                    key: 'operate',
                    title: '操作',
                    dataIndex: 'operate',
                    width: "15%",
                    align: 'center'
                },{
                    key: 'operType',
                    title: '类型',
                    dataIndex: 'operType',
                    width: "15%",
                    align: 'center'
                },{
                    key: 'pointer',
                    title: '类型值',
                    dataIndex: 'pointer',
                    width: "30%",
                    align: 'center'
                },{
                    key: 'level',
                    title: '管控级别',
                    dataIndex: 'level',
                    width: "15%",
                    align: 'center'
                }
            ];
        }
        componentDidMount() {
            this.props.onRef(this);
            this.loadInfo(); //获取下拉框信息
        }

        //获取下拉框信息
        loadInfo(){
            var params = [{}]
            $http.post('urlS', this, {
                code: "02020020",
                data: params,
                success: function (res) {
                    if (res.errorCode === '0') {
                        var j=0
                        // for(j = 0; j < res.relation.length; j++) {
                        //     this.state.relationData.push(<Option value={res.relation[j].id} key={j}>{res.relation[j].descripts}</Option>)
                        // }
                        for(j = 0; j < res.operType.length; j++) {
                            this.state.operTypeData.push(<Option value={res.operType[j].id} title={res.operType[j].descripts} key={j}>{res.operType[j].descripts}</Option>)
                        }
                        for(j = 0; j < res.operate.length; j++) {
                            this.state.operateData.push(<Option value={res.operate[j].id} title={res.operate[j].descripts} key={j}>{res.operate[j].descripts}</Option>)
                        }
                        for(j = 0; j < res.level.length; j++) {
                            this.state.levelData.push(<Option value={res.level[j].id} title={res.level[j].descripts} key={j}>{res.level[j].descripts}</Option>)
                        }
                    }
                }
            });
        }

        //获取下拉框信息
        loadPointerInfo(value){
            let data = {}
            data = {
                params: [{
                    typeCode: value,
                }],
            }
            //console.log(data)
            $http.post('urlS', this, {
                code: "02020021",
                data: data,
                success: function (res) {
                    if (res.errorCode === '0') {
                        var j=0
                        for(j = 0; j < res.pointer.length; j++) {
                            this.state.pointerData.push(<Option value={res.pointer[j].id} title={res.pointer[j].descripts} key={j}>{res.pointer[j].descripts}</Option>)
                        }
                    }
                }
            });
        }

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

        ///处理select  relation
        selectOnChange_relation=(value,option)=>{
            if(value){
                this.setState({
                    [option.props.title]:value,
                })
            }else{
                this.setState({
                    relation:'',
                })
            }
        }

        ///处理select operType
        selectOnChange_operType=(name,value,option)=>{
            if(value){
                this.setState({
                    [name]:value,
                    pointer:'',
                    pointerDesc:'',
                    pointerData:[],
                })
                this.loadPointerInfo(value);
            }else{
                this.setState({
                    operType:'',
                })
            }
        }

        ///处理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: "02020023",
                    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: '',
                                relation:'',
                                operType:'',
                                pointer:'',
                                pointerDesc:'',
                                operate:'',
                                level:'',
                            })
                            this.props.form.resetFields();
                        }
                    }
                });
            }else{

            }
        }

        // 保存
        handleSave = () => {
            // if(this.state.relation===""){
            //     message.warning('关系不能为空!!');
            //     return;
            // }
            if(this.state.operType===""){
                message.warning('类型不能为空!!');
                return;
            }
            if(this.state.pointer===""){
                message.warning('类型值不能为空!!');
                return;
            }
            if(this.state.operate===""){
                message.warning('操作不能为空!!');
                return;
            }
            if(this.state.level===""){
                message.warning('管控级别不能为空!!');
                return;
            }
            if(parseInt(this.state.medItemID)>0){
                let data = {}
                data={
                    params: [{
                        medID: this.state.medItemID,
                        ID: this.state.selectID,
                        // relation:this.state.relation,
                        operType:this.state.operType,
                        pointer:this.state.pointer,
                        operate:this.state.operate,
                        level:this.state.level,
                    }],
                }
                $http.post('urlS', this, {
                    code: "02020022",
                    data: data,
                    success: function (res) {
                        if (res.errorCode === '0') {
                            message.success('保存成功');
                            this.handleQuery();
                        }
                    }
                });
            }else{
                let obj= {
                    key:0,
                    ID: "",
                    level: "",
                    levelDr: this.state.level,
                    operType: "",
                    operTypeDr: this.state.operType,
                    operate: "",
                    operateDr: this.state.operate,
                    pointer: "",
                    pointerDr: this.state.pointer,
                }
                for (var i = 0; i < this.state.operTypeData.length; i++) {
                    if (this.state.operTypeData[i].props.value === this.state.operType) {
                        obj.operType = this.state.operTypeData[i].props.children;
                        break;
                    }
                }
                for (var i = 0; i < this.state.operateData.length; i++) {
                    if (this.state.operateData[i].props.value === this.state.operate) {
                        obj.operate = this.state.operateData[i].props.children;
                        break;
                    }
                }
                for (var i = 0; i < this.state.levelData.length; i++) {
                    if (this.state.levelData[i].props.value === this.state.level) {
                        obj.level = this.state.levelData[i].props.children;
                        break;
                    }
                }
                for (var i = 0; i < this.state.pointerData.length; i++) {
                    if (this.state.pointerData[i].props.value === this.state.pointer) {
                        obj.pointer = this.state.pointerData[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: "02020024",
                    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: '',
                // relation:'',
                operType:'',
                pointer:'',
                pointerDesc:'',
                operate:'',
                level:'',
            })
            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();
                    this.setState({
                        pointerData: [],
                    },()=>{
                        if(record.operTypeDr!==""){
                            this.loadPointerInfo(record.operTypeDr);
                        }
                        if(this.state.selectKey===""){
                            this.setState({
                                selectKey: record.key,
                                selectID: record.ID,
                                // relation:record.relationDr,
                                operType:record.operTypeDr,
                                pointerDesc:record.pointer,
                                pointer:record.pointerDr,
                                operate:record.operateDr,
                                level:record.levelDr,
                            });
                        }else{
                            if(this.state.selectKey!==record.key){
                                this.setState({
                                    selectKey: record.key,
                                    selectID: record.ID,
                                    // relation:record.relationDr,
                                    operType:record.operTypeDr,
                                    pointer:record.pointerDr,
                                    operate:record.operateDr,
                                    level:record.levelDr,
                                });
                            }else{
                                this.Clear();
                            }
                        }
                    });
                    
                },
                onDoubleClick: () => {
                    
                }
            };
        }

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

        render() {
            const { getFieldDecorator } = this.props.form;
            let formItemLayout = {
                labelCol: { span: 9},
                wrapperCol: { span: 15 }
            };
            return (
                <div>
                    <Form>
                        <Card bodyStyle={{padding:'5px'}}>
                            <Row>
                                <Col span={9}>
                                    <FormItem {...formItemLayout} label='类型'>
                                        {getFieldDecorator('OperType', {
                                            initialValue:this.state.operType,
                                            rules: [{ required: true, message: '类型是必填项,请选择！' }]
                                            })(
                                                <Select
                                                    allowClear={true}
                                                    showSearch 
                                                    optionFilterProp="children" 
                                                    onChange={this.selectOnChange_operType.bind(this,"operType")}
                                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                >
                                                {this.state.operTypeData}
                                                </Select>
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={9}>
                                    <FormItem {...formItemLayout} label='操作'>
                                        {getFieldDecorator('Operate', {
                                            initialValue:this.state.operate,
                                            rules: [{ required: true, message: '操作是必填项,请选择！' }]
                                            })(
                                                <Select
                                                    allowClear={true}
                                                    showSearch 
                                                    optionFilterProp="children" 
                                                    onChange={this.selectOnChange.bind(this,"operate")}
                                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                >
                                                {this.state.operateData}
                                                </Select>
                                            )}
                                    </FormItem>
                                </Col>
                                {/* <Col span={6}>
                                    <FormItem {...formItemLayout} label='关系'>
                                        {getFieldDecorator('Relation', {
                                            initialValue:this.state.relation,
                                            rules: [{ required: true, message: '关系是必填项,请选择！' }]
                                            })(
                                                <Select
                                                    allowClear={true}
                                                    showSearch 
                                                    optionFilterProp="children" 
                                                    onChange={this.selectOnChange.bind(this,"relation")}
                                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                >
                                                {this.state.relationData}
                                                </Select>
                                            )}
                                    </FormItem>
                                </Col> */}
                                <Col span={3}>
                                    <Button style={{ marginLeft: '30px',marginTop:'2px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleSave}>保存</Button>          
                                </Col>
                                </Row>
                                <Row>
                                <Col span={9}>
                                    <FormItem {...formItemLayout} label='类型值'>
                                        {getFieldDecorator('Pointer', {
                                            initialValue:this.state.pointerDesc,
                                            rules: [{ required: true, message: '类型值是必填项,请选择！' }]
                                            })(
                                                <Select
                                                    allowClear={true}
                                                    showSearch 
                                                    optionFilterProp="children" 
                                                    onChange={this.selectOnChange.bind(this,"pointer")}
                                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                >
                                                {this.state.pointerData}
                                                </Select>
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={9}>
                                    <FormItem {...formItemLayout} label='管控级别'>
                                        {getFieldDecorator('level', {
                                            initialValue:this.state.level,
                                            rules: [{ required: true, message: '管控级别是必填项,请选择！' }]
                                            })(
                                                <Select
                                                    allowClear={true}
                                                    showSearch 
                                                    optionFilterProp="children" 
                                                    onChange={this.selectOnChange.bind(this,"level")}
                                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                >
                                                {this.state.levelData}
                                                </Select>
                                            )}
                                    </FormItem>
                                </Col>
                                {/* <Col span={6}></Col> */}
                                <Col span={3}>
                                    <Button style={{ marginLeft: '30px',marginTop:'2px', background: 'rgba(255,0,0,1)',color:'#ffffff'}}  onClick={this.handleDelete}>删除</Button>
                                </Col>
                            </Row>
                        </Card>
                        <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:'700px'}}
                                        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;