// 效期报警
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';
import {printStkExpWarnData} from '../commonPrint/stkPrint';
var serialNumber = 0; //库存单序列号

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:10 },
    wrapperCol: { span: 14 },
};
const formItemSpan = {    // label 和input宽度
    labelCol: { span:5 },
    wrapperCol: { span: 19 },
};

const ExpiryDateAlertor = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                queryCondition: {},
                SelectData: {},
                inOpLocDr:'',
                vendor: '',
                WaListData: [], //库存单数据
                pageSize: 20,
                page: 1,
                total:0,
                stateID: '',
                columns: [],
                detailWidthTotal: '',
                ChineseEnglishSize: [],
                printInfo:{},
                BottomState: false, //導出按鈕裝填
                allRpAmt: '', //总金额
            }
            // 库存单的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '状态',
                    dataIndex: 'status',
                    align: "center",
                    width: '7%',
                },
                {
                    key: 2,
                    title: '代码',
                    dataIndex: 'stockCode',
                    align: "center",
                    width: '9%'
                },
                {
                    key: 3,
                    title: '名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 4,
                    title: '规格',
                    dataIndex: 'stockSpec',
                    align: "center",
                    width: '6%'
                },
                {
                    key: 5,
                    title: '批号',
                    dataIndex: 'batNo',
                    align: "center",
                    width: '9%'
                },
                {
                    key: 6,
                    title: '效期',
                    dataIndex: 'expDate',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 7,
                    title: '库存',
                    dataIndex: 'qty',
                    align: "center",
                    width: '6%'
                },
                {
                    key: 8,
                    title: '单位',
                    dataIndex: 'unitDesc',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 9,
                    title: '生产厂家',
                    dataIndex: 'stkSubCatDesc',
                    align: "center",
                    width: '9%'
                },
                {
                    key: 10,
                    title: '库存子类',
                    dataIndex: 'manfDesc',
                    align: "center",
                    width: '6%'
                },
                {
                    key: 11,
                    title: '货位',
                    dataIndex: 'rpAmt',
                    align: "center",
                    width: '8%'
                },
                {
                    key: 12,
                    title: '最后一次入库供应商',
                    dataIndex: 'remark',
                    align: "center",
                    width: '9%'
                },
                {
                    key: 13,
                    title: '失效天数',
                    dataIndex: 'expDate',
                    align: "center",
                    width: '6%'
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getDetailTableColumns();
            let listData = document.querySelectorAll('.ExpiryHeight  .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: ['ValidityAlarm'],
                    compontName: 'ExpiryDateAlertorList',
                    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, index)=>{
                                    if(item.code == 'status'){
                                        return <span style={{width: '100%',height: '100%',display: 'inline-block',backgroundColor: record.color}}>{text}</span>
                                    } else if(item.code == 'Serial'){
                                        return <span>{index+1}</span>
                                    }else {
                                        return text
                                    }
                                },
                                sorter:item.code == 'status'? (a, b) => a.invalDays - b.invalDays : false,
                            }
                        }) : '';
                        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, allRpAmt: ''});
            this.props.form.resetFields();
        };

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

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

        printInfo=()=>{
            this.props.form.validateFields((error, value)=> {
                let obj = JSON.parse(JSON.stringify(value));
                if(error == null){
                    let data = {
                        params: [{
                            locID: obj.Loc ? obj.Loc : undefined,
                            stkCatID: obj.stkCatID ? obj.stkCatID : undefined,
                            stkSubCatID: obj.stkSubCatID ? obj.stkSubCatID : undefined,
                            endExpDate: obj.endExpDate ? Moment(obj.endExpDate ).format('YYYY-MM-DD'): undefined,
                            incZeroBat: obj.incZeroBat ? true : false,
                            excNotFlag: obj.excNotFlag ? true : false,
                            restMonth: obj.restMonth ? obj.restMonth :'',
                        }]
                    };
                    printStkExpWarnData(data)
                }
            })
        }
        // 获取库存单列表数据
        getBoundList=()=>{
            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.Loc ? obj.Loc : undefined,
                            stkCatID: obj.stkCatID ? obj.stkCatID : undefined,
                            stkSubCatID: obj.stkSubCatID ? obj.stkSubCatID : undefined,
                            endExpDate: obj.endExpDate ? Moment(obj.endExpDate ).format('YYYY-MM-DD'): undefined,
                            incZeroBat: obj.incZeroBat ? true : false,
                            excNotFlag: obj.excNotFlag ? true : false,
                            restMonth: obj.restMonth ? obj.restMonth :'',
                        }],
                        pagination: [
                            {
                                pageSize:this.state.pageSize,
                                currentPage:this.state.page,
                                sort:"ID",
                                dir:"asc",
                            }
                        ],
                    };
                    $http.post('urlS', this, {
                        code: "02020186",
                        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,allRpAmt: res.allRpAmt, loading: false});
                                serialNumber = 0;

                            }else {
                                this.setState({ WaListData: [],total: 0, page: 1});
                                message.error(ChineseEnglishSize.ValidityAlarmnoData ? ChineseEnglishSize.ValidityAlarmnoData.descripts:"没数据");

                            }
                        }
                    });
                }
            })
        };

        //导出数据
        ExportData =()=>{
            let {ChineseEnglishSize} = this.state;
            this.setState({BottomState: true})
            this.props.form.validateFields((error, value)=> {
                let obj = JSON.parse(JSON.stringify(value));
                if(obj.restMonth==null){
                    this.setState({BottomState: false})
                    message.error(ChineseEnglishSize.ValidityAlarmwarnDate ? ChineseEnglishSize.ValidityAlarmwarnDate.descripts:'请选择报警期限时间')
                }else if(error == null){
                    let data = {
                        params: [{
                            locID: obj.Loc ? obj.Loc : undefined,
                            stkCatID: obj.stkCatID ? obj.stkCatID : undefined,
                            stkSubCatID: obj.stkSubCatID ? obj.stkSubCatID : undefined,
                            endExpDate: obj.endExpDate ? Moment(obj.endExpDate ).format('YYYY-MM-DD'): undefined,
                            incZeroBat: obj.incZeroBat ? true : false,
                            excNotFlag: obj.excNotFlag ? true : false,
                            restMonth: obj.restMonth ? obj.restMonth :'',
                        }]
                    };
                    $http.post('urlS', this, {
                        code: "02020342",
                        data: data,
                        success: function (res) {
                            if(res.result.filePath){
                                document.getElementById("ifile").src= window.location.protocol+"//"+window.location.host+res.result.filePath;
                                this.setState({BottomState: false})
                                message.success(ChineseEnglishSize.ValidityAlarmexporting ? ChineseEnglishSize.ValidityAlarmexporting.descripts:'正在导出...')
                            }else {
                                this.setState({BottomState: false})
                                message.error(ChineseEnglishSize.ValidityAlarmexportFailure ? ChineseEnglishSize.ValidityAlarmexportFailure.descripts:'导出失败')
                            }
                        },
                        error: function (err) {
                            this.setState({BottomState: false})
                            // message.error(err.errorMessage);
                        }
                    });
                }else {
                    this.setState({BottomState: false})
                }
            })
        };

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

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

        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };
        render() {
            let {ChineseEnglishSize,userInfo} = this.state;
            const { getFieldDecorator } = this.props.form;
            //库存科室列表
            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="expiryDateAlertor">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.ValidityAlarmvalidityAlarm ? ChineseEnglishSize.ValidityAlarmvalidityAlarm.descripts:'效期报警'}</div>}
                        >
                            <Col span={19}>
                                <Form>
                                    <Col span={12}>
                                        <Row >
                                            <Col span={12}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.ValidityAlarmloc ? ChineseEnglishSize.ValidityAlarmloc.descripts:'科室'}>
                                                    {getFieldDecorator('Loc',{
                                                        initialValue: this.state.userInfo.locID ? this.state.userInfo.locID : undefined,
                                                        rules:[{ required : ChineseEnglishSize.ValidityAlarmloc ? ChineseEnglishSize.ValidityAlarmloc.required =='Y'? true:false: false, message: ChineseEnglishSize.ValidityAlarmloc ? ChineseEnglishSize.ValidityAlarmloc.message:'科室不能为空'}]
                                                    })(
                                                        <Select allowClear>
                                                            {inOpLocDrSelect}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={12} className="time">
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.ValidityAlarmendExpDate ? ChineseEnglishSize.ValidityAlarmendExpDate.descripts:'截止效期'}>
                                                    {getFieldDecorator('endExpDate',{
                                                        initialValue:  this.state.SelectData.params&&this.state.SelectData.params.endDate ? Moment(this.state.SelectData.params.endDate, 'YYYY-MM-DD') : Moment(),
                                                        rules:[{ required : ChineseEnglishSize.ValidityAlarmendExpDate ? ChineseEnglishSize.ValidityAlarmendExpDate.required =='Y'? true:false: false, message: ChineseEnglishSize.ValidityAlarmendExpDate ? ChineseEnglishSize.ValidityAlarmendExpDate.message:'截止效期不能为空'}]
                                                    })(
                                                        <DatePicker format="YYYY-MM-DD" />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row >
                                            <Col span={12}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.ValidityAlarmStkCat ? ChineseEnglishSize.ValidityAlarmStkCat.descripts:'库存大类'}>
                                                    {getFieldDecorator('stkCatID',{
                                                        initialValue: undefined,
                                                        rules:[{ required : ChineseEnglishSize.ValidityAlarmStkCat ? ChineseEnglishSize.ValidityAlarmStkCat.required =='Y'? true:false: false, message: ChineseEnglishSize.ValidityAlarmStkCat ? ChineseEnglishSize.ValidityAlarmStkCat.message:'库存大类不能为空'}]
                                                    })(
                                                        <Select allowClear>
                                                            {this.state.SelectData.stkCat && this.state.SelectData.stkCat.map((item, i) => {
                                                                return <Option value={item.id} key={i}>{item.descripts}</Option>
                                                            })}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={12}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.ValidityAlarmstkSubCatID ? ChineseEnglishSize.ValidityAlarmstkSubCatID.descripts:'库存子类'}>
                                                    {getFieldDecorator('stkSubCatID',{
                                                        initialValue: undefined,
                                                        rules:[{ required : ChineseEnglishSize.ValidityAlarmstkSubCatID ? ChineseEnglishSize.ValidityAlarmstkSubCatID.required =='Y'? true:false: false, message: ChineseEnglishSize.ValidityAlarmstkSubCatID ? ChineseEnglishSize.ValidityAlarmstkSubCatID.message:'库存子类不能为空'}]
                                                    })(
                                                        <Select allowClear>
                                                            {this.state.SelectData.stkSubCat && this.state.SelectData.stkSubCat.map((item, i) => {
                                                                return <Option value={item.id} key={i}>{item.descripts}</Option>
                                                            })}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Col>
                                    <Col span={12}>
                                        <Row >
                                            <Col span={11}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.ValidityAlarmincZeroBat ? ChineseEnglishSize.ValidityAlarmincZeroBat.descripts:'包括零批次'}>
                                                    {getFieldDecorator('incZeroBat',{
                                                        valuePropName: 'checked',
                                                        initialValue: false,
                                                        rules:[{required: false}]
                                                    })(
                                                        userInfo.language == 'EN' ?  <Switch checkedChildren="Yes" unCheckedChildren="No" /> : <Switch checkedChildren="是" unCheckedChildren="否" />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={11}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.ValidityAlarmexcNotFlag ? ChineseEnglishSize.ValidityAlarmexcNotFlag.descripts:'排除不可用项'}>
                                                    {getFieldDecorator('excNotFlag',{
                                                        valuePropName: 'checked',
                                                        initialValue: false,
                                                        rules:[{required: false}]
                                                    })(
                                                        userInfo.language == 'EN' ?  <Switch checkedChildren="Yes" unCheckedChildren="No" /> : <Switch checkedChildren="是" unCheckedChildren="否" />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row >
                                            <Col span={22}>
                                                <FormItem {...formItemSpan} label={ChineseEnglishSize.ValidityAlarmalarmDeadline ? ChineseEnglishSize.ValidityAlarmalarmDeadline.descripts:'报警期限时间'}>
                                                    {getFieldDecorator('restMonth',{
                                                        initialValue: undefined,
                                                        rules:[{ required : ChineseEnglishSize.ValidityAlarmalarmDeadline ? ChineseEnglishSize.ValidityAlarmalarmDeadline.required =='Y'? true:false: false, message: ChineseEnglishSize.ValidityAlarmalarmDeadline ? ChineseEnglishSize.ValidityAlarmalarmDeadline.message:'报警期限不能为空'}]
                                                    })(
                                                        <Select
                                                            mode="multiple"
                                                            style={{ width: '100%' }}
                                                        >
                                                            {this.state.SelectData.restMonth && this.state.SelectData.restMonth.map((item, i) => {
                                                                return <Option value={item.id} key={i}>{item.descripts}</Option>
                                                            })}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Col>
                                </Form>
                            </Col>
                            <Col span={5}>
                                <Row style={{marginBottom: '18px'}} className="button">
                                    <Button style={{marginRight: '30px'}} onClick={this.searchInformation}>{ChineseEnglishSize.ValidityAlarmsearch ? ChineseEnglishSize.ValidityAlarmsearch.descripts:'查询'}</Button>
                                    <Button type="primary" onClick={this.handleReset}>{ChineseEnglishSize.ValidityAlarmclean ? ChineseEnglishSize.ValidityAlarmclean.descripts:'清屏'}</Button>
                                </Row>
                                <Row style={{marginBottom: '18px'}} className="button">
                                    <iframe id="ifile" style={{display:'none'}}></iframe>
                                    <Button type="dashed" style={{ marginRight: '30px' }} onClick={this.printInfo}>{ChineseEnglishSize.ValidityAlarmprint ? ChineseEnglishSize.ValidityAlarmprint.descripts:'打印'}</Button>
                                    <Button type="dashed"  onClick={this.ExportData}>{this.state.BottomState ? '导出中...': ChineseEnglishSize.ValidityAlarmexport1 ? ChineseEnglishSize.ValidityAlarmexport.descripts:'导出'}</Button>
                                </Row>
                            </Col>
                        </Card>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.ValidityAlarmvalidityAlarmForm ? ChineseEnglishSize.ValidityAlarmvalidityAlarmForm.descripts:'效期报警单'}</div>}
                                extra={<span style={{color: '#666'}} className='span' onClick={() => { this.columnRef.onOpenModel();}}><Icon type="setting" title={ChineseEnglishSize.ValidityAlarmcolumnSettings ? ChineseEnglishSize.ValidityAlarmcolumnSettings.descripts:'列权限设置'} /></span>}
                            >
                                <div style={{position: 'relative'}}>
                                    <Table
                                        columns={this.state.columns.length>0 ? this.state.columns : this.columns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        scroll={{x: this.state.detailWidthTotal ? this.state.detailWidthTotal : 1600, y: store.getState().tableHeight.y - 38 }}
                                        rowKey={record => record.key}
                                        className="ExpiryHeight"
                                    />
                                    <span className='Total'>总金额： {this.state.allRpAmt}</span>
                                    <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)} pageSize={true} />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='ExpiryDateAlertorList'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns}
                    />
                </div>
            )
        }
    }
);
export default ExpiryDateAlertor;