//医嘱项维护
import React from 'react';
import {
    Form,Row,Card,Input,Button,Table,Pagination,message,Tag
} from 'antd';
import MedItemSave from './MedItemSave';
import '../../../assets/css/App.css'
import { $http } from '../../../containers/config/https';
import moment from 'moment'
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
var _queryGenericFlag=0;

class MedItemMain extends React.Component {
    constructor(props) {
        super(props)
        // var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            meditemdesc:'',
            total: 0,
            page: 1,
            pageSize: 10,
        }
        this.columns = [
			{
                key: '1',
                title: '医嘱项代码',
                dataIndex: 'medCode',
                width: "10%",
                align: 'center'
            },{
                key: '2',
                title: '医嘱项描述',
                dataIndex: 'medDesc',
                width: "20%",
                align: 'center'
            },{
                key: '3',
                title: '含量规格',
                dataIndex: 'medSpec',
                width: "12%",
                align: 'center'
            },{
                key: '4',
                title: '医嘱子类',
                dataIndex: 'medSubCatDesc',
                width: "15%",
                align: 'center'
            },{
                key: '5',
                title: '处方通用名',
                dataIndex: 'generDesc',
                width: "18%",
                align: 'center'
            },{
                key: '6',
                title: '剂型',
                dataIndex: 'medFormDesc',
                width: "10%",
                align: 'center'
            }];
    }

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

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    // 查询条件 --- 描述
    onChangeDesc = (e) => {
        this.setState({ meditemdesc: e.target.value });
    }

    // 查询全部
	handleAllQuery = () => {
        this.setState({
            genericDesc:'',
            page: 1,
            pageSize: 10,
        })
        _queryGenericFlag=0;
        setTimeout(() => {this.handleQuery(_queryGenericFlag)},100)
    }

    // 查询
	handleQuery = (flag) => {
        //console.log('this.props.genericID:'+this.props.genericID)
		let {meditemdesc, page, pageSize} = this.state;
		let data = {}
        data = {
            params: [{
                generID: this.props.genericID && flag ? this.props.genericID:'',
                medAlias: meditemdesc,
            }],
            pagination:[{
                pageSize: pageSize,
                currentPage: page,
                sort: "ID",
                dir: "desc"
            }]
        }
        //console.log(data)
		$http.post('urlS', this, {
			code: '02020011',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
                    this.setState({
                        selectID:'',
                    })
					for(var i = 0; i < res.result.rows.length; i++) {
						res.result.rows[i].key = i
                    }
                    this.setState({data: res.result.rows, total: res.result.total})
                    if(res.result.rows.length===0)
                    {
                        message.success('没有查询到数据！！！');
                    }
				} else {
                    
				}
			}
        })
    }

    // 医嘱项新增
    handleAdd = () => {
        this.child.setState({
            ordAlone:true,
        },()=>{
            this.child.loadOrdSubCatInfo("");
            // 显示弹框
            this.child.showModal()
            // 初始化数据
            this.setState({
                flag: 'addMedItem', 
                title: '新增医嘱项',
                ID:'',
            })
        })
    }

    // 医嘱项修改
    handleModify = () => {
        if(parseInt(this.state.selectID)>0){
            // 初始化数据
            this.setState({
                flag: 'modifyMedItem', 
                title: '修改医嘱项',
                ID:this.state.selectID,
            },()=>{
                this.GetMedItemInfo(this.state.selectID);
            })
        }else{
            message.warning('请选择医嘱项再修改！！！');
            return; 
        }
    }

    // 医嘱项另存为
    handleSaveAs = () => {
        if(parseInt(this.state.selectID)>0){
            // 初始化数据
            this.setState({
                flag: 'saveAsMedItem', 
                title: '另存医嘱项',
                ID:'',
            },()=>{
                this.GetMedItemInfo(this.state.selectID);
            })
        }else{
            message.warning('请选择医嘱项再另存！！！');
            return; 
        }
    }

    // 获取医嘱项信息
    GetMedItemInfo = (medID) => {
        let data = {}
        data = {
            params: [{
                medID: medID,
            }],
        }
        //console.log(data)
		$http.post('urlS', this, {
			code: '02020012',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    if(this.state.flag==='saveAsMedItem'){
                        // medID='';
                    }
                    this.child.loadOrdSubCatInfo(medID);
                    setTimeout(() => {this.SendMedItemInfo(medID,res)},100)
				} else {
                    
				}
			}
        })
    }

    ///加载医嘱项信息
    SendMedItemInfo = (medID,res) =>{
        this.child.setState({
            medID:medID,
            medCode:res.result.medCode,
            medDesc:res.result.medDesc,
            medShortDesc:res.result.medShortDesc,
            medSubCatID:res.result.medSubCatID,
            medPriorityID:String(res.result.medPriorityID),
            generID:res.result.generID,
            medUnitID:res.result.medUnitID,
            medMessage:res.result.medMessage,
            startDate:res.result.startDate!==""?moment(res.result.startDate).utcOffset(480).format('YYYY-MM-DD'):null,
            medMaxDose:res.result.medMaxDose,
            medQdMaxQty:res.result.medQdMaxQty,
            medSexID:res.result.medSexID!==""?Number(res.result.medSexID):'',
            medAgeFrom:res.result.medAgeFrom,
            medAgeTo:res.result.medAgeTo,
            medDurQty:res.result.medDurQty,
            medDurationID:res.result.medDurationID,
            stopDate:res.result.stopDate!==""?moment(res.result.stopDate).utcOffset(480).format('YYYY-MM-DD'):null,
            medNoAloneOrder:res.result.medNoAloneOrder==="Y"?true:false,
            medNoStockFlag:res.result.medNoStockFlag==="Y"?true:false,
            medNoChangeFlag:res.result.medNoChangeFlag==="Y"?true:false,
            medMergeUseFlag:res.result.medMergeUseFlag==="Y"?true:false,
            medEMFlag:res.result.medEMFlag==="Y"?true:false,
            medPrivateFlag:res.result.medPrivateFlag==="Y"?true:false,
            medToalCountO:res.result.medToalCountO==="Y"?true:false,
            medToalCountI:res.result.medToalCountI==="Y"?true:false,
            medSpec:res.result.medSpec,
            medUsageID:res.result.medUsageID,
            medFreqID:res.result.medFreqID,
            tradeName:res.result.tradeName,
            poisonID:res.result.poisonID,
            criLevID:res.result.criLevID,
            antidFlag:res.result.antidFlag==="Y"?true:false,
            countryFlag:res.result.countryFlag==="Y"?true:false,
            provFlag:res.result.provFlag==="Y"?true:false,
            cityFlag:res.result.cityFlag==="Y"?true:false,
            monitFlag:res.result.monitFlag==="Y"?true:false,
            medSkinTestFlag:res.result.medSkinTestFlag==="Y"?true:false,
            medFormID:res.result.formID,
        },()=>{
            // 显示弹框
            this.child.showModal()
        })
    }

    // 页码改变的回调，参数是改变后的页码及每页条数
    PageChange = (page, pageSize)=> {
        this.setState({page: page, pageSize: pageSize}, () => {
            // 重新调用查询方法
            this.handleQuery(_queryGenericFlag);
        });
    }

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

    setRowClassName = (record) => {
        return record.medID === this.state.selectID ? 'clickRowStyle' : '';
    }

    onClickRow = (record) => {
        //console.log(record)
        return {
            onClick: () => {
                if(this.state.selectID!==record.medID){
                    this.setState({
                        selectID: record.medID,
                        selectCode:record.medCode,
                        selectDesc:record.medDesc,
                    });
                }
            },
            onDoubleClick: () => {
                this.props.handelThis.setState({
                    selectMedItemID:record.medID,
                    selectMedItemDesc:record.medDesc,
                },()=>{

                })
                setTimeout(() => {this.props.handelThis.onChangeTabs(4)},100)
            }
        };
    }
    
    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }

    render() {
        return(
            <div>
                <Row gutter={24}>
                    <Card bodyStyle={{padding:'12px'}}>
                        <Row>
                            <Input placeholder="医嘱项···" value={this.state.meditemdesc} style={{width: '180px', marginLeft: '12px'}} onChange={this.onChangeDesc} />
                            <Button style={{ marginLeft: '25px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleAllQuery}>查询</Button>
                            <Button style={{ marginLeft: '25px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleAdd}>新增</Button>
                            <Button style={{ marginLeft: '25px', background: 'rgba(255,0,0,1)',color:'#ffffff'}}  onClick={this.handleModify}>修改</Button>
                            <Button style={{ marginLeft: '25px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleSaveAs}>另存</Button>
                            <Tag style={{ marginLeft: '25px',fontSize:"12pt"}} color="green">{'处方通用名：' + (this.state.genericDesc?this.state.genericDesc:'全部')}</Tag>
                        </Row>
                    </Card>
                </Row>
                <Row gutter={24}>  
                    <Card bodyStyle={{padding:'12px',paddingLeft:'24px'}}>
                        <Row>
                            <div>
                                <Table
                                    dataSource={this.state.data}
                                    columns={this.columns}
                                    rowClassName={this.setRowClassName}
                                    pagination={false}
                                    bordered
                                    onRow={this.onClickRow}
                                    style={{height:'520px'}}
                                    scroll={{ x: this.state.TableWidth, y: '470px' }}
                                />
                                 <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>
                        </Row>
                    </Card>
                </Row>
                {/* 新增弹框 */}
                <MedItemSave
                    onRef={this.onRef}
                    handelThis={this}
                    title={this.state.title}
                    flag={this.state.flag}
                    ID={this.state.ID}
                />
            </div>
        )
    }
}export default Form.create()(MedItemMain);