//单号规则维护
import React from 'react';
import {
    Card, Input, Row, Col, Checkbox, Button, Pagination, Table, message, InputNumber, Form, Select, Tag
} from 'antd';
import { $http } from '../../../containers/config/https';
import '../../../assets/css/App.css'
import '../common/App.css'
import './style/index.less'
import store from 'store';
const FormItem = Form.Item;
let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};

const FormHandel = Form.create()(
    class AppCounter extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                page:1,
                pageSize:10,
                total:0,
                hospData:[],
                hospID:'',
                code:'',
                desc:'',
                rowId:'',
                saveCode: '',
                saveDesc: '', 
                saveHosp: false, 
                saveLoc: false, 
                savePrefix: '', 
                saveYear: false, 
                saveMonth: false, 
                saveDay: false, 
                saveLength: '',
                No:'',
            }
            // 表格的表头数据
            this.columns = [
                {
                    key: 'Code',
                    title: '代码',
                    dataIndex: 'Code',
                    width: "12%",
                    align: 'center'
                },{
                    key: 'Descripts',
                    title: '描述',
                    dataIndex: 'Descripts',
                    width: "18%",
                    align: 'center'
                },{
                    key: 'Hospital',
                    title: '医院',
                    dataIndex: 'Hospital',
                    width: "8%",
                    align: 'center'
                },{
                    key: 'Loc',
                    title: '科室',
                    dataIndex: 'Loc',
                    width: "8%",
                    align: 'center'
                },{
                    key: 'Prefix',
                    title: '前缀',
                    dataIndex: 'Prefix',
                    width: "8%",
                    align: 'center'
                },{
                    key: 'Year',
                    title: '年',
                    dataIndex: 'Year',
                    width: "8%",
                    align: 'center'
                },{
                    key: 'Month',
                    title: '月',
                    dataIndex: 'Month',
                    width: "8%",
                    align: 'center'
                },{
                    key: 'Day',
                    title: '日',
                    dataIndex: 'Day',
                    width: "8%",
                    align: 'center'
                },{
                    key: 'Length',
                    title: '序号长度',
                    dataIndex: 'Length',
                    width: "8%",
                    align: 'center'
                }];
        }

        componentDidMount() {
            this.loadInfo();//获取下拉框信息
            // 初始化列表数据
            this.handleQuery()
        }

        //获取下拉框信息
        loadInfo(){
            var params = [{}]
            $http.post('urlS', this, {
                code: "02010008",
                data: params,
                success: function (res) {
                    if (res.errorCode === '0') {
                        for(var j = 0; j < res.hospital.length; j++) {
                            this.state.hospData.push(<Select.Option value={res.hospital[j].id} key={j}>{res.hospital[j].descripts}</Select.Option>)
                        }
                        this.setState({
                            hospID:Number(user.hospID),
                        })
                    }
                }
            });
        }

        //获取单号预览
        getNoView = () => {
            if(Number(this.state.saveLength)>0){} else{
                this.setState({
                    No:'序号长度是必填项',
                })
                return;
            }
            let data = {}
            data={
                params: [{
                    code: this.state.saveCode,
                    desc:this.state.saveDesc,
                    hosp:this.state.saveHosp===true ? "Y": "N",
                    loc:this.state.saveLoc===true ? "Y": "N",
                    prefix:this.state.savePrefix,
                    year:this.state.saveYear===true ? "Y": "N",
                    month:this.state.saveMonth===true ? "Y": "N",
                    day:this.state.saveDay===true ? "Y": "N",
                    length:this.state.saveLength,
                    hospdr:this.state.hospID,
                }],
            }
            $http.post('urlS', this, {
                code: '02020175',
                data: data,
                success: function (res) {   
                    if (+res.errorCode === 0 ) {
                        this.setState({
                            No:res.result,
                        })
                    } else {

                    }
                }
            })
        }

        //处理多个input的公共方法
        onChangeInput(name, e){
            this.setState({
                [name]: e.target.value
            },()=>{
                if ((name==="savePrefix")||(name==="saveLength")) {
                    this.getNoView();
                }
            })
            if (e.target.value==="" && ((name==="code")||(name==="desc"))) {
                this.handleAllQuery();
            }
        }

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

        //处理多个checkbox的公共方法
        onChangeCheckbox(name, e){
            this.setState({
                [name]: e.target.checked
            },()=>{
                this.getNoView();
            })
        }

        Clear = () =>{
            this.setState({
                rowId: "",
                saveCode: '',
                saveDesc: '', 
                saveHosp: false ,
                saveLoc: false , 
                savePrefix: '', 
                saveYear: false ,  
                saveMonth: false ,  
                saveDay: false ,  
                saveLength: '', 
                No:'',
            });
        }

        //查询
        handleAllQuery = () => {
            this.setState({
                page:1,
            },()=>{
                this.handleQuery();
            })
        }

        // 查询
        handleQuery = () => {
            this.Clear();
            let data = {}
            data = {
                params: [{
                    Code: this.state.code,
                    Descripts: this.state.desc,
                    HospID:this.state.hospID ? this.state.hospID : user.hospID,
                }],
                pagination:[{ 
                    pageSize: this.state.pageSize,
                    currentPage: this.state.page,
                    sort: "ID",
                    dir: "desc"
                }]
            }
            $http.post('urlS', this, {
                code: '02010001',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        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})
                        message.success(res.errorMessage);
                    } else {
                        
                    }
                }
            })
        }

        // 保存
        handleSave = () => {
            if(this.state.saveCode==="") {message.warning("代码不能为空!");return;}
            if(this.state.saveDesc==="") {message.warning("描述不能为空!");return;}
            if(Number(this.state.saveLength)>0){} else{message.warning("序号长度必须大于0!");return;}
            let data = {}
            data={
                params: [{
                    ID: this.state.rowId,
                    code: this.state.saveCode,
                    desc:this.state.saveDesc,
                    hosp:this.state.saveHosp===true ? "Y": "N",
                    loc:this.state.saveLoc===true ? "Y": "N",
                    prefix:this.state.savePrefix,
                    year:this.state.saveYear===true ? "Y": "N",
                    month:this.state.saveMonth===true ? "Y": "N",
                    day:this.state.saveDay===true ? "Y": "N",
                    length:this.state.saveLength,
                    user:user.userID,
                    hospdr:this.state.hospID,
                }],
            }
            console.log(data)
            $http.post('urlS', this, {
                code: '02010002',
                data: data,
                success: function (res) {   
                    if (+res.errorCode === 0 ) {
                        message.success('保存成功');
                        this.handleQuery();
                    } else {

                    }
                }
            })
        }

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

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

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

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

        setRowClassName = (record) => {
            return record.ID === this.state.rowId ? 'clickRowStyle' : '';
        }

        onClickRow = (record) => {
            return {
                onClick: () => {
                    if(this.state.rowId===""){
                        this.setState({
                            rowId: record.ID,
                            saveCode: record.Code,
                            saveDesc: record.Descripts,
                            saveHosp: record.Hospital==="Y" ? true:false,
                            saveLoc: record.Loc==="Y" ? true:false,
                            savePrefix: record.Prefix,
                            saveYear: record.Year==="Y" ? true:false,
                            saveMonth: record.Month==="Y" ? true:false, 
                            saveDay: record.Day==="Y" ? true:false,
                            saveLength: record.Length,
                        },()=>{
                            this.getNoView();
                        });
                    }else{
                        if(this.state.rowId!==record.ID){
                            this.setState({
                                rowId: record.ID,
                                saveCode: record.Code,
                                saveDesc: record.Descripts,
                                saveHosp: record.Hospital==="Y" ? true:false,
                                saveLoc: record.Loc==="Y" ? true:false,
                                savePrefix: record.Prefix,
                                saveYear: record.Year==="Y" ? true:false,
                                saveMonth: record.Month==="Y" ? true:false, 
                                saveDay: record.Day==="Y" ? true:false,
                                saveLength: record.Length
                            },()=>{
                                this.getNoView();
                            });
                        }else{
                            this.Clear();
                        }
                    } 
                },
            };
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            let formItemLayout = {
                labelCol: { span: 6 },
                wrapperCol: { span: 18 }
            };
            return (
                <div>
                    <Row>
                        <Card  
                            size="small"
                            title="业务单号规则维护"
                            headStyle={{background: 'rgba(100,169,130,1)'}}
                        >
                            <Row>
                                <Form>
                                    <Col span={4}>
                                        <FormItem {...formItemLayout} label='医院'>
                                            {getFieldDecorator('hospID', {
                                                initialValue:this.state.hospID ? this.state.hospID : user.hospID,
                                                rules: [{ required: true, message: '医院是必填项,请选择！' }]
                                                })(
                                                    <Select
                                                        optionFilterProp="children" 
                                                        onChange={this.selectOnChange.bind(this,"hospID")}
                                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                    >
                                                    {this.state.hospData}
                                                    </Select>
                                                )}
                                        </FormItem>
                                    </Col>
                                    <Col span={4}>
                                        <FormItem {...formItemLayout} label='代码'>
                                            {getFieldDecorator('code', {
                                                initialValue:this.state.code,
                                                rules: [{ required: false, message: '代码是必填项,请选择！' }]
                                                })(
                                                    <Input 
                                                        allowClear={true}
                                                        onChange={this.onChangeInput.bind(this,"code")}
                                                        onPressEnter={() => this.handleAllQuery()}
                                                    />
                                                )}
                                        </FormItem>
                                    </Col>
                                    <Col span={4}>
                                        <FormItem {...formItemLayout} label='描述'>
                                            {getFieldDecorator('desc', {
                                                initialValue:this.state.desc,
                                                rules: [{ required: false, message: '描述是必填项,请选择！' }]
                                                })(
                                                    <Input 
                                                        allowClear={true}
                                                        onChange={this.onChangeInput.bind(this,"desc")}
                                                        onPressEnter={() => this.handleAllQuery()}
                                                    />
                                                )}
                                        </FormItem>
                                    </Col>
                                    <Col span={6}>
                                        <FormItem>
                                            <Button style={{ marginLeft: '40px', background: 'rgba(100,169,130,1)',color:'#ffffff'}}  onClick={this.handleAllQuery}>查询</Button>
                                            <Button style={{ marginLeft: '60px', background: 'rgba(100,169,130,1)',color:'#ffffff'}}  onClick={this.handleSave}>保存</Button>
                                            <Button style={{ marginLeft: '60px', background: 'rgba(255,0,0,1)',color:'#ffffff'}}  onClick={this.handleClear}>清屏</Button>
                                        </FormItem>
                                    </Col>
                                    <Col span={5}>
                                        <FormItem>
                                            <Tag style={{ width:'90%',marginLeft: '25px',marginTop:'2px',fontSize:"12pt"}} color="green">{'单号预览：'+ (this.state.No?this.state.No:'')}</Tag>
                                        </FormItem>
                                    </Col>
                                </Form>
                            </Row>
                            <Card bodyStyle={{padding:'8px'}}>
                                <Row>
                                    <Input 
                                        style={{ width: '13.7%'}}
                                        placeholder="代码"
                                        allowClear={true}
                                        value={this.state.saveCode}
                                        onChange={this.onChangeInput.bind(this,"saveCode")}
                                    />
                                    <Input 
                                        style={{ width: '20.7%',paddingLeft: '0.3%'}}
                                        placeholder="描述"
                                        allowClear={true}
                                        value={this.state.saveDesc}
                                        onChange={this.onChangeInput.bind(this,"saveDesc")}
                                    />
                                    <Checkbox 
                                        style={{width: '8%',paddingLeft: '4.2%'}} 
                                        checked={this.state.saveHosp}
                                        onChange={this.onChangeCheckbox.bind(this,"saveHosp")} 
                                    />
                                    <Checkbox 
                                        style={{width: '8%',paddingLeft: '4.9%'}} 
                                        checked={this.state.saveLoc}
                                        onChange={this.onChangeCheckbox.bind(this,"saveLoc")} 
                                    />
                                    <Input 
                                        style={{ width: '10.2%',marginLeft: '1.5%'}}
                                        placeholder="前缀"
                                        allowClear={true}
                                        value={this.state.savePrefix}
                                        onChange={this.onChangeInput.bind(this,"savePrefix")}
                                    />
                                    <Checkbox 
                                        style={{width: '8%',paddingLeft: '3.6%'}} 
                                        checked={this.state.saveYear}
                                        onChange={this.onChangeCheckbox.bind(this,"saveYear")} 
                                    />
                                    <Checkbox 
                                        style={{width: '8%',paddingLeft: '4.35%'}} 
                                        checked={this.state.saveMonth}
                                        onChange={this.onChangeCheckbox.bind(this,"saveMonth")} 
                                    />
                                    <Checkbox 
                                        style={{width: '8%',paddingLeft: '5%'}} 
                                        checked={this.state.saveDay}
                                        onChange={this.onChangeCheckbox.bind(this,"saveDay")} 
                                    />
                                    <Input 
                                        style={{ width: '10.5%',marginLeft: '1.5%'}}
                                        placeholder="序号长度"
                                        allowClear={true}
                                        value={this.state.saveLength}
                                        onChange={this.onChangeInput.bind(this,"saveLength")}
                                    />
                                </Row>
                                <Row style={{marginTop:'8px'}}>
                                    <Table
                                        dataSource={this.state.data}
                                        columns={this.columns}
                                        rowClassName={this.setRowClassName}
                                        pagination={false}
                                        bordered
                                        onRow={this.onClickRow}
                                        scroll={{ y: store.getState().tableHeight.y - 20}}
                                        style={{height: (store.getState().tableHeight.y + 15 )}}
                                    />
                                    {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                                    <Pagination
                                        showTotal={() => this.showTotal(this.state.total)}
                                        size="small"
                                        showQuickJumper
                                        showSizeChanger
                                        defaultCurrent={1}
                                        current={this.state.page}
                                        total={this.state.total}
                                        onChange={this.PageChange}
                                        onShowSizeChange={this.onShowSizeChange}
                                        style={{textAlign: "right", marginTop: '15px'}}
                                    />
                                </Row>
                            </Card>
                        </Card>
                    </Row>
                </div>
            )
        }
    }
);
export default Form.create()(FormHandel);