//配药窗口维护
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Checkbox, Table, Input, message, Pagination  } from 'antd';
import CommonPagination from 'components/pagination/index';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import './style/index.less';

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:7 },
    wrapperCol: { span: 16 },
};

const PrepareWin = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                SelectData: {},
                inOpLocDr:'',
                vendor: '',
                detailsId: '',//配药列表ID
                WaListData: [], //入库单数据
                pageSize: 10,
                page: 1,
                rowId: '', //行选中高亮id
                total:0,
                warehouseListId: '',
                locData: ''
            }
            // 配药表头
            this.columns = [
                {
                    key: 1,
                    title: '药房名称',
                    dataIndex: 'locDesc',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 2,
                    title: '序号',
                    dataIndex: 'seqNo',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 3,
                    title: '窗口代码',
                    dataIndex: 'prepWinCode',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 4,
                    title: '窗口名称',
                    dataIndex: 'prepWinDesc',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 5,
                    title: 'IP地址',
                    dataIndex: 'ipAddress',
                    align: "center",
                    width: '12%'
                },
                {
                    key: 6,
                    title: '生效日期',
                    dataIndex: 'startDate',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 7,
                    title: '失效日期',
                    dataIndex: 'endDate',
                    align: "center",
                    width: '14%'
                }
            ]
        }

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

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

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

        // 获取配药窗口列表
        getWarehouseList=()=>{
            this.setState({loading: true})
            let inOpLocDr = this.props.form.getFieldValue('locDr');
            let data = {
                params: [{
                    locID:inOpLocDr ? inOpLocDr :this.state.locData,
                }],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                        sort:"ID",
                        dir:"asc",
                    }
                ],
            };
            if(inOpLocDr){
                $http.post('urlS', this, {
                    code: "02030003",
                    data: data,
                    success: function (res) {
                        if(res.result.rows.length > 0){
                            for(let i = 0; i < res.result.rows.length; i++){
                                res.result.rows[i].key = i;
                            }
                            this.setState({ WaListData: res.result.rows,total: res.result.total, loading : false});

                        }else {
                            this.setState({detailsListData: [], WaListData: []});
                            message.error("没数据")
                        }
                    },
                    error: function (err) {
                        message.error(err.errorMessage)
                    }
                });
            }else {
                message.error('请选择科室')
            }

        };

        // 保存
        approveDetermine=()=>{

            let locDr = this.props.form.getFieldValue('locDr');
            let seqNo = this.props.form.getFieldValue('seqNo');
            let code = this.props.form.getFieldValue('code');
            let desc = this.props.form.getFieldValue('desc');
            let ipAddress = this.props.form.getFieldValue('ipAddress');
            let StartDate = this.props.form.getFieldValue('StartDate');
            let EndDate = this.props.form.getFieldValue('EndDate');
            let data = {
                params: [{
                    prepWinID:this.state.detailsId ? this.state.detailsId : '',
                    locID: locDr ? locDr : '',
                    seqNo:seqNo ? seqNo : '',
                    prepWinCode:code ? code : '',
                    prepWinDesc:desc ? desc : '',
                    ipAddress:ipAddress ? ipAddress : '',
                    startDate:StartDate ? Moment(StartDate).format('YYYY-MM-DD') : '',
                    endDate:EndDate ? Moment(EndDate).format('YYYY-MM-DD') : '',

                }]
            };
            if(locDr && code && desc && StartDate){
                $http.post('urlS', this, {
                    code: "02030002",
                    data: data,
                    success: function (res) {
                        if(+res.errorCode == '0'){
                            this.getWarehouseList();
                            this.props.form.setFieldsValue({
                                ID: '',
                                seqNo: '',
                                code: '',
                                ipAddress: '',
                                desc: '',
                                StartDate:Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                EndDate:undefined,
                            });
                            this.setState({rowId: ''});
                            message.success(res.errorMessage);
                        }
                    },
                    error: function (err) {
                        message.error('保存失败');
                    }
                });
            }else {
                message.error('必填选项缺漏')
            }

        };

        //获取选中列表数据
        getListDate = (id) => {

            let data = {
                params: [{
                    prepWinID:id,
                }]
            };
            $http.post('urlS', this, {
                code: "02030004",
                data: data,
                success: function (res) {
                    if(res.result.length > 0){
                        this.props.form.setFieldsValue({
                            seqNo:res.result[0].seqNo,
                            code:res.result[0].prepWinCode,
                            ipAddress:res.result[0].ipAddress,
                            desc:res.result[0].prepWinDesc,
                            StartDate:res.result[0].startDate !=='' ? Moment(res.result[0].startDate, 'YYYY-MM-DD') : Moment(Moment().format('L'), 'YYYY-MM-DD'),
                            EndDate:res.result[0].endDate !=='' ? Moment(res.result[0].endDate, 'YYYY-MM-DD') : undefined,
                        });

                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };

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

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

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

        //添加样式高亮
        setRowClassName=(record)=>{
            return record.prepWinID === this.state.rowId ? 'clickRowStyle' : '';
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.state.userInfo ? this.state.userInfo: {};
            //入库部门列表
            let inOpLocDrSelect = [];
            this.state.SelectData.length > 0 && this.state.SelectData.map((item, i) => {
                inOpLocDrSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });

            return (
                <div className="PrepareWin">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>配药窗口维护</div>}
                        >
                            <Col span={20}>
                                <Form>
                                    <Row >
                                        <Row>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="药房科室">
                                                    {getFieldDecorator('locDr',{
                                                        initialValue: undefined,
                                                        rules:[{ required : true, message: '药房不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch onChange={(data) => {this.setState({locData: data}, () => {this.getWarehouseList()})}}>
                                                            {inOpLocDrSelect}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="序号">
                                                    {getFieldDecorator('seqNo',{
                                                        initialValue: undefined,
                                                        rules:[{required: false,message: '序号不能为空'}]
                                                    })(
                                                       <Input />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="窗口代码">
                                                    {getFieldDecorator('code',{
                                                        initialValue: undefined,
                                                        rules:[{required: true,message: '窗口代码不能为空'}]
                                                    })(
                                                        <Input />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="窗口名称">
                                                    {getFieldDecorator('desc',{
                                                        initialValue: undefined,
                                                        rules: [{ required: true, message: '窗口名称不能为空' }],
                                                    })(
                                                        <Input />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="IP地址">
                                                    {getFieldDecorator('ipAddress',{
                                                        initialValue: undefined,
                                                        rules:[{required: false,message: 'IP地址不能为空'}]
                                                    })(
                                                        <Input />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="生效日期">
                                                    {getFieldDecorator('StartDate',{
                                                        initialValue: Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                        rules:[{required: true,message: '有效时间不能为空'}]
                                                    })(
                                                        <DatePicker  disabledDate={(curDate) => {
                                                            return curDate && curDate > Moment().endOf('day');
                                                        }} />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="失效日期">
                                                    {getFieldDecorator('EndDate',{
                                                        initialValue: undefined,
                                                        rules:[{required: false}]
                                                    })(
                                                        <DatePicker  disabledDate={(curDate) => {
                                                            return curDate && curDate > Moment().endOf('day');
                                                        }} />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={3}>
                                <Row style={{marginBottom: '18px',paddingLeft: '40px',marginTop: '4px'}}>
                                    <Button style={{marginRight: '30px'}} onClick={this.getWarehouseList}>查询</Button>
                                    <Button type="primary" onClick={this.handleReset}>清屏</Button>
                                </Row>
                                <Row style={{paddingLeft: '40px'}}>
                                    <Button type="primary"  style={{marginRight: '30px'}} onClick={this.approveDetermine}>保存</Button>
                                </Row>
                            </Col>

                        </Card>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>配药窗口列表</div>}
                            >
                                <div>
                                    <Table
                                        columns={this.columns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        scroll={{ y:  store.getState().tableHeight.y - 70 }}
                                        rowKey={record => record.key}
                                        rowClassName={this.setRowClassName}
                                        className="PrdetailsHeight"
                                        onRow={(record) => {
                                            return {
                                                onClick: () => {
                                                    this.setState({detailsId: record.prepWinID});
                                                    if (this.state.rowId === '') {
                                                        // 保存行数据以及ID
                                                        this.setState({rowId: record.prepWinID});
                                                        this.getListDate(record.prepWinID);
                                                    } else {
                                                        if (this.state.rowId !== record.prepWinID) {
                                                            this.setState({rowId: record.prepWinID});
                                                            this.getListDate(record.prepWinID);
                                                        } else {
                                                            this.setState({rowId: '', detailsId: ''});
                                                            this.props.form.setFieldsValue({
                                                                ID: '',
                                                                seqNo: '',
                                                                code: '',
                                                                ipAddress: '',
                                                                desc: '',
                                                                StartDate:Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                                EndDate:undefined,
                                                            });
                                                        }
                                                    }
                                                },

                                            };
                                        }}
                                    />
                                    <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>

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