// 按消耗量
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Icon, Table, Switch, message, Pagination, Input  } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import './style/index.less';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:7 },
    wrapperCol: { span: 17 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span:11 },
    wrapperCol: { span: 13 },
};

const AccordingConsumption = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                queryCondition: {},
                SelectData: {},
                inOpLocDr:'',
                vendor: '',
                WaListData: [], //库存单数据
                pageSize: 10,
                page: 1,
                total:0,
                columns: [],
                 ChineseEnglishSize: [],
                detailWidthTotal: '',
            }
            // 库存单的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '代码',
                    dataIndex: 'stockCode',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 2,
                    title: '名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 3,
                    title: '规格',
                    dataIndex: 'stockSpec',
                    align: "center",
                    width: '12%'
                },
                {
                    key: 4,
                    title: '单位',
                    dataIndex: 'unitDesc',
                    align: "center",
                    width: '12%'
                },
                {
                    key: 5,
                    title: '可用库存',
                    dataIndex: 'qty',
                    align: "center",
                    width: '12%'
                },
                {
                    key: 6,
                    title: '日消耗量',
                    dataIndex: 'dayQty',
                    align: "center",
                    width: '12%'
                },
                {
                    key: 7,
                    title: '需求量',
                    dataIndex: 'needQty',
                    align: "center",
                    width: '12%'
                },
                {
                    key: 8,
                    title: '生产厂家',
                    dataIndex: 'manfDesc',
                    align: "center",
                    width: '12%'
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getDetailTableColumns();
            let listData = document.querySelectorAll('.AccordingHeight  .ant-table-body');
            if(listData.length>0){
                listData[0].style.height = store.getState().tableHeight.y + 25 + 'px';
            }
        }

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

        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let {userInfo} = this.state;
            let data = {
                params: [{
                    reactCode: ['InventoryAlarmAccordingToConsu'],
                    compontName: 'AccordingConsumptionList',
                    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();}}>{userInfo.language== 'EN' ? item.enDescripts : item.title}</div>,
                                render: (text, record)=>{
                                    return (<span className={record.warnID == 1 && item.code == 'warnStatus' ? 'redColor' : record.warnID == 2 && item.code == 'warnStatus' ? 'cyanColor': ''}>{text}</span>)
                                }
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columns: filterArr, detailWidthTotal: res.totalWidth,ChineseEnglishSize:userInfo.language=='EN' ? res.result.language.EN : res.result.language.CN})
                    }
                }
            });
        };

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

        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02020183",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({SelectData: res})
                    }
                }
            })
        }

        searchInformation=()=>{
            this.setState({page: 1},()=>{
                this.getConsumptionList()
            })
        };

        // 获取库存单列表数据
        getConsumptionList=()=>{
            let {ChineseEnglishSize} = this.state;
            this.setState({loading: true})
            this.props.form.validateFields((error, value)=>{
                let obj = JSON.parse(JSON.stringify(value));
                if(error == null){
                    let data = {
                        params: [{
                            locID: obj.locDesc ? obj.locDesc : undefined,
                            startDate: obj.StartDate ? Moment(obj.StartDate).format( 'YYYY-MM-DD') : undefined,
                            endDate: obj.EndData ? Moment(obj.EndData).format('YYYY-MM-DD') : undefined,
                            useDays: obj.useDays ? obj.useDays : undefined,
                            incNotFlag: obj.incNotFlag ? true : false,
                        }],
                        pagination: [
                            {
                                pageSize:this.state.pageSize,
                                currentPage:this.state.page,
                                sort:"ID",
                                dir:"asc",
                            }
                        ],
                    };
                    $http.post('urlS', this, {
                        code: "02020182",
                        data: data,
                        success: function (res) {
                            if(res.rows.length > 0){
                                for(let i = 0; i < res.rows.length; i++){
                                    res.rows[i].key = i;
                                }
                                this.setState({ WaListData: res.rows,total: res.total, loading: false});

                            }else {
                                this.setState({ WaListData: [],total: 0});
                                 message.error(ChineseEnglishSize.InventoryAlarmAccordingToConsunoData ? ChineseEnglishSize.InventoryAlarmAccordingToConsunoData.descripts:"没数据");
                            }
                        },
                        error: function (err) {
                            message.error(err.errorMessage)
                        }
                    });
                }
            })

        };

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

        onShowSizeChange = (current, size) => {
            this.setState({page: current, pageSize: size}, () => {
                // 重新调用查询方法
                this.onChange(current,size);
            })
        };
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };

        render() {
            const { getFieldDecorator } = this.props.form;
            let {ChineseEnglishSize,userInfo} = this.state;
            //库存科室列表
            let inOpLocDrSelect = [];
            this.state.SelectData.loc && this.state.SelectData.loc.map((item, i) => {
                inOpLocDrSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });

            return (
                <div className="accordingConsumption">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.InventoryAlarmAccordingToConsuaccToConsumption ? ChineseEnglishSize.InventoryAlarmAccordingToConsuaccToConsumption.descripts:'库存报警-按消耗量'}</div>}
                        >
                            <Col span={19}>
                                <Form>
                                    <Row >
                                        <Col span={5}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.InventoryAlarmAccordingToConsuloc ? ChineseEnglishSize.InventoryAlarmAccordingToConsuloc.descripts:'科室'}>
                                                {getFieldDecorator('locDesc',{
                                                    initialValue: this.state.userInfo.locID ? this.state.userInfo.locID : undefined,
                                                    rules:[{ required : ChineseEnglishSize.InventoryAlarmAccordingToConsuloc ? ChineseEnglishSize.InventoryAlarmAccordingToConsuloc.required =='Y'? true:false: false, message: ChineseEnglishSize.InventoryAlarmAccordingToConsuloc ? ChineseEnglishSize.InventoryAlarmAccordingToConsuloc.message:'科室不能为空'}] 
                                                })(
                                                    <Select allowClear>
                                                        {inOpLocDrSelect}
                                                    </Select>
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={5}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.InventoryAlarmAccordingToConsuStartDate ? ChineseEnglishSize.InventoryAlarmAccordingToConsuStartDate.descripts:'开始日期'}>
                                                {getFieldDecorator('StartDate',{
                                                    initialValue: this.state.SelectData.params&&this.state.SelectData.params.startDate ? Moment(this.state.SelectData.params.startDate, 'YYYY-MM-DD') : Moment(),
                                                })(
                                                    <DatePicker format="YYYY-MM-DD" />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={5}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.InventoryAlarmAccordingToConsudeadline ? ChineseEnglishSize.InventoryAlarmAccordingToConsudeadline.descripts:'结束日期'}>
                                                {getFieldDecorator('EndData',{
                                                    initialValue: this.state.SelectData.params&&this.state.SelectData.params.endDate ? Moment(this.state.SelectData.params.endDate, 'YYYY-MM-DD') : Moment(),
                                                })(
                                                    <DatePicker  format="YYYY-MM-DD" />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={4}>
                                            <FormItem {...formItemSwitch} label={ChineseEnglishSize.InventoryAlarmAccordingToConsuuseDays ? ChineseEnglishSize.InventoryAlarmAccordingToConsuuseDays.descripts:'用药天数'}>
                                                {getFieldDecorator('useDays',{
                                                    initialValue: undefined,
                                                })(
                                                   <Input />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={5}>
                                            <FormItem {...formItemSwitch} label={ChineseEnglishSize.InventoryAlarmAccordingToConsuincNotFlag ? ChineseEnglishSize.InventoryAlarmAccordingToConsuincNotFlag.descripts:'包含不可用品种'}>
                                                {getFieldDecorator('incNotFlag',{
                                                    valuePropName: 'checked',
                                                    initialValue: false,
                                                    rules:[{required: false}]
                                                })(
                                                    userInfo.language == 'EN' ?  <Switch checkedChildren="Yes" unCheckedChildren="No" /> : <Switch checkedChildren="是" unCheckedChildren="否" />
                                                ) }
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={5}>
                                <Row style={{marginBottom: '18px'}} className="button">
                                <Button style={{marginRight: '30px'}} onClick={this.searchInformation}>{ChineseEnglishSize.InventoryAlarmAccordingToConsusearch ? ChineseEnglishSize.InventoryAlarmAccordingToConsusearch.descripts:'查询'}</Button>
                                    <Button type="primary" onClick={this.handleReset}>{ChineseEnglishSize.InventoryAlarmAccordingToConsuclean ? ChineseEnglishSize.InventoryAlarmAccordingToConsuclean.descripts:'清屏'}</Button>
                                </Row>
                            </Col>

                        </Card>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.InventoryAlarmAccordingToConsuinventoryAlarmForm ? ChineseEnglishSize.InventoryAlarmAccordingToConsuinventoryAlarmForm.descripts:'库存报警单'}</div>}
                                extra={<span style={{color: '#666'}} className='span' onClick={() => { this.columnRef.onOpenModel();}}><Icon type="setting" title={ChineseEnglishSize.InventoryAlarmAccordingToConsucolumnSettings ? ChineseEnglishSize.InventoryAlarmAccordingToConsucolumnSettings.descripts:'列权限设置'} /></span>}
                            >
                                <div style={{height: store.getState().tableHeight.y + 95 + 'px'}}>
                                    <Table
                                        columns={this.state.columns.length>0 ? this.state.columns : this.columns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        style={{height: store.getState().tableHeight.y +50 + 'px'}}
                                        scroll={{x: this.state.detailWidthTotal ? this.state.detailWidthTotal : 1600, y: store.getState().tableHeight.y  }}
                                        rowKey={record => record.key}
                                        className="AccordingHeight"
                                    />
                                    <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>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='AccordingConsumptionList'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns}
                    />
                </div>
            )
        }
    }
);
export default AccordingConsumption;