/**
 * 医生排班信息
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Button, Tooltip, Modal,
    Popconfirm, Divider, Icon, message, Spin
} from 'antd';
import { Util } from 'tools/index';
import SaveSchedulingModal from './component/SaveSchedulingModal';
import ShowDoctorModal from './component/ShowDoctorModal';
import { $http } from 'containers/config/https';
import moment from 'moment';
import store from 'store';
import './style/index.less';

const Option = Select.Option;
const confirm = Modal.confirm;
//全局申明时间
const now = new Date(); //当前日期
const nowDayOfWeek = now.getDay(); //今天本周的第几天
const nowDay = now.getDate(); //当前日
const nowMonth = now.getMonth(); //当前月
const nowYear = now.getFullYear(); //当前年
class ScheduInformation extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            dataSource: [],
            checked: false,
            identity: 'save',
            userData: userData,
            statusDr: '',
            newStr: '',
            newDateStr: '',
            locStatus: true,
            loading: false
        }
    }

    componentDidMount() {
        this.loadSchedulingTitleType()
    }

    loadSchedulingTitleType() {
        var params = {
            params: [{
                // hospitalId:this.state.userData.hospDr,
                hospID: this.state.userData.hospID,
                active: 'Y'
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040160",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    var data = res.result.data;
                    var resourceTypeID = ''
                    if (!Util.isEmpty(data)) {
                        resourceTypeID = data[0].id
                    }
                    this.setState({
                        resourceType: res.result.data,
                        resourceTypeID: resourceTypeID
                    }, () => {
                        this.loadSchedulingTime()
                        this.getDoctor();
                        this.loadScheduTime();//排班周期
                    })
                }
            }
        });
    }


    loadSchedulingTime() {
        var params = {
            params: [{
                beforNumber: '4',
                afterNumber: '4',
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlS', this, {
            code: "03020060",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    var data = res.result
                    var dateStr = ''
                    if (!Util.isEmpty(data)) {
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].defaultFlag && data[i].defaultFlag == 'Y') {
                                dateStr = data[i].id
                            }
                        }
                    }
                    this.setState({
                        schedulingTime: res.result,
                        dateStr: dateStr
                    }, () => {
                        this.getDepartment();
                        this.loadColumn();
                    })
                }
            }
        })
    }

    //获取排班周期
    loadScheduTime(id) {
        var params = {
            params: [{
                locID: id ? id : this.state.userData.locID,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03020054",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        lastList: res.lastList,
                        nextList: res.nextList
                    })
                }
            }
        });
    }

    //获取坐诊医生
    getDoctor(id, e) {
        var params = {
            params: [{
                hospID: this.state.hospId ? this.state.hospId : this.state.userData.hospID,
                locID: id ? id : (this.state.locStatus ? this.state.userData.locID : ''),
                // depDoctorID: this.state.depDoctorId
                userID: this.state.userData.userID,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03020056",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        doctorData: res.data
                    })
                }
            }
        });
    }

    getDepartment(e) {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                userID: this.state.userData.userID,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlS', this, {
            code: "03020055",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        departmentData: res.data.locList,
                        defaultLocID: res.data.defaultLocID
                    }, () => {
                        this.loadData()
                    })
                }
            }
        })
    }

    loadColumn() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                dateStr: this.state.newDateStr ? this.state.newDateStr : this.state.dateStr,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03020035",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        columns: res.data
                    })
                }
            }
        });
    }

    commonCheckbox(name, data, e) {
        data.monMorCheck = e.target.checked;
        this.setState({
            monMorCheck: e.target.checked
        })
    }

    commonCheckboxs(name, data, e) {
        data.monAfterCheck = e.target.checked;
        this.setState({
            monAfterCheck: e.target.checked
        })
    }

    loadData(data) {
        this.loadColumn()
        this.setState({ loading: true })
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                dateStr: this.state.newDateStr ? this.state.newDateStr : this.state.dateStr,
                locID: this.state.locId ? this.state.locId : this.state.defaultLocID,//this.state.userData.locID,
                depDoctorID: this.state.depDoctorId,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03020036",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        dataSource: res.data,
                        statusDr: res.statusDr,
                        saveStatus: false,
                        loading: false,
                        clearInput: false
                    }, () => {
                        if (data == 'save') {
                            this.showScheduModal('copys')
                        }
                    })
                }
            }
        });
    }

    //展示复制、保存弹框
    showScheduModal(name) {
        if (name == 'copy') {
            this.setState({
                identity: name,
                isSaveSchedulingModal: true,
                copyStatus: false,
                showScheduModal: false
            })
            return
        }
        this.setState({
            saveStatus: true
        })
        var { dataSource } = this.state;
        var params = {
            dateStr: this.state.newDateStr ? this.state.newDateStr : this.state.dateStr,
            locID: this.state.locId ? this.state.locId : this.state.userData.locID,
            userID: this.state.userData.userID,
            params: dataSource,
            resourceTypeID: this.state.resourceTypeID
        }
        $http.post('urlDeault', this, {
            code: "03020037",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        isSaveSchedulingModal: name == 'copys' ? false : true,
                        identity: name,
                        style: undefined,
                        checkStatus: false,
                        clearInput: false
                    })
                    this.loadData()
                }
                else {
                    var errData = res.errorMessages;
                    var errList = []
                    for (var i = 0; i < errData.length; i++) {
                        errList.push(
                            <h4>{errData[i].errorMessage}</h4>
                        )
                    }
                    Modal.error({
                        title: '排班错误信息提示',
                        content: errList,
                    })
                    this.setState({
                        style: '',
                        errorMessage: res.errorMessages
                    })

                }
            }
        });
    }

    //隐藏弹出框
    hideModal(name) {
        this.setState({
            [name]: false,//将所有参数置为false
            // identity:'save'
        });
        if (this.state.copyStatus) {
            this.showScheduModal('copy')
        }
    }

    //保存
    onSubmit(oldDateStr, newDateStr) {
        if (this.state.identity == 'save') {
            this.hideModal('isSaveSchedulingModal')
        } else {
            if (Util.isEmpty(oldDateStr) || Util.isEmpty(newDateStr)) {
                message.error('请选择需要复制的排班周期！')
                return
            }
            var params = {
                params: [{
                    oldDateStr: oldDateStr,
                    newDateStr: newDateStr,
                    locID: this.state.locId ? this.state.locId : this.state.userData.locID,
                    userID: this.state.userData.userID,
                    resourceTypeID: this.state.resourceTypeID
                }]
            }
            $http.post('urlDeault', this, {
                code: "03020038",
                data: params,
                success: function (res) {
                    if (res.errorCode === '0') {
                        this.setState({
                            newDateStr: newDateStr
                        }, () => {
                            this.loadData('save')
                            message.success('保存成功！')
                            this.hideModal('isSaveSchedulingModal')
                            // this.showScheduModal('copys')
                            // setTimeout(()=>{
                            // },300)
                        })

                    }
                }
            });
        }
    }

    //新增医生
    addDoctorModal() {
        this.setState({
            isShowDoctorModal: true
        })
    }

    //保存新增医生
    saveDoctorData() {
        this.hideModal('isShowDoctorModal')
        this.loadData()
    }

    //勾选checkbox，渲染页面
    checkedBox(text, name, data, e) {
        text.checked = e.target.checked;
        text.style = '1'
        text.returnModelID = e.target.checked ? text.resModelID : '',
            text.locResModDetailID = e.target.checked ? text.locResModDetailID : '',
            this.setState({
                [name]: e.target.checked,
                checked: e.target.checked,
                style: '1',
                checkStatus: true,
            })
    }

    //全选
    checkedAll(data, index, e) {
        // console.dir(data)
        data['QT0'].checked = e.target.checked
        this.setState({
            checked: e.target.checked
        })
    }

    //获取科室ID
    changeDepartment(e) {
        var departName = '';
        var { departmentData } = this.state;
        for (var i = 0; i < departmentData.length; i++) {
            if (e == departmentData[i].id) {
                departName = departmentData[i].descripts
            }
        }
        this.setState({
            locId: e,
            departName: departName,
            depDoctorId: '',
            locStatus: false
        }, () => {
            this.getDoctor(e, '')
            this.loadScheduTime(e)
        })
    }

    //获取坐诊医生ID
    changeDoctorId(e) {
        var id = '';
        if (e) {
            id = e.substring(e.indexOf('^') + 1);
        }
        this.setState({
            depDoctorId: id,
            deptDrName: e ? (e.substring(0, e.indexOf('-'))) : ''
        })
    }

    //获取当前年的当前周
    getWeekOfYear() {
        var today = new Date();
        var firstDay = new Date(today.getFullYear(), 0, 1);
        var dayOfWeek = firstDay.getDay();
        var spendDay = 1;
        if (dayOfWeek != 0) {
            spendDay = 7 - dayOfWeek + 1;
        }
        firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
        var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
        var result = Math.ceil(d / 7);
        return result + 1;
    };

    changeWeek(e) {
        this.setState({
            newDateStr: '',
            dateStr: e,
            newStr: e,

        })
    }
    //获得上周的开始日期
    getLastWeekStartDate(day) {
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - day);
        return this.formatDate(weekStartDate);
    }
    //获得上周的结束日期
    getLastWeekEndDate(day) {
        var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - day);
        return this.formatDate(weekEndDate);
    }


    //获得下周开始时间
    getNextWeekStartDate(day) {
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + day);
        return this.formatDate(weekStartDate);
    }

    //获得下周结束时间
    getNextWeekEndDate(day) {
        var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + day);
        return this.formatDate(weekEndDate);
    }

    //格式化日期：yyyy-MM-dd
    formatDate(date) {
        var myyear = date.getFullYear();
        var mymonth = date.getMonth() + 1;
        var myweekday = date.getDate();
        if (mymonth < 10) {
            mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
            myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
    }

    //查询
    confirmModal() {
        var rthis = this;
        if (this.state.checkStatus) {
            confirm({
                content: '当前排班未保存，是否保存?',
                onOk() {
                    rthis.showScheduModal('save')
                },
                onCancel() { rthis.loadData() },
            });
        } else {
            rthis.loadData()
        }
    }

    //复制
    confirmCopyModal() {
        var rthis = this;
        if (this.state.checkStatus) {
            confirm({
                content: '当前排班未保存，是否保存?',
                onOk() {
                    rthis.setState({
                        copyStatus: true
                    })
                    rthis.showScheduModal('save');
                },
                onCancel() { rthis.showScheduModal('copy') },
            });
        } else {
            this.showScheduModal('copy')
        }
    }

    changeRecorceType(data) {
        this.setState({
            resourceTypeID: data.id
        }, () => {
            this.loadSchedulingTime()
            this.getDoctor();
            this.loadScheduTime();//排班周期
        })
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                if (!Util.isEmpty(this.state.indexID) && record.indexID == this.state.indexID) {
                    this.setState({
                        indexID: undefined
                    })
                } else {
                    this.setState({
                        indexID: record.indexID
                    })
                }
            },
        };
    }

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

    handleClearInput() {
        this.setState({
            clearInput: true
        })
    }


    render() {

        const columnData = [
            {
                title: '医生',
                dataIndex: 'doctorName',
                width: 150,
                align: 'center',
                fixed: 'left',
                children: [{
                    title: '',
                    dataIndex: 'doctorName',
                    className: 'loc-style',
                    width: 150,
                    align: 'center',
                }]
            },
            //  {先毙掉
            //     title: '全选',
            //     dataIndex: 'all',
            //     width: 120,
            //     align: 'center',
            //     render: (text,record, data, index) => {
            //         return <Checkbox
            //             onChange={this.checkedAll.bind(this, data, index)}></Checkbox>
            //     }
            // }
        ]
        var { columns } = this.state;
        var columnOption = [];
        var newColumn = []
        if (columns) {
            var newOption = []
            for (var i = 0; i < columns.length; i++) {
                newColumn = []
                for (var j = 0; j < columns[i].children.length; j++) {
                    newColumn.push({
                        title: (columns[i].children)[j].title,
                        dataIndex: (columns[i].children)[j].dataIndex,
                        width: 80,
                        align: (columns[i].children)[j].align,
                        render: (text, data) => {
                            if (text && this.state.clearInput == true) {
                                text.locResModDetailID = ''
                                text.returnModelID = ''
                                text.checked = false
                            }
                            if (this.state.errorMessage) {
                                var errorMessage = this.state.errorMessage;
                                for (var i = 0; i < errorMessage.length; i++) {
                                    if (text.count == errorMessage[i].count) {
                                        return {
                                            props: {
                                                className: text.style == this.state.style ? '' : 'errStyle'
                                            },
                                            children: text && text.statusID == '2' ? <span>{text ? text.registNum : ''}</span> :
                                                <Checkbox disabled={text.resModelID ? false : true}
                                                    checked={text.checked ? text.checked : (text.locResModDetailID ? true : false)}
                                                    onChange={this.checkedBox.bind(this, text, text.name, data)}></Checkbox>
                                        }
                                    }
                                }
                            }
                            return text && text.statusID == '2' ? <span>{text ? text.registNum : ''}</span> :
                                <Checkbox disabled={text.resModelID ? false : true}
                                    checked={text.checked ? text.checked : (text.locResModDetailID ? true : false)}
                                    onChange={this.checkedBox.bind(this, text, text.name, data)}></Checkbox>
                        }
                    })
                }
                newOption.push(newColumn)
            }
            for (var i = 0; i < columns.length; i++) {
                columnOption.push({
                    title: <div><div>{(columns[i].title).substring(0, (columns[i].title).indexOf('^'))}
                        <span style={{ color: 'white', background: '#1999db', marginLeft: 5 }}>
                            {columns[i].today == 'Y' ? <span>&nbsp;{'今'}&nbsp;</span> : ''}</span>
                    </div>
                        <div>{(columns[i].title).substring((columns[i].title).indexOf('^') + 1)}</div>
                    </div>,
                    children: newOption[i]
                })
            }
        }

        let hospitalOption = []
        var column = columnData.concat(columnOption)
        let searchColConfig = {
            xs: { span: 24 },
            sm: { span: 12 },
            md: { span: 8 },
            lg: { span: 6 }
        }
        //获取科室Department
        let departmentOption = [];
        this.state.departmentData && this.state.departmentData.map((item, index) => {
            departmentOption.push(<Option key={index} value={item.id} name={item.descripts} code={item.descriptsSPCode}>
                {item.descripts}</Option>)
        })

        //坐诊医生
        let doctorOption = []
        this.state.doctorData && this.state.doctorData.map((item, index) => {
            doctorOption.push(<Option key={index}
                value={item.descripts + '-' + item.code + item.descriptsSPCode + '^' + item.depDoctorID + ''}>
                {item.descripts}</Option>)
        })

        //获取年份、月、日
        var date = new Date();
        var year = date.getFullYear();
        var month = moment(date).format('MM-DD');
        let schedulingTimeOption = []
        this.state.schedulingTime && this.state.schedulingTime.map((item, index) => {
            schedulingTimeOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        var resourceTypeOption = []
        this.state.resourceType && this.state.resourceType.map((item, index) => {
            resourceTypeOption.push(<Button key={index} value={item.id} size="large" style={{ marginRight: 5 }}
                className={item.id == this.state.resourceTypeID ? 'resource-btn-bgd' : ''}
                onClick={this.changeRecorceType.bind(this, item)}>{item.descripts}</Button>)
        })

        return (
            <Spin tip='加载中...' spinning={this.state.loading}>
                <div style={{ background: '#F1F1F1' }} className='informationStyle'>
                    {/**保存、复制排班弹框 */}
                    <SaveSchedulingModal
                        isShow={this.state.isSaveSchedulingModal}
                        lastList={this.state.lastList}
                        nextList={this.state.nextList}
                        identity={this.state.identity}
                        onHide={this.hideModal.bind(this, 'isSaveSchedulingModal')}
                        onSubmit={this.onSubmit.bind(this)}>
                    </SaveSchedulingModal>
                    {/**添加临时医生*/}
                    <ShowDoctorModal
                        isShow={this.state.isShowDoctorModal}
                        locId={this.state.locId}
                        departName={this.state.departName}
                        addDepart={true}
                        dateStr={this.state.dateStr}
                        resourceTypeID={this.state.resourceTypeID}
                        doctorData={this.state.doctorData}
                        departmentData={this.state.departmentData}
                        onHide={this.hideModal.bind(this, 'isShowDoctorModal')}
                        onSubmit={this.saveDoctorData.bind(this)}>
                    </ShowDoctorModal>
                    <div className='scheduling-broad-title'>
                        <Card>
                            {resourceTypeOption}
                        </Card>
                    </div>
                    <Card>
                        <Row>
                            <Col span={4}>
                                科室：<Select placeholder="请选择科室" style={{ width: '220px' }}
                                    showSearch
                                    allowClear
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                    defaultValue={this.state.defaultLocID}
                                    onChange={this.changeDepartment.bind(this)}
                                    getPopupContainer={triggerNode => triggerNode.parentNode}>
                                    {departmentOption}
                                </Select>
                            </Col>

                            <Col span={4}>
                                医生：<Select placeholder="请选择医生" style={{ width: '190px' }}
                                    showSearch
                                    allowClear
                                    value={this.state.depDoctorId ? this.state.deptDrName : undefined}
                                    onChange={this.changeDoctorId.bind(this)}
                                    getPopupContainer={triggerNode => triggerNode.parentNode}>
                                    {doctorOption}
                                </Select>
                            </Col>
                            <Col span={4}>
                                排班周期：<Tooltip placement="top" title={this.state.checkStatus ? '排班数据变动，请先保存排班' : ''}>
                                    <Select placeholder="请选择排班周期" style={{ width: '190px', textAlign: 'right' }} disabled={this.state.checkStatus ? true : false}
                                        value={this.state.newDateStr ? this.state.newDateStr : this.state.dateStr}
                                        onChange={this.changeWeek.bind(this)}
                                        defaultActiveFirstOption={false}
                                        getPopupContainer={triggerNode => triggerNode.parentNode}>
                                        {schedulingTimeOption}
                                    </Select></Tooltip>
                            </Col>
                            <Col span={2}>
                                <Button style={{ background: '#108EE9', color: 'white' }} onClick={this.confirmModal.bind(this)}>查询</Button>
                            </Col>
                            <div style={{ textAlign: 'right' }}>
                                <Button onClick={this.handleClearInput.bind(this)}>清空</Button>
                                <Button style={{ marginLeft: 10 }}
                                    className={this.state.statusDr == '2' || this.state.saveStatus ? 'disSchBtn' : 'saveSchedSchButton'} disabled={this.state.statusDr == '2' || this.state.saveStatus ? true : false}
                                    onClick={this.showScheduModal.bind(this, 'save')}>保存排班</Button>
                                <Button type='primary' style={{ marginLeft: 10 }}
                                    onClick={this.confirmCopyModal.bind(this)}>复制排班</Button>
                            </div>
                        </Row>
                    </Card>

                    <Card style={{ marginTop: '10px' }}>
                        <Row>
                            <Table columns={column} style={{ width: '100%', minHeight: 400 }}
                                dataSource={this.state.dataSource}
                                loadData={this.loadData.bind(this)}
                                footer={() => {
                                    return this.state.statusDr == '2' ? null : <span style={{ marginLeft: '10px', cursor: 'pointer', color: '#1890FF' }}
                                        onClick={this.addDoctorModal.bind(this)}>
                                        <Icon type='plus' />添加医生到排班</span>
                                }
                                }
                                // rowClassName={(data) => {
                                //     return data.statusID == '1' ? '' : 'rowClassStyle1'
                                // }}
                                onRow={this.onClickRow}
                                rowClassName={this.setRowClassName}
                                scroll={{ y: store.getState().tableHeight.y - 45, x: 1500 }}
                                bordered
                                rowKey={(data) => {
                                    return data.id
                                }}
                                pagination={false}>
                            </Table>
                        </Row>
                    </Card>
                </div ></Spin>
        )
    }
}

export default ScheduInformation;