/**
 * 排班时间段
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, TimePicker,
    DatePicker, Button, Popconfirm, Icon, Divider, message, Pagination, Tag
} from 'antd';
import moment from 'moment';
import { $http } from 'containers/config/https';
import { dayFormat, timeFormat,Util } from 'tools/index';
import { TIME_INTERVAL_STATUS } from 'tools/statusConstants';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import './style/index.less';
import store from 'store';

const FormItem = Form.Item;
const Option = Select.Option;

class TimeSlot extends React.Component {

    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            hospital: [],
            dataSource: [],
            hospitalData: [],
            timeRange: [],
            sumData: [],
            timeStatus: [{ "id": "1", "descripts": "生效" }, { "id": "2", "descripts": "失效" }, { "id": "3", "descripts": "全部" }],
            statusID: "1",
            userData: userData,
            editStatus: false,
            startTime: '00:00',
            endTime: '00"00',
            userData: userData,
            timeRangeId: '',
            stopDate: ''
        }
    }

    componentDidMount() {
        // this.loadData(1);
        this.initData();
        this.loadHospitalMsg();//获取医院信息
        this.loadTimeRange(this.state.dataSource.hospID)
    }

    initData() {
        // var date = new Date();
        let data = {
            params: [{
                compontName: "TimeSlot",
                type: "C",
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    var columns = res.result.C;
                    var dynColumns = []
                    for (var i = 0; i < columns.length; i++) {
                        if (columns[i].dataIndex == 'timeRange') {
                            dynColumns.push({
                                title: columns[i].title,
                                dataIndex: columns[i].dataIndex,
                                width: parseInt(columns[i].width),
                                align: columns[i].align || 'center',
                                render: (text, data) => {
                                    return <span style={{color:'orange'}}>{data.timeRange}</span>
                                }
                            })
                        } else {
                            dynColumns.push({
                                title: columns[i].title,
                                dataIndex: columns[i].dataIndex,
                                width: parseInt(columns[i].width),
                                align: columns[i].align || 'center',
                            })
                        }
                    }
                }
                var colimns = [{
                    title: '操作',
                    dataIndex: 'operation',
                    width: 120,
                    align: 'center',
                    render: (text, data) => {
                        return (
                            data.status == '失效' ? null : <span>
                                {/* <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                                <span className='span' onClick={this.editData.bind(this, data)}>编辑</span>
                                <Divider type="vertical" /> */}
                                <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                                <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDel.bind(this, data)} >
                                    <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                                </Popconfirm>
                            </span >
                        )
                    }
                }]
                this.setState({
                    column: dynColumns.concat(colimns),
                })
                this.props.hanlderThis.setState({
                    reload: false,
                })
            }
        }
        )

    }

    //初始化数据
    loadData(page) {
        // this.props.form.resetFields();
        var params = {
            params: [
                {
                    hospID: this.state.hospId ? this.state.hospId : this.state.userData.hospID,//hospId -->hospID
                    timeRangeID: '',
                    statusID: this.state.statusID
                }
            ],
            // pagination: [{
            //     pageSize: 10,
            //     currentPage: page
            // }]
        }
        $http.post('urlDeault', this, {
            code: "03020011",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        dataSource: res.timeRangeDate,
                        editStatus: false,
                        editData: ''
                    })
                }
            }
        });
    }

    //获取医院信息
    loadHospitalMsg() {
        var params = {
            params: [{
                logonHospID: this.state.userData.hospID,
                logonGroupID: this.state.userData.groupID,
                hospRequired: '1'
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040001",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    if (!Util.isEmpty(res.depDoctor)) {
                        this.setState({
                            hospitalData: res.depDoctor
                        }, () => {
                            this.loadData(1)
                        })
                    }
                }
            }
        });
    }

    //查询时段服务
    loadTimeRange(id) {
        var params = {
            params: [{
                hospID: id ? id : this.state.userData.hospID//hospId--> hospID
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040010",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        timeRange: res.timeRange
                    })
                }
            }
        });
    }

    changeTimeInterVal(e) {
        const { value } = e.target;
        const reg = /^[1-9]\d*$/;
        if (!reg.test(value) && value.length > 0) {
            message.error('只允许输入正整数！')
            return
        }
        this.setState({
            timeLengthName: e.target.value
        })
    }

    handleSearch(e) {
        this.setState({
            timeLengthName: e
        })
    }

    clearBtn() {
        this.props.form.resetFields();
        this.setState({
            editData: '',
            timeLengthName: '',
            timeRangeId: undefined,
            timeLengthName: '',
            startTime: '00:00',
            endTime: '00:00',
            stopDate: '',
            status: false,
            disabledFlag: false
        })
    }

    //添加时间段
    addTimeRange() {
        var { editStatus, editData, timeRange } = this.state;//editStatus：true标识保存，false为添加
        let { validateFields } = this.props.form;
        var Code = '';
        var timeId = '';
        Code = '03020008';
        validateFields({ force: true }, (err, params) => {
            if (err) {
                return;
            }
            //获取时间段的ID
            if (editStatus && timeRange.length > 0) {
                for (var i = 0; i < timeRange.length; i++) {
                    if (params.timeRangeId == timeRange[i].descripts || params.timeRangeId == timeRange[i].id) {
                        timeId = timeRange[i].id
                    }
                }
            }
            var params = {
                params: [{
                    timeRangeID: editStatus ? timeId : params.timeRangeId,//时段ID
                    timeIntervalID: editStatus ? editData.timeIntervalID : '',//时段ID
                    startTime: editStatus ? moment(params.startTime).format('HH:mm') : this.state.startTime,//开始时间
                    endTime: editStatus ? moment(params.endTime).format('HH:mm') : this.state.endTime,//结束时间
                    timeLength: editStatus ? params.timeLength : this.state.timeLengthName,//间隔时间
                    startDate: moment(params.startDate).format(dayFormat),//生效时间
                    stopDate: params.stopDate ? moment(params.stopDate).format(dayFormat) : '',//失效时间
                    userID: this.state.userData.userID,//createUserDr --> userID
                    // updateUser: this.state.userData.userID,
                }]
            }
            $http.post('urlDeault', this, {
                code: Code,
                data: params,
                success: function (res) {
                    if (res.errorCode === '0') {
                        this.setState({
                            newStatus: false,
                            record: ''
                        })
                        this.loadData(1);
                        message.success('保存成功！')
                    }
                }
            });
        });
    }

    //获取坐诊类型ID
    getSumDataId(e) {
        this.setState({
            regTitleId: e
        })
    }

    getHospitalId(e) {
        this.setState({
            hospId: e,
            delStatus: true
        })
    }

    getStatusID(e) {
        this.setState({
            statusID: e
        })
    }

    //点击编辑，弹出框
    editData(data) {
        this.setState({
            timeLengthName: '',
            isShowEditModal: true,
            editData: data,
            editStatus: true,
            record: data.timeRangeID,
            status: true,
            disabledFlag: true

        }, () => {
            this.loadTimeRange(data.hospID)
        })
    }

    //删除
    handleDel(data) {
        var params = {
            params: [
                {
                    id: data.timeIntervalID,
                    userID: this.state.userData.userID//createUserDr --> userID
                }
            ]
        }
        $http.post('urlDeault', this, {
            code: "03020009",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.loadData(1);
                    message.success('删除成功！')
                }
            }
        });
    }

    //获取所选医院ID
    changeHospitalOption(e) {
        this.props.form.resetFields('timeRangeId');
        this.setState({
            hospitalId: e,
            timeRangeId: '',
            startTime: '00:00',
            endTime: '00:00'
        })
        this.loadTimeRange(e);//查询时段服务
    }

    //获取开始时间和结束时间
    changeTimeRang(e) {
        var { timeRange } = this.state;
        for (var i = 0; i < timeRange.length; i++) {
            if (e == timeRange[i].id) {
                this.setState({
                    startTime: timeRange[i].startTime,
                    endTime: timeRange[i].endTime,
                })
            }
        }
        this.setState({
            timeRangeId: e,
        })
    }
    onChange(e) {
        this.setState({ pageSize: e }, () => {
            this.loadData(e);
        });
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        this.props.form.resetFields('timeLength')
        return {
            onClick: () => {
                this.setState({
                    timeLengthName: '',
                    isShowEditModal: true,
                    editData: record,
                    editStatus: true,
                    newStatus: true,
                    status: true,
                    record: record.timeIntervalID,
                    disabledFlag: true
                })
                this.loadTimeRange(record.hospID)
            },
        };
    }

    //点击行，渲染当前行样式
    setRowClassName = (record) => {
        return this.state.record == record.timeIntervalID ? 'clickRowStyle' : '';
    }

    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    render() {
        let { getFieldDecorator } = this.props.form;
        var date = new Date()

        let formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 19 }
        };

        let searchColConfig = {
            xs: { span: 24 },
            sm: { span: 12 },
            md: { span: 8 },
            lg: { span: 7 }
        }

        let searchByCondition = {
            xs: { span: 24 },
            sm: { span: 12 },
            md: { span: 8 },
            lg: { span: 8 }
        }

        //所属医院下拉参数
        let hospitalOption = [];
        this.state.hospitalData.map((item, index) => {
            hospitalOption.push(<Option key={index} value={item.id + ''}>{item.descripts}</Option>)
        })

        //时间段
        let timeRangeOption = []
        this.state.timeRange.map((item, index) => {
            timeRangeOption.push(<Option key={index} value={item.id + ''}>{item.descripts}</Option>)
        })

        //状态
        let statusOption = []
        this.state.timeStatus.map((item, index) => {
            statusOption.push(<Option key={index} value={item.id + ''}>{item.descripts}</Option>)
        })

        //坐诊类型sumData
        let sumDataOption = []
        this.state.sumData.map((item, index) => {
            sumDataOption.push(<Option key={index} value={item.id + ''}>{item.descripts}</Option>)
        })

        //时间间隔
        let timeInterValOption = []
        TIME_INTERVAL_STATUS.map((item, index) => {
            timeInterValOption.push(<Option key={index} value={item.code + ''}>{item.name}</Option>)
        })
        const format = 'HH:mm';
        let { editData } = this.state;
        return (
            <div style={{ background: '#F1F1F1' }} className='timesolt-body'>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName="TimeSlot"
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.initData}
                />
                <Card title={<span style={{ color: '#666666' }}>
                    <span className='scheduling-title-borders'></span>
                    <span style={{ marginLeft: 10 }}>添加时间段</span>
                </span>}>
                    <Form>
                        <Row gutter={40}>
                            <Col span={5}>
                                <FormItem {...formItemLayout} label="所属医院">
                                    {getFieldDecorator('HospitalDr', {
                                        initialValue: editData ? editData.hospDescripts :
                                            (Util.isEmpty(this.state.hospitalData) ? undefined : this.state.userData.hospDesc),
                                        // rules: [{ required: true, message: '所属不能为空' }],
                                    })(
                                        <Select placeholder="请选择所属医院" style={{ width: '190px' }}
                                            allowClear disabled={this.state.disabledFlag ? true : false}
                                            onChange={this.changeHospitalOption.bind(this)}
                                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                                            {hospitalOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>

                            <Col span={5}>
                                <FormItem {...formItemLayout} label="时间范围">
                                    {getFieldDecorator('timeRangeId', {
                                        initialValue: editData ? editData.timeRangeID : (this.state.timeRangeId ? this.state.timeRangeId : undefined),
                                        // rules: [{ required: true, message: '时间范围不能为空' }],
                                    })(
                                        <Select placeholder="请选择时间范围" style={{ width: '190px' }}
                                            onChange={this.changeTimeRang.bind(this)}
                                            disabled={this.state.disabledFlag ? true : false}
                                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                                            {timeRangeOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>

                            <Col span={5}>
                                <FormItem {...formItemLayout} label="间隔(分钟)">
                                    {getFieldDecorator('timeLength', {
                                        initialValue: this.state.timeLengthName ? this.state.timeLengthName : (editData ? editData.timeLength : '')
                                    })(
                                        <Input placeholder='单位(分),空为全时段' style={{ width: '190px' }}
                                            disabled={this.state.disabledFlag ? true : false}
                                            onChange={this.changeTimeInterVal.bind(this)} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem {...formItemLayout} label="开始时间">
                                    {getFieldDecorator('startTime', {
                                        initialValue: editData ? moment(editData.startTime, format) : moment(this.state.startTime, 'HH:mm'),
                                        // rules: [{ required: true, message: '开始时间不能为空' }],
                                    })(
                                        <TimePicker disabled={true} style={{ width: '190px' }} format={format} allowClear={false} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem {...formItemLayout} label="结束时间">
                                    {getFieldDecorator('endTime', {
                                        initialValue: editData ? moment(editData.endTime, format) : moment(this.state.endTime, 'HH:mm'),
                                        // rules: [{ required: true, message: '结束时间不能为空' }],
                                    })(
                                        <TimePicker disabled={true} style={{ width: '190px' }} format={format} allowClear={false} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem {...formItemLayout} label="生效日期">
                                    {getFieldDecorator('startDate', {
                                        initialValue: editData ? moment(editData.startDate, dayFormat) : moment(date, dayFormat),
                                        // rules: [{ required: true, message: '生效日期不能为空' }],
                                    })(
                                        <DatePicker format="YYYY-MM-DD" style={{ width: '190px' }} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem {...formItemLayout} label="失效日期">
                                    {getFieldDecorator('stopDate', {//处理当失效时间为空是，datePicker显示错误
                                        initialValue: editData ? (editData.stopDate ? moment(editData.stopDate, dayFormat) : '') : this.state.stopDate,
                                    })(
                                        <DatePicker format="YYYY-MM-DD" style={{ width: '190px' }} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4}>
                                <Button className='saveSchButton' onClick={this.addTimeRange.bind(this)}>
                                    保存</Button>
                                <Button className='cannelBtn' style={{ marginLeft: 10 }} onClick={this.clearBtn.bind(this)}>
                                    {this.state.status ? '取消' : '清空'}
                                </Button>
                            </Col>
                        </Row>
                    </Form>
                </Card>
                <div style={{ height: 48, lineHeight: '48px', background: 'white', color: '#666666' }}>
                    <div style={{ float: 'left' }}>
                        <span style={{ color: '#666666' }}>
                            <span className='scheduling-title-borders'></span>
                            <span style={{ marginLeft: 10,fontSize:16 }}>时间段列表</span></span>
                    </div>
                    <div style={{ float: 'right' }}>
                        <Col span={12}>
                            所属医院：<Select placeholder="请选择所属医院" style={{ width: '170px' }}
                                allowClear
                                value={this.state.hospId ? this.state.hospId : (this.state.delStatus == true ? undefined :
                                    (Util.isEmpty(this.state.hospitalData) ? undefined : this.state.userData.hospDesc))}
                                onChange={this.getHospitalId.bind(this)}
                                getPopupContainer={triggerNode => triggerNode.parentNode}>
                                {hospitalOption}
                            </Select>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="状态">
                                {getFieldDecorator('statusID', {
                                    initialValue: "生效",
                                    // rules: [{ required: true, message: '时间范围不能为空' }],
                                })(
                                    <div style={{ display: 'flex',marginTop:8 }}>
                                        <Select placeholder="请选择状态" style={{ width: '170px' }}
                                            onChange={this.getStatusID.bind(this)}
                                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                                            {statusOption}
                                        </Select>

                                        <Button style={{ background: '#1999db', color: 'white', marginLeft: 10, marginRight: 10 }}
                                            onClick={this.loadData.bind(this, 1)}>查询</Button></div>
                                )}
                            </FormItem>
                        </Col>
                    </div>
                </div>
                <Card style={{ marginTop: '10px' }}>

                    <Row gutter={40}>
                        <Table columns={this.state.column} style={{ marginTop: '10px' }} bordered
                            dataSource={this.state.dataSource} style={{height:store.getState().tableHeight.y + 'px'}}
                            loadData={this.loadData.bind(this, 1)}
                            onHeaderRow={column => {
                                return {
                                    onDoubleClick: () => {
                                        this.columnRef.onOpenModel();
                                    },
                                };
                            }}
                            rowKey={(data) => {
                                return data.id
                            }}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassName}
                            pagination={false}
                            scroll={{ x: 0, y: 0 }}>
                        </Table>
                    </Row>
                </Card>
            </div>
        )
    }
}

export default Form.create()(TimeSlot);