// 医院物资信息维护
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Checkbox, Table, Switch, message, Pagination, Input ,Radio ,Tabs} from 'antd';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import DoctorOrderInformation from './component/DoctorOrderInformation'
import FeeInformation from './component/FeeInformation'
import InventoryItemInformation from './component/InventoryItemInformation'
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import OurInformation from './component/OurInformation'
import StorageCondition from './component/StorageCondition'
import './style/index.less';
import Moment from 'moment';
import store from 'store';
import AIIEssentialInformation from "../../pharmacy/drugMaintenance/component/AddInventoryItem";
import AccordingToRequestForm from "../../pharmacy/inpurplan/InPurPlan";
const { TabPane } = Tabs;
const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:8 },
    wrapperCol: { span: 16 },
};
const formItemCheckbox  = {
    labelCol: {span: 14},
    wrapperCol: {span: 10}
};
const formItemItem  = {
    labelCol: {span: 11},
    wrapperCol: {span: 13}
};
const HospitalMaterialMaintenance = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: {}, //表单数据详情
                SelectData: {}, //下拉数据
                WaListData: [], //物资信息列表数据
                pageSize: 10,
                page: 1,
                total:0,
                rowKey: '', //行选中id
                language: JSON.parse(window.sessionStorage.userData),
                ChineseEnglishSize: [],
                active: 'all',
                value: 'common',
                tableData: {}, //行数据
                FeeInformationData: {}, //收费项的数据
                OurInformationData: {}, //本院目录数据
                columns: [], //表头数据
                columnsWidth: '', //表长度
            }
            // 库存单的数据表头
            this.columns = [

                {
                    key: 1,
                    title: this.state.language.language == 'EN' ?  'Code':'代码',
                    dataIndex: 'stockCode',
                    align: "center",
                    width: '10%'
                },
                {
                    key: 2,
                    title: this.state.language.language == 'EN' ?  'Name':'名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                    width: '10%'
                },
                {
                    key: 3,
                    title: this.state.language.language == 'EN' ?  'Specification':'规格',
                    dataIndex: 'stockSpec',
                    align: "center",
                    width: '10%'
                },
                {
                    key: 4,
                    title: this.state.language.language == 'EN' ?  'Storage unit':'入库单位',
                    dataIndex: 'purUnitDesc',
                    align: "center",
                    width: '10%'
                },
                {
                    key: 5,
                    title: this.state.language.language == 'EN' ?  'Price (inbound unit)':'售价(入库单位)',
                    dataIndex: 'outSpAmt',
                    align: "center",
                    width: '10%'
                },
                {
                    key: 6,
                    title: this.state.language.language == 'EN' ?  'Basic unit':'基本单位',
                    dataIndex: 'baseUnitDesc',
                    align: "center",
                    width: '10%'
                },
                {
                    key: 7,
                    title: this.state.language.language == 'EN' ?  'Inventory classification':'库存分类',
                    dataIndex: 'stkSubCatDesc',
                    align: "center",
                    width: '10%',
                },
                {
                    key: 8,
                    title: this.state.language.language == 'EN' ?  'Creation date':'创建日期',
                    dataIndex: 'qty',
                    align: "center",
                    width: '10%'
                },
                {
                    key: 9,
                    title: this.state.language.language == 'EN' ?  'Updated date':'更新日期',
                    dataIndex: 'outQty',
                    align: "center",
                    width: '10%'
                },

                {
                    key: 10,
                    title: this.state.language.language == 'EN' ?  'Unavailable':'不可用',
                    dataIndex: 'inSpAmt',
                    align: "center",
                    width: '10%'
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getDetailTableColumns();
        }

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态，防止内存泄漏
            this.setState = (state,callback)=>{ return; }
        }

        //清空表格内容
        resetFields = () => {
            this.props.form.resetFields();
            this.setState({userInfo: {}, rowKey: ''});
            this.DoctorOrderChildRef.resetFields();
            this.OurInformationChildRef.resetFields();
        };
        handleReset=()=> {
            this.resetFields();
            this.setState({WaListData: [],total: 0});
        }

        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02060159",
                data: data,
                success: function (res) {
                    if (+res.errorCode == 0) {
                        this.setState({SelectData: res.result})
                    }
                }
            })
        }
        searchInformation=()=>{
            this.setState({page: 1},()=>{
                this.getDeadStockList()
            })
        };
        // 获取物资列表数据
        getDeadStockList=()=>{
            let {language} = this.state;
            this.setState({loading: true});
            let StkCat = this.props.form.getFieldValue('StkCat');
            let StkSubCat = this.props.form.getFieldValue('StkSubCat');
            let Alias = this.props.form.getFieldValue('Alias');
            let data = {
                params: [{
                    alias: Alias ? Alias : '',
                    hospFlag: this.state.value == 'common' ? 1 : 2,
                    stkCatID: StkCat ? StkCat : '',
                    stkSubCatID: StkSubCat ? StkSubCat : '',

                }],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                        sort:"ID",
                        dir:"asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02060160",
                data: data,
                success: function (res) {
                    if(res.errorCode==0 && res.result[0].rows.length > 0){
                        for(let i = 0; i < res.result[0].rows.length; i++){
                            res.result[0].rows[i].key = i;
                        }
                        this.setState({ WaListData: res.result[0].rows, total: res.result[0].total, loading: false});
                    }else {
                        this.setState({ WaListData: [],userInfo: {}});
                        if (language.language =='EN'){
                            message.error("No related data was found");
                        }else{
                            message.error("没数据");
                        }
                        // this.props.form.resetFields();
                    }
                }
            });
        };

        setFeeInformationData=(val)=>{
            this.setState({FeeInformationData: val})
        }
        setOurInformationData=(val)=>{
            this.setState({OurInformationData: val})
        }
        //保存
        saveData=()=>{
            this.DoctorOrderChildRef.setData();
            this.OurInformationChildRef.setData();
            setTimeout(()=>{
                let {FeeInformationData, OurInformationData} = this.state;
            let data = {
                params: [
                    {
                        stockID: this.state.rowKey ? this.state.rowKey : '',
                        packUnitID:OurInformationData.packUnitID ? OurInformationData.packUnitID : '',
                        appPreFixID:OurInformationData.appPreFixID ? OurInformationData.appPreFixID : '',
                        PBLID:OurInformationData.PBLID ? OurInformationData.PBLID : '',
                        PBManfID:OurInformationData.PBManfID ? OurInformationData.PBManfID : '',
                        stockStartDate:OurInformationData.stockStartDate ? Moment(OurInformationData.stockStartDate).format('YYYY-MM-DD') : '',
                        stockEndDate:OurInformationData.stockEndDate ? Moment(OurInformationData.stockEndDate).format('YYYY-MM-DD') : '',
                        packFac:OurInformationData.packFac ? OurInformationData.packFac : '',
                        approvalNo:OurInformationData.approvalNo ? OurInformationData.approvalNo : '',
                        PBRp:OurInformationData.PBRp ? OurInformationData.PBRp : '',
                        PBLevID:OurInformationData.PBLevID ? OurInformationData.PBLevID : '',
                        purPlanCode:OurInformationData.purPlanCode ? OurInformationData.purPlanCode : '',
                        PBVendorID:OurInformationData.PBVendorID ? OurInformationData.PBVendorID : '',
                        packPicPath:OurInformationData.packPicPath ? OurInformationData.packPicPath : '',
                        itemID:this.state.userInfo.itemID ? this.state.userInfo.itemID : '',
                        itemCode:FeeInformationData.itemCode ? FeeInformationData.itemCode : '',
                        itemDesc:FeeInformationData.itemDesc ? FeeInformationData.itemDesc : '',
                        itemTCID:FeeInformationData.itemTCID ? FeeInformationData.itemTCID : '',
                        itemICID:FeeInformationData.itemICID ? FeeInformationData.itemICID : '',
                        itemOCID:FeeInformationData.itemOCID ? FeeInformationData.itemOCID : '',
                        itemECID:FeeInformationData.itemECID ? FeeInformationData.itemECID : '',
                        itemACID:FeeInformationData.itemACID ? FeeInformationData.itemACID : '',
                        itemMCID:FeeInformationData.itemMCID ? FeeInformationData.itemMCID : '',
                        itemStartDate:FeeInformationData.itemStDate ? Moment(FeeInformationData.itemStDate).format('YYYY-MM-DD'): '',
                        itemEndDate:FeeInformationData.itemEndDate ? Moment(FeeInformationData.itemEndDate).format('YYYY-MM-DD'): ''
                    }
                ]
            };
            $http.post('urlS', this, {
                code: "02060163",
                data: data,
                success: function (res) {
                    if(res.errorCode == 0) {
                        message.success(res.errorMessage);
                        this.resetFields();
                        this.getDeadStockList();
                    }
                }
            });
            },300)

        }

        //保存到本院
        handleSaveToHosp = () =>{
            if (this.state.rowKey===""){
                message.warning('请选择药品记录在保存到本院!!');
                return;
            }
            let data= {
                params: [{
                    stockID: this.state.rowKey,
                }],
            }
            $http.post('urlS', this, {
                code: '02060162',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.searchInformation();
                    } else {
                        return;
                    }
                }
            })
        }

        // 设置行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    // this.resetFields();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowKey: record.stockID});
                        this.materialInfoData(record.stockID);
                    } else {
                        if (this.state.rowKey !== record.stockID) {
                            this.setState({rowKey: record.stockID});
                            this.materialInfoData(record.stockID);
                        } else {
                            this.setState({rowKey: '', userInfo: {}});
                            this.resetFields();
                            // this.childDesc.resetFields();
                        }
                    }
                }
            }
        };

        // 表格行的类名
        setRowClassName = (record) => {
            return record.stockID === this.state.rowKey ? 'clickRowStyle' : '';
        };

        materialInfoData=(id)=>{
            let data = {
                params: [
                    {
                        stockID: id ? id : '',
                        hospFlag: this.state.value == 'common' ? 1 : 2,
                    }
                ]
            };
            $http.post('urlS', this, {
                code: "02060161",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({userInfo: res.result})
                    }else {
                        this.setState({userInfo: {}})
                    }
                }
            })

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

        onShowSizeChange = (current, size) => {
            this.setState({page: current, pageSize: size}, () => {
                // 重新调用查询方法
                this.onChange(current,size);
            })
        };

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


        //页面中英文翻译
        getDetailTableColumns = () => {
            let {language} = this.state;
            let data = {
                params: [{
                    reactCode: ['HosMaterialInfoMaintenance'],
                    compontName: 'HosMaterialInfoMaintenance',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: <div onDoubleClick={() => {this.columnRef.onOpenModel();}}>{language.language== 'EN' ? item.enDescripts : item.title}</div>,
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columns:filterArr, columnsWidth: res.totalWidth, ChineseEnglishSize:  language.language=='EN' ? res.result.language.EN : res.result.language.CN})
                    }
                }
            })
        };

        // 切换医嘱项页签
        handleToggleActive = key => {
            this.setState({active: key})
        };
        DoctorOrderRef=(ref)=>{
            this.DoctorOrderChildRef = ref;
        }
        FeeInformationRef=(ref)=>{
            this.DoctorOrderChildRef = ref;
        }
        InventoryItemInformationRef=(ref)=>{
            this.InventoryItemChildRef = ref;
        }
        OurInformationRef=(ref)=>{
            this.OurInformationChildRef = ref;
        };
        StorageConditionRef=(ref)=>{
            this.StorageConditionChildRef = ref;
        };

        onChangeRadio=(val)=>{
            this.setState({value: val.target.value},()=>{
                this.searchInformation();
            })
        }

        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };
        render() {
            const { getFieldDecorator } = this.props.form;
            const {SelectData, userInfo,ChineseEnglishSize, active, columnsWidth , columns} = this.state;


            // // 关联收费项
            // const chargeItemOptions = this.state.chargeData.map(d => <Option title={d.text} key={d.value}>{d.text}</Option>);
            return (
                <div className="HospitalMaterialMaintenance">
                    <Col span={12}>
                        <Row>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.HosMaterialInfoMaintenanceHospitalSupplies ? ChineseEnglishSize.HosMaterialInfoMaintenanceHospitalSupplies.descripts:'医院物资信息'}</div>}
                            >
                                <Col span={22}>
                                    <Row>
                                        <Col span={9} style={{paddingLeft:'10px'}}>
                                            <FormItem {...formItemLayout} label=   {ChineseEnglishSize.HosMaterialInfoMaintenanceStkCat ? ChineseEnglishSize.HosMaterialInfoMaintenanceStkCat.descripts:'库存大类'}>
                                                {getFieldDecorator('StkCat', {
                                                    initialValue:undefined,
                                                })(
                                                    <Select
                                                        style={{ width: '100%'}}
                                                        allowClear={true}
                                                        showSearch
                                                        optionFilterProp="seatchprop"
                                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                    >
                                                        {SelectData.stkCat&& SelectData.stkCat.map((v, i)=>{
                                                            return <Option value={v.id} key={v.id} seatchprop={v.descripts + '^' + v.descriptsSPCode}>{v.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </FormItem>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.HosMaterialInfoMaintenanceAlias ? ChineseEnglishSize.HosMaterialInfoMaintenanceAlias.descripts:'药品别名'}>
                                                {getFieldDecorator('Alias', {
                                                    initialValue:undefined,
                                                })(
                                                    <Input
                                                        allowClear={true}
                                                        onPressEnter={() => this.searchInformation()}
                                                    />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={9} style={{paddingLeft:'20px'}}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.HosMaterialInfoMaintenanceStkSubCat ? ChineseEnglishSize.HosMaterialInfoMaintenanceStkSubCat.descripts:'库存子类'}>
                                                {getFieldDecorator('StkSubCat', {
                                                    initialValue:undefined,
                                                })(
                                                    <Select
                                                        style={{ width: '100%'}}
                                                        allowClear={true}
                                                        showSearch
                                                        optionFilterProp="seatchprop"
                                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                    >
                                                        {SelectData.stkSubCat&& SelectData.stkSubCat.map((v, i)=>{
                                                            return <Option value={v.id} key={v.id} seatchprop={v.descripts + '^' + v.descriptsSPCode}>{v.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </FormItem>
                                            <FormItem>
                                                <Radio.Group onChange={this.onChangeRadio} value={this.state.value}>
                                                    <Radio value='common'>{ChineseEnglishSize.HosMaterialInfoMaintenanceallInfo ? ChineseEnglishSize.HosMaterialInfoMaintenanceallInfo.descripts:'全部信息'}</Radio>
                                                    <Radio value='court'>{ChineseEnglishSize.HosMaterialInfoMaintenancecourtDir ? ChineseEnglishSize.HosMaterialInfoMaintenancecourtDir.descripts:'本院目录'}</Radio>
                                                </Radio.Group>
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem>
                                                <Button style={{ marginLeft: '50px' , background: '#1999db',color:'#ffffff'}}  onClick={this.searchInformation}>{ChineseEnglishSize.HosMaterialInfoMaintenancesearch ? ChineseEnglishSize.HosMaterialInfoMaintenancesearch.descripts:'查询'}</Button>
                                            </FormItem>
                                            <FormItem>
                                                <Button disabled={this.state.saveBtnStatus} style={{ marginLeft: '50px' }}  onClick={this.handleSaveToHosp}>{ChineseEnglishSize.HosMaterialInfoMaintenancesaveToHospital ? ChineseEnglishSize.HosMaterialInfoMaintenancesaveToHospital.descripts:'保存到本院'}</Button>
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Col>
                            </Card>
                        </Row>
                        <Row>
                            <Col>
                                <Card
                                    size="small"
                                    title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.HosMaterialInfoMaintenanceListOfSupplies ? ChineseEnglishSize.HosMaterialInfoMaintenanceListOfSupplies.descripts:'物资列表明细'}</div>}
                                >
                                    <div >
                                        <Table
                                            columns={columns.length>0 ? columns : this.columns}
                                            dataSource={this.state.WaListData}
                                            pagination={false}
                                            bordered
                                            style={{height: store.getState().tableHeight.y -26 + 'px'}}
                                            scroll={{x: columnsWidth? columnsWidth : 1000, y: store.getState().tableHeight.y - 60 }}
                                            rowKey={record => record.key}
                                            onRow={this.onClickRow}
                                            rowClassName={this.setRowClassName}
                                        />
                                        <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                                          onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.WaListData}
                                                          loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                    </div>
                                </Card>
                            </Col>
                        </Row>
                    </Col>
                    <Col span={12}>
                        <div className="header-button">
                            <Button onClick={() => this.handleToggleActive('all')} className={active === 'all' ? 'active first' : 'first'}>
                                {ChineseEnglishSize.HosMaterialInfoMaintenanceallInfo ? ChineseEnglishSize.HosMaterialInfoMaintenanceallInfo.descripts:'全部信息'}
                            </Button>
                            <Button onClick={() => this.handleToggleActive('1')} className={active === '1' ? 'active two' : 'two'}>
                                {ChineseEnglishSize.HosMaterialInfoMaintenanceprescriptionItemInfo ? ChineseEnglishSize.HosMaterialInfoMaintenanceprescriptionItemInfo.descripts:'医嘱项信息'}
                            </Button>
                            <Button onClick={() => this.handleToggleActive('2')} className={active === '2' ? 'active' : ''}>
                                {ChineseEnglishSize.HosMaterialInfoMaintenanceinventoryItemInfo ? ChineseEnglishSize.HosMaterialInfoMaintenanceinventoryItemInfo.descripts:'库存项信息'}
                            </Button>
                            <Button onClick={() => this.handleToggleActive('3')} className={active === '3' ? 'active' : ''}>
                                {ChineseEnglishSize.HosMaterialInfoMaintenancechargeItemInfo ? ChineseEnglishSize.HosMaterialInfoMaintenancechargeItemInfo.descripts:'收费项信息'}
                            </Button>
                            <Button onClick={() => this.handleToggleActive('4')} className={active === '4' ? 'active' : ''}>
                                {ChineseEnglishSize.HosMaterialInfoMaintenancestorageConditions ? ChineseEnglishSize.HosMaterialInfoMaintenancestorageConditions.descripts:'储存条件'}
                            </Button>
                            {this.state.value == 'court' &&
                                <Button onClick={() => this.handleToggleActive('5')} className={active === '5' ? 'active' : ''}>
                                    {ChineseEnglishSize.HosMaterialInfoMaintenanceourInformation ? ChineseEnglishSize.HosMaterialInfoMaintenanceourInformation.descripts:'本院信息'}
                                </Button>
                            }

                        </div>
                        <Col style={{height: store.getState().tableHeight.y +160+ 'px', overflow: 'auto'}}>
                            <div style={{display: (active === 'all' || active === '1') ? 'block ' : 'none'}}>
                                <DoctorOrderInformation
                                    ChineseEnglishSize={ChineseEnglishSize}
                                    onRef={this.DoctorOrderRef}
                                    SelectData={SelectData}
                                    userInfo={userInfo}
                                />
                            </div>
                           <div style={{display: (active === 'all' || active === '2') ? 'block ' : 'none'}}>
                               <InventoryItemInformation
                                   ChineseEnglishSize={ChineseEnglishSize}
                                   onRef={this.InventoryItemInformationRef}
                                   SelectData={SelectData}
                                   userInfo={userInfo}
                               />
                           </div>
                            <div style={{display: (active === 'all' || active === '3') ? 'block ' : 'none'}}>
                                <FeeInformation
                                    ChineseEnglishSize={ChineseEnglishSize}
                                    onRef={this.FeeInformationRef}
                                    SelectData={SelectData}
                                    userInfo={userInfo}
                                    value={this.state.value}
                                    handleThis={this}
                                />
                            </div>
                            <div style={{display: (active === 'all' || active === '4') ? 'block ' : 'none'}}>
                                <StorageCondition
                                    ChineseEnglishSize={ChineseEnglishSize}
                                    onRef={this.StorageConditionRef}
                                    SelectData={SelectData}
                                    userInfo={userInfo}
                                />
                            </div>
                            {this.state.value == 'court' &&
                                <div style={{display: (active === 'all' || active === '5') ? 'block ' : 'none'}}>
                                    <OurInformation
                                        ChineseEnglishSize={ChineseEnglishSize}
                                        onRef={this.OurInformationRef}
                                        SelectData={SelectData}
                                        userInfo={userInfo}
                                        handleThis={this}
                                    />
                                </div>
                            }
                        </Col>
                        {this.state.value == 'court' &&
                            <Col>
                                <Row style={{marginTop: '10px',textAlign: 'right'}} >
                                    <Button style={{marginRight: '30px'}} onClick={this.saveData}>{ChineseEnglishSize.HosMaterialInfoMaintenancesave ? ChineseEnglishSize.HosMaterialInfoMaintenancesave.descripts:'保存'}</Button>
                                    <Button type="primary" onClick={this.resetFields}>{ChineseEnglishSize.HosMaterialInfoMaintenanceReset ? ChineseEnglishSize.HosMaterialInfoMaintenanceReset.descripts:'重置'}</Button>
                                </Row>
                            </Col>
                        }

                    </Col>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='HosMaterialInfoMaintenance'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns}

                    />
                </div>
            )
        }
    }
);
export default HospitalMaterialMaintenance;