// 库存项关联收费项
import React from 'react';
import { Button, Modal, Form, Row ,Col ,message ,Select ,DatePicker ,Card ,Pagination, Table} from 'antd';
import { $http } from '../../../containers/config/https';
import '../druginfo/Maintenance.css'
import moment from 'moment'
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
const Option = Select.Option;
const FormItem = Form.Item;

class StockLinkCharge extends React.Component {
    constructor(props) {
        super(props)
        this.state = { 
            chargeItemData:[],
            page:1,
            pageSize:10,
            total:0,
        }

        this.columns = [
			{
                key: 'Code',
                title: '收费项代码',
                dataIndex: 'Code',
                width: "10%",
                align: 'center'
            },{
                key: 'Descripts',
                title: '收费项描述',
                dataIndex: 'Descripts',
                width: "20%",
                align: 'center'
            },{
                key: 'Uom',
                title: '单位',
                dataIndex: 'Uom',
                width: "10%",
                align: 'center'
            },{
                key: 'Qty',
                title: '数量',
                dataIndex: 'Qty',
                width: "10%",
                align: 'center'
            },{
                key: 'Price',
                title: '价格',
                dataIndex: 'Price',
                width: "10%",
                align: 'center'
            },{
                key: 'StartDate',
                title: '生效日期',
                dataIndex: 'StartDate',
                width: "15%",
                align: 'center'
            },{
                key: 'StopDate',
                title: '失效日期',
                dataIndex: 'StopDate',
                width: "15%",
                align: 'center'
            }];
    }

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

    //获取下拉框信息
    loadInfo(){
        let data = {
            params: [{
                Code: '',
                Descripts: '',
                FindType: '',
                TypeID: '',
                Alias: '',
                include:"",
                hospitalId:"",
                include:"combo",
            }],
            pagination:[{
                pageSize: 0,
                currentPage: 0,
                sortColumn: "Code",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "05100010",
            data: data,
            success: function (res) {
                if (res.errorCode === '0') {
                    var j=0
                    for(j = 0; j < res.result.Data.length; j++) {
                        this.state.chargeItemData.push(<Option value={res.result.Data[j].ID} key={j}>{res.result.Data[j].ItemDesc}</Option>)
                    }
                }
            }
        });
    }

     // 显示弹出层
     showModal = () => {
        this.setState({
            visible: true,
        });
    }

    // 重置表单
    resetFields(){
        // console.log("触发了")
        this.props.form.resetFields(); //清空所有
    }

    // 取消
    handleCancel = () => {
        this.resetFields();
        this.setState({
            visible: false,
        });
    }

    //处理多个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: '',
            chargeItem:'',
            startDate:moment(new Date(), 'YYYY-MM-DD'),
            stopDate:null,
        })
        this.props.form.resetFields();
    }

    // 查询
    handleQuery = () => {
        if(parseInt(this.state.stockItemID)>0){
            let data = {}
            data={
                params: [{
                    stockItemID: this.state.stockItemID,
                    userDr:1,
                    hospDr:1,
                }],
                pagination:[{
                    pageSize: this.state.pageSize,
                    currentPage: this.state.page,
                    sort: "ID",
                    dir: "desc"
                }]
            }
            $http.post('urlS', this, {
                code: "02020037",
                data: data,
                success: function (res) {
                    console.log(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: '',
                            chargeItem:'',
                            startDate:moment(new Date(), 'YYYY-MM-DD'),
                            stopDate:null,
                        })
                        this.props.form.resetFields();
                    }
                }
            });
        }else{

        }
    }

    // 保存
    handleSave = () => {
        if(parseInt(this.state.stockItemID)>0){
            if(this.state.chargeItem===""){
                message.warning('收费项不能为空!!');
                return;
            }
            if(this.state.startDate===""){
                message.warning('生效日期不能为空!!');
                return;
            }
            let data = {}
            data={
                params: [{
                    ID: this.state.selectID,
                    stockItemID: this.state.stockItemID,
                    chargeItemID: this.state.chargeItem,
                    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:'',
                    userDr:1,
                    hospDr:1,
                }],
            }
            $http.post('urlS', this, {
                code: "02020036",
                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,
                        chargeItem:record.ChargeItemID,
                        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,
                            chargeItem:record.ChargeItemID,
                            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: () => {
                
            }
        };
    }


    //清空
    handleClear = () => {
        this.Clear();
    }

    render() {
        const { getFieldDecorator } = this.props.form;

        let formItemLayout = {
            labelCol: { span: 10 },
            wrapperCol: { span: 14 }
        };
        let formItemLayout2 = {
            labelCol: { span: 8 },
            wrapperCol: { span: 16 }
        };
        return (
            <Modal
                visible={this.state.visible}
                title="库存项关联收费项"
                width="1000px"
                onCancel={this.handleCancel}
                footer={[
                    <Button key="onCancel" onClick={this.handleCancel}>返回</Button>,
                ]}
            >
            <div style={{height:'370px'}}>
                <Form>
                    <Card bodyStyle={{padding:'5px',paddingTop:'15px'}}>
                        <Row>
                            <Col span={7}>
                                <FormItem {...formItemLayout2} label='收费项'>
                                    {getFieldDecorator('ChargeItem', {
                                        initialValue:this.state.chargeItem,
                                        rules: [{ required: true, message: '收费项是必填项,请选择！' }]
                                        })(
                                            <Select
                                                allowClear={true}
                                                showSearch 
                                                optionFilterProp="children" 
                                                onChange={this.selectOnChange.bind(this,"chargeItem")}
                                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                            >
                                            {this.state.chargeItemData}
                                            </Select>
                                        )}
                                </FormItem>
                            </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={5}>
                                <Button style={{ marginLeft: '20px',marginTop:'2px', background: '#1999db',color:'#ffffff'}}  onClick={this.handleSave}>保存</Button>
                                <Button style={{ marginLeft: '20px',marginTop:'2px', background: 'rgba(255,0,0,1)',color:'#ffffff'}}  onClick={this.handleClear}>清空</Button>
                            </Col>
                        </Row>
                    </Card>
                        <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>
                </Form>
            </div>
            </Modal>
        )
    }
}
export default Form.create()(StockLinkCharge);