//库存项维护
import React from 'react';
import {
    Form,Row,Card,Input,Button,Table,Pagination,message,Tag
} from 'antd';
import StockItemSave from './StockItemSave';
import StockLinkCharge from './StockLinkCharge';
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 _queryMedItemFlag=0;

class StockItemMain extends React.Component {
    constructor(props) {
        super(props)
        // var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            stockItemDesc:'',
            total: 0,
            page: 1,
            pageSize: 10,
        }
        this.columns = [
			{
                key: '1',
                title: '库存项代码',
                dataIndex: 'stockCode',
                width: "10%",
                align: 'center'
            },{
                key: '2',
                title: '库存项描述',
                dataIndex: 'stockDesc',
                width: "20%",
                align: 'center'
            },{
                key: '3',
                title: '包装规格',
                dataIndex: 'stockSpec',
                width: "10%",
                align: 'center'
            },{
                key: '4',
                title: '库存分类',
                dataIndex: 'stkSubCatDesc',
                width: "10%",
                align: 'center'
            },{
                key: '5',
                title: '基本单位',
                dataIndex: 'baseUnitDesc',
                width: "10%",
                align: 'center'
            },{
                key: '6',
                title: '医嘱项描述',
                dataIndex: 'medDesc',
                width: "20%",
                align: 'center'
            }];
    }

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

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

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

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

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

    // 查询
	handleQuery = (flag) => {
        //console.log('this.props.genericID:'+this.props.genericID)
		let {stockItemDesc, page, pageSize} = this.state;
		let data = {}
        data = {
            params: [{
                medItemDr: this.props.medItemID && flag ? this.props.medItemID:'',
                descripts: stockItemDesc,
            }],
            pagination:[{
                pageSize: pageSize,
                currentPage: page,
                sort: "ID",
                dir: "desc"
            }]
        }
        //console.log(data)
		$http.post('urlS', this, {
			code: '02020027',
			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,
            intrFlag:false,
        },()=>{
            // 显示弹框
            this.child.showModal()
            // 初始化数据
            this.setState({
                flag: 'addStockItem', 
                title: '新增库存项',
                ID:'',
            })
        })
    }

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

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

    // 获取库存项信息
    GetStockItemInfo = (stockID) => {
        let data = {}
        data = {
            params: [{
                stockID: stockID,
            }],
        }
        //console.log(data)
		$http.post('urlS', this, {
			code: '02020028',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    this.child.setState({
                        stockID:this.state.flag==='saveAsStockItem'?'':stockID,
                        stockCode:res.result.stockCode,
                        stockDesc:res.result.stockDesc,
                        stockSpec:res.result.stockSpec,
                        barCode:res.result.barCode,
                        baseUnitID:res.result.baseUnitID,
                        purUnitID:res.result.purUnitID,
                        baseFac:res.result.baseFac,
                        stkSubCatID:res.result.stkSubCatID,
                        medDesc:res.result.medDesc,
                        medID:res.result.medID,
                        importTypeID:res.result.importTypeID,
                        quaLevID:res.result.quaLevID,
                        qualityNo:res.result.qualityNo,
                        priceTypeID:res.result.priceTypeID,
                        maxSp:res.result.maxSp,
                        priceFileNo:res.result.priceFileNo,
                        drugUseInfo:res.result.drugUseInfo,
                        packUnitID:res.result.packUnitID,
                        packFac:res.result.packFac,
                        packPicPath:res.result.packPicPath,
                        appPreFixID:res.result.appPreFixID,
                        approvalNo:res.result.approvalNo,
                        PBLID:res.result.PBLID,
                        PBRp:res.result.PBRp,
                        PBVendorID:res.result.PBVendorID,
                        PBManfID:res.result.PBManfID,
                        PBLevID:res.result.PBLevID,
                        standCode:res.result.standCode,
                        inMedBasis:res.result.inMedBasis,
                        purPlanCode:res.result.purPlanCode,
                        refRetReaID:res.result.refRetReaID,
                        startDate:res.result.startDate!==""?moment(res.result.startDate).utcOffset(480).format('YYYY-MM-DD'):null,
                        stopDate:res.result.stopDate!==""?moment(res.result.stopDate).utcOffset(480).format('YYYY-MM-DD'):null,
                        stopReaID:res.result.stopReaID,
                        rp:res.result.rp,
                        sp:res.result.sp,
                        billFac:res.result.billFac,
                        isHospFlag:res.result.isHospFlag==="Y"?true:false,
                        itemID:this.state.flag==='saveAsStockItem'?'':res.result.itemID,
                        chargeItem:this.state.flag==='saveAsStockItem'?'':res.result.itemDesc,
                        itemCode:res.result.itemCode,
                        itemDesc:res.result.itemDesc,
                        itemTCID:res.result.itemTCID,
                        itemPCID:res.result.itemPCID,
                        itemICID:res.result.itemICID,
                        itemOCID:res.result.itemOCID,
                        itemECID:res.result.itemECID,
                        itemACID:res.result.itemACID,
                        itemMCID:res.result.itemMCID,
                        itemStDate:res.result.itemStDate!==""?moment(res.result.itemStDate).utcOffset(480).format('YYYY-MM-DD'):null,
                        itemEndDate:res.result.itemEndDate!==""?moment(res.result.itemEndDate).utcOffset(480).format('YYYY-MM-DD'):null,
                        minTemp:res.result.minTemp,
                        maxTemp:res.result.maxTemp,
                        minHumidity:res.result.minHumidity,
                        maxHumidity:res.result.maxHumidity,
                        commonTemp:res.result.commonTemp==="Y"?true:false,
                        dry:res.result.dry==="Y"?true:false,
                        airtight:res.result.airtight==="Y"?true:false,
                        dark:res.result.dark==="Y"?true:false,
                        radiation:res.result.radiation==="Y"?true:false,
                        seal:res.result.seal==="Y"?true:false,
                        gloomyCool:res.result.gloomyCool==="Y"?true:false,
                        meltPack:res.result.meltPack==="Y"?true:false,
                        coldST:res.result.coldST==="Y"?true:false,
                        freeze:res.result.freeze==="Y"?true:false,  
                        dampProof:res.result.dampProof==="Y"?true:false,
                        intrFlag: this.state.flag==='modifyStockItem'? (res.result.intrFlag===1?true:false) : false,
                    },()=>{
                        // 显示弹框
                        this.child.showModal()
                    })
				} else {
                    
				}
			}
        })
    }


    // 库存项关联收费项
    handleLinkCharge = () => {
        if(parseInt(this.state.selectID)>0){
            // 初始化数据
            this.childLinkCharge.setState({
                stockItemID:this.state.selectID,
            },()=>{
                // 显示弹框
                this.childLinkCharge.showModal();
                setTimeout(() => {this.childLinkCharge.handleQuery()},100)
            })
        }else{
            message.warning('请选择库存项做关联操作！！！');
            return; 
        }
    }

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

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

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

    onClickRow = (record) => {
        //console.log(record)
        return {
            onClick: () => {
                if(this.state.selectID!==record.stockID){
                    this.setState({
                        selectID: record.stockID,
                        selectCode:record.stockCode,
                        selectDesc:record.stockDesc,
                    });
                }
            },
            onDoubleClick: () => {
                
            }
        };
    }

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

    render() {
        return(
            <div>
                <Row gutter={24}>
                    <Card bodyStyle={{padding:'12px'}}>
                        <Row>
                            <Input placeholder="库存项···" value={this.state.stockItemDesc} style={{width: '150px', marginLeft: '12px'}} onChange={this.onChangeDesc} />
                            <Button style={{ marginLeft: '20px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleAllQuery}>查询</Button>
                            <Button style={{ marginLeft: '20px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleAdd}>新增</Button>
                            <Button style={{ marginLeft: '20px', background: 'rgba(255,0,0,1)',color:'#ffffff'}}  onClick={this.handleModify}>修改</Button>
                            <Button style={{ marginLeft: '20px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleSaveAs}>另存</Button>
                            {/* <Button style={{ marginLeft: '20px', background: 'rgba(100,169,130,1)',color:'#ffffff'}}  onClick={this.handleLinkCharge}>关联收费项</Button> */}
                            <Tag style={{ marginLeft: '20px',fontSize:"12pt"}} color="green">{'医嘱项：' + (this.state.medItemDesc?this.state.medItemDesc:'全部')}</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>
                {/* 新增弹框 */}
                <StockItemSave
                    onRef={this.onRef}
                    handelThis={this}
                    title={this.state.title}
                    flag={this.state.flag}
                    ID={this.state.ID}
                />
                <StockLinkCharge
                    onRef={this.onRefLinkCharge}
                    handelThis={this}
                />
            </div>
        )
    }
}export default Form.create()(StockItemMain);