//发药单位维护
import React from 'react';
import {
    Form,Row,Input,Col,Button,Select,Card,Table,Pagination,message,DatePicker
} from 'antd';
import '../../../assets/css/App.css'
import { $http } from '../../../containers/config/https';
import moment from 'moment'
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
const FormItem = Form.Item;
const Option = Select.Option;

const FormHandel = Form.create()(
    class extends React.Component {
        constructor(props) {
            super(props)
            this.state = { 
                uomData:[],
                locData:[],
                total: 0,
                page: 1,
                pageSize: 10,
            }
            this.columns = [
                {
                    key: 'dispLoc',
                    title: '发药科室',
                    dataIndex: 'dispLoc',
                    width: "25%",
                    align: 'center'
                },{
                    key: 'dispUom',
                    title: '发药单位',
                    dataIndex: 'dispUom',
                    width: "20%",
                    align: 'center'
                },{
                    key: 'factor',
                    title: '转换系数',
                    dataIndex: 'factor',
                    width: "15%",
                    align: 'center'
                },{
                    key: 'startDate',
                    title: '生效日期',
                    dataIndex: 'startDate',
                    width: "20%",
                    align: 'center'
                },{
                    key: 'stopDate',
                    title: '失效日期',
                    dataIndex: 'stopDate',
                    width: "20%",
                    align: 'center'
                }];
        }

        componentDidMount() {
            this.props.onRef(this);
            this.loadInfo(); //获取下拉框信息
        }

        //获取下拉框信息
        loadInfo(){
            var params = [{}]
            $http.post('urlS', this, {
                code: "02020032",
                data: params,
                success: function (res) {
                    if (res.errorCode === '0') {
                        var j=0
                        for(j = 0; j < res.uom.length; j++) {
                            this.state.uomData.push(<Option value={res.uom[j].id} key={j}>{res.uom[j].descripts}</Option>)
                        }
                        for(j = 0; j < res.loc.length; j++) {
                            this.state.locData.push(<Option value={res.loc[j].id} key={j}>{res.loc[j].descripts}</Option>)
                        }
                    }
                }
            });
        }

        //处理多个input的公共方法
        onChangeInput(name, e){
            this.setState({
                [name]: e.target.value
            })
        }

        ///处理多个select下拉的公共方法
        selectOnChange=(name,value,option)=>{
            if(value){
                this.setState({
                    [name]:value,
                })
            }else{
                this.setState({
                    [name]:'',
                })
            }
        }

        // 时间
        dateOnChange = (name,date, dateString)=> {
            this.setState({
                [name]: dateString,
            })
        }

        // 清空
        Clear = () => {
            this.setState({
                selectID: '',
                dispLoc:'',
                dispUom:'',
                factor:'',
                startDate:moment(new Date(), 'YYYY-MM-DD'),
                stopDate:null,
            })
            this.props.form.resetFields();
        }

        // 查询
        handleQuery = () => {
            if(parseInt(this.state.stockID)>0){
                let data = {}
                data={
                    params: [{
                        stockID: this.state.stockID,
                        dispLocID: this.state.dispLoc,
                    }],
                    pagination:[{
                        pageSize: this.state.pageSize,
                        currentPage: this.state.page,
                        sort: "ID",
                        dir: "desc"
                    }]
                }
                $http.post('urlS', this, {
                    code: "02020035",
                    data: data,
                    success: function (res) {
                        if (res.errorCode === '0') {
                            for(var i = 0; i < res.result.rows.length; i++) {
                                res.result.rows[i].key = i
                            }
                            this.setState({
                                data: res.result.rows, 
                                total: res.result.total,
                                selectID:'',
                                dispLoc:'',
                                dispUom:'',
                                factor:'',
                                startDate:moment(new Date(), 'YYYY-MM-DD'),
                                stopDate:null,
                            })
                            this.props.form.resetFields();
                        }
                    }
                });
            }else{

            }
        }

        // 保存
        handleSave = () => {
            if(parseInt(this.state.stockID)>0){
                if(this.state.dispLoc===""){
                    message.warning('发药科室不能为空!!');
                    return;
                }
                if(this.state.dispUom===""){
                    message.warning('发药单位不能为空!!');
                    return;
                }
                if(Number(this.state.factor)===0){
                    message.warning('转换系数不能为0!!');
                    return;
                }
                if(this.state.startDate===""){
                    message.warning('生效日期不能为空!!');
                    return;
                }
                let data = {}
                data={
                    params: [{
                        stockID: this.state.stockID,
                        ID: this.state.selectID,
                        dispLocID: this.state.dispLoc,
                        dispUomID: this.state.dispUom,
                        factor: this.state.factor,
                        startDate: this.state.startDate?moment(this.state.startDate).utcOffset(480).format('YYYY-MM-DD'):moment(new Date()).utcOffset(480).format('YYYY-MM-DD'),
                        stopDate: this.state.stopDate?this.state.stopDate:'',
                    }],
                }
                $http.post('urlS', this, {
                    code: "02020033",
                    data: data,
                    success: function (res) {
                        if (res.errorCode === '0') {
                            message.success('保存成功');
                            this.handleQuery();
                        }
                    }
                });
            }else{
                message.warning('请先保存库存项信息!');
                return;
            }
        }

        //删除
        handleDelete = ()=>{
            if(parseInt(this.state.selectID)>0){
                let data = {}
                data={
                    params: [{
                        ID: this.state.selectID,
                        userDr:1,
                        hospDr:1,
                    }],
                }
                $http.post('urlS', this, {
                    code: "02020034",
                    data: data,
                    success: function (res) {
                        if (res.errorCode === '0') {
                            message.success('删除成功');
                            this.handleQuery();
                        }
                    }
                });
            }else{
                message.warning('请先选择记录再删除信息!');
                return;
            }
        }

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

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

        setRowClassName = (record) => {
            return record.ID === this.state.selectID ? 'clickRowStyle' : '';
        }
    
        onClickRow = (record) => {
            return {
                onClick: () => {
                    this.Clear();
                    if(this.state.selectID===""){
                        this.setState({
                            selectID: record.ID,
                            dispLoc:record.dispLocDr,
                            dispUom:record.dispUomDr,
                            factor:record.factor,
                            startDate:record.startDate!==""?moment(record.startDate).utcOffset(480).format('YYYY-MM-DD'):null,
                            stopDate:record.stopDate!==""?moment(record.stopDate).utcOffset(480).format('YYYY-MM-DD'):null,
                        });
                    }else{
                        if(this.state.selectID!==record.ID){
                            this.setState({
                                selectID: record.ID,
                                dispLoc:record.dispLocDr,
                                dispUom:record.dispUomDr,
                                factor:record.factor,
                                startDate:record.startDate!==""?moment(record.startDate).utcOffset(480).format('YYYY-MM-DD'):null,
                                stopDate:record.stopDate!==""?moment(record.stopDate).utcOffset(480).format('YYYY-MM-DD'):null,
                            });
                        }else{
                            this.Clear();
                        }
                    }
                },
                onDoubleClick: () => {
                    
                }
            };
        }
        render() {
            const { getFieldDecorator } = this.props.form;

            let formItemLayout = {
                labelCol: { span: 10 },
                wrapperCol: { span: 14 }
            };
            return (
                <div>
                    <Form>
                        <Card bodyStyle={{padding:'5px'}}>
                            <Row>
                                <Col span={6}>
                                    <FormItem {...formItemLayout} label='发药科室'>
                                        {getFieldDecorator('DispLoc', {
                                            initialValue:this.state.dispLoc,
                                            rules: [{ required: true, message: '发药科室是必填项,请选择！' }]
                                            })(
                                                <Select
                                                    allowClear={true}
                                                    showSearch 
                                                    optionFilterProp="children" 
                                                    onChange={this.selectOnChange.bind(this,"dispLoc")}
                                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                >
                                                {this.state.locData}
                                                </Select>
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={6}>
                                    <FormItem {...formItemLayout} label='发药单位'>
                                        {getFieldDecorator('DispUom', {
                                            initialValue:this.state.dispUom,
                                            rules: [{ required: true, message: '发药单位是必填项,请选择！' }]
                                            })(
                                                <Select
                                                    allowClear={true}
                                                    showSearch 
                                                    optionFilterProp="children" 
                                                    onChange={this.selectOnChange.bind(this,"dispUom")}
                                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                >
                                                {this.state.uomData}
                                                </Select>
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={6}>
                                    <FormItem {...formItemLayout} label='转换系数'>
                                        {getFieldDecorator('Factor', {
                                            initialValue:this.state.factor,
                                            rules: [{ required: true, message: '转换系数是必填项,请选择！' }]
                                            })(
                                                <Input 
                                                    onChange={this.onChangeInput.bind(this,"factor")}
                                                />
                                            )}
                                    </FormItem>
                                </Col>
                                
                                <Col span={6}>
                                    <Button style={{ marginLeft: '50px',marginTop:'2px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleSave}>保存</Button>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={6}></Col>
                                <Col span={6}>
                                    <FormItem {...formItemLayout} label='生效日期'>
                                        {getFieldDecorator('StartDate', {
                                            initialValue:this.state.startDate?moment(this.state.startDate, 'YYYY-MM-DD'):moment(new Date(), 'YYYY-MM-DD'),
                                            rules: [{ required: true, message: '生效日期是必填项,请选择！' }]
                                            })(
                                                <DatePicker
                                                    onChange={this.dateOnChange.bind(this,"startDate")}
                                                    format="YYYY-MM-DD" 
                                                    style={{width:'100%'}}
                                                >
                                                </DatePicker>
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={6}>
                                    <FormItem {...formItemLayout} label='失效日期'>
                                        {getFieldDecorator('StopDate', {
                                            initialValue:this.state.stopDate?moment(this.state.stopDate, 'YYYY-MM-DD'):null,
                                            rules: [{ required: false, message: '失效日期是必填项,请选择！' }]
                                            })(
                                                <DatePicker
                                                    onChange={this.dateOnChange.bind(this,"stopDate")}
                                                    format="YYYY-MM-DD" 
                                                    style={{width:'100%'}}
                                                >
                                                </DatePicker>
                                            )}
                                    </FormItem>
                                </Col>
                                
                                <Col span={6}>
                                    <Button style={{ marginLeft: '50px',marginTop:'2px', background: 'rgba(255,0,0,1)',color:'#ffffff'}}  onClick={this.handleDelete}>删除</Button>
                                </Col>
                            </Row>
                        </Card>
                        <Row type="flex" justify="space-between">
                            <Card bodyStyle={{padding:'10px'}}>
                                <div>
                                    <Table
                                        dataSource={this.state.data}
                                        columns={this.columns}
                                        rowClassName={this.setRowClassName}
                                        pagination={false}
                                        bordered
                                        onRow={this.onClickRow}
                                        rowKey="ID"
                                        style={{height:'260px',width:'900px'}}
                                        scroll={{ x:this.state.TableWidth, y: '215px' }}
                                    
                                    />
                                    {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                                    <Pagination
                                        size="small"
                                        showQuickJumper
                                        showSizeChanger
                                        defaultCurrent={1}
                                        current={this.state.page}
                                        total={this.state.total}
                                        onChange={this.PageChange}
                                        onShowSizeChange={this.onShowSizeChange}
                                        style={{textAlign: "right", marginTop: '5px'}}
                                    />
                                </div>
                            </Card>
                        </Row>
                    </Form>
                </div>
            )
        }
    }
);
export default FormHandel;