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

import React from 'react';
import {
    Card, Table, Select, Row, Col, Checkbox, Button, Tooltip,Modal,
    Icon, message
} from 'antd';
import { Util } from 'tools/index';
import SaveSchedulingModal from '../../scheduling/component/SaveSchedulingModal';
import ShowDoctorModal from '../../scheduling/component/ShowDoctorModal';
import { $http } from 'containers/config/https';
import moment from 'moment';
import '../../scheduling/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: '',
            dateStr: Util.getWeek(0) + '||' + Util.getWeek(6),
            newStr: '',
            newDateStr: '',
            locStatus:true
        }
    }

    componentDidMount() {
        this.loadColumn();
        this.loadData();
        this.getDepartment();
        this.getDoctor();
        this.loadScheduTime();//排班周期
    }

    //获取排班周期
    loadScheduTime(id) {
        var params = {
            params: [{
                locID: id ? id : this.props.locID,
            }]
        }
        $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.props.locID:''),
                groupID: '',
                depDoctorID: this.state.depDoctorId
            }]
        }
        $http.post('urlDeault', this, {
            code: "03020049",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        doctorData: res.depDoctor
                    })
                }
            }
        });
    }

    getDepartment(e) {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
            }]
        }
        $http.post('urlS', this, {
            code: "03020046",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({ departmentData: res.result.Data })
                }
            }
        })
    }

    loadColumn() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                dateStr: this.state.newDateStr ? this.state.newDateStr : (this.state.dateStr ? this.state.dateStr : Util.getWeek(0) + '||' + Util.getWeek(6)),
            }]
        }
        $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() {
        this.loadColumn()
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                dateStr: this.state.newDateStr ? this.state.newDateStr : (this.state.dateStr ? this.state.dateStr : Util.getWeek(0) + '||' + Util.getWeek(6)),
                locID: this.state.locId ? this.state.locId : this.props.locID,
                depDoctorID: this.state.depDoctorId
            }]
        }
        $http.post('urlDeault', this, {
            code: "03020036",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        dataSource: res.data,
                        statusDr: res.statusDr
                    })
                }
            }
        });
    }

    //展示复制、保存弹框
    showScheduModal(name) {
        if (name == 'copy') {
            this.setState({
                identity: name,
                isSaveSchedulingModal: true,
                copyStatus:false,
                showScheduModal:false
            })
            return
        }
        var { dataSource } = this.state;
        var params = {
            dateStr: this.state.newDateStr ? this.state.newDateStr : (this.state.dateStr ? this.state.dateStr : Util.getWeek(0) + '||' + Util.getWeek(6)),
            locID: this.state.locId ? this.state.locId : this.props.locID,
            userID: this.state.userData.userID,
            params: dataSource
        }
        $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
                    })
                    this.loadData()
                }
                else {
                    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) {
        this.setState({
            newDateStr: newDateStr,
        })
        if (this.state.identity == 'save') {
            this.hideModal('isSaveSchedulingModal')
        } else {
            var params = {
                params: [{
                    oldDateStr: oldDateStr,
                    newDateStr: newDateStr,
                    locID: this.state.locId ? this.state.locId : this.props.locID,
                    userID: this.state.userData.userID
                }]
            }
            $http.post('urlDeault', this, {
                code: "03020038",
                data: params,
                success: function (res) {
                    if (res.errorCode === '0') {
                        this.loadData()
                        message.success('保存成功！')
                        this.hideModal('isSaveSchedulingModal')
                    }
                }
            });
        }
        this.showScheduModal('copys');
    }

    //新增医生
    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 id = '';
        var departName = '';
        var { departmentData } = this.state;
        if (e) {
            id = e.substring(e.indexOf('^') + 1)
        }
        for (var i = 0; i < departmentData.length; i++) {
            if (id == departmentData[i].id) {
                departName = departmentData[i].descripts
            }
        }
        this.setState({
            locId: id,
            departName: departName,
            depDoctorId: '',
            locStatus:false
        },()=>{
        this.getDoctor(id, '')
        this.loadScheduTime(id)
        })
    }

    //获取坐诊医生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')
        }
    }


    render() {

        const columnData = [
            {
                title: '医生',
                dataIndex: 'doctorName',
                width: 120,
                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: (columns[i].children)[j].width,
                        align: (columns[i].children)[j].align,
                        render: (text, data) => {
                            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('^'))}
                    </div>
                        <div>{(columns[i].title).substring((columns[i].title).indexOf('^') + 1)}</div>
                    </div>,
                    children: newOption[i]
                })
            }
        }

        var column = columnData.concat(columnOption)
        //获取科室Department
        let departmentOption = [];
        this.state.departmentData && this.state.departmentData.map((item, index) => {
            departmentOption.push(<Option key={index} value={item.descripts + '-' + item.descriptsSPCode +
                '^' + item.id}>{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.deptDoctorID + ''}>
                {item.descripts}</Option>)
        })

        //获取年份、月、日
        var date = new Date();
        var year = date.getFullYear();
        var month = moment(date).format('MM-DD');
        
        return (
            <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}
                    doctorData={this.state.doctorData}
                    departmentData={this.state.departmentData}
                    onHide={this.hideModal.bind(this, 'isShowDoctorModal')}
                    onSubmit={this.saveDoctorData.bind(this)}>
                </ShowDoctorModal>
                <Card>
                    <Row>
                        <Col span={18}>
                            科室：<Select placeholder="请选择科室" style={{ width: '200px', marginRight: '15px' }}
                                showSearch
                                allowClear
                                defaultValue={this.state.userData.locDesc}
                                onChange={this.changeDepartment.bind(this)}
                                getPopupContainer={triggerNode => triggerNode.parentNode}>
                                {departmentOption}
                            </Select>
                            医生：<Select placeholder="请选择医生" style={{ width: '200px', marginRight: '15px' }}
                                showSearch
                                allowClear
                                value={this.state.depDoctorId ? this.state.deptDrName : undefined}
                                onChange={this.changeDoctorId.bind(this)}
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                            >
                                {doctorOption}
                            </Select>
                            排班周期：<Tooltip placement="top" title={this.state.checkStatus?'排班数据变动，请先保存排班':''}>
                                <Select placeholder="请选择排班周期" style={{ width: '200px', marginRight: '15px' }} disabled={this.state.checkStatus?true:false}
                                defaultValue={'本周(' + (moment(Util.getWeek(0)).format('MM-DD') + '至' + moment(Util.getWeek(6)).format('MM-DD')) + ')'}
                                value={this.state.newDateStr ? this.state.newDateStr : (this.state.newStr ? this.state.dateStr : ('本周(' + (moment(Util.getWeek(0)).format('MM-DD') + '至' + moment(Util.getWeek(6)).format('MM-DD')) + ')'))}
                                onChange={this.changeWeek.bind(this)}
                                getPopupContainer={triggerNode => triggerNode.parentNode}>
                                <Option key='9' value={year + '-' + moment(this.getLastWeekStartDate(27)).format('MM-DD')
                                    + '||' + year + '-' + moment(this.getLastWeekEndDate(21)).format('MM-DD')}>
                                    {'上四周(' + (moment(this.getLastWeekStartDate(27)).format('MM-DD') +
                                        '至' + moment(this.getLastWeekEndDate(21)).format('MM-DD')) + ')'}</Option>

                                <Option key='8' value={year + '-' + moment(this.getLastWeekStartDate(20)).format('MM-DD')
                                    + '||' + year + '-' + moment(this.getLastWeekEndDate(14)).format('MM-DD')}>
                                    {'上三周(' + (moment(this.getLastWeekStartDate(20)).format('MM-DD') +
                                        '至' + moment(this.getLastWeekEndDate(14)).format('MM-DD')) + ')'}</Option>

                                <Option key='7' value={year + '-' + moment(this.getLastWeekStartDate(13)).format('MM-DD')
                                    + '||' + year + '-' + moment(this.getLastWeekEndDate(7)).format('MM-DD')}>
                                    {'上两周(' + (moment(this.getLastWeekStartDate(13)).format('MM-DD') +
                                        '至' + moment(this.getLastWeekEndDate(7)).format('MM-DD')) + ')'}</Option>

                                <Option key='6' value={year + '-' + moment(this.getLastWeekStartDate(6)).format('MM-DD')
                                    + '||' + year + '-' + moment(this.getLastWeekEndDate(0)).format('MM-DD')}>
                                    {'上周(' + (moment(this.getLastWeekStartDate(6)).format('MM-DD') +
                                        '至' + moment(this.getLastWeekEndDate(0)).format('MM-DD')) + ')'}</Option>

                                <Option key='1' value={year + '-' + moment(Util.getWeek(0)).format('MM-DD')
                                    + '||' + year + '-' + moment(Util.getWeek(6)).format('MM-DD')}>
                                    {'本周(' + (moment(Util.getWeek(0)).format('MM-DD') +
                                        '至' + moment(Util.getWeek(6)).format('MM-DD')) + ')'}</Option>

                                <Option key='2' value={year + '-' + moment(this.getNextWeekStartDate(8)).format('MM-DD')
                                    + '||' + year + '-' + moment(this.getNextWeekEndDate(8)).format('MM-DD')}>
                                    {'下周(' + (moment(this.getNextWeekStartDate(8)).format('MM-DD') +
                                        '至' + moment(this.getNextWeekEndDate(8)).format('MM-DD')) + ')'}</Option>

                                <Option key='3' value={year + '-' + moment(this.getNextWeekStartDate(15)).format('MM-DD')
                                    + '||' + year + '-' + moment(this.getNextWeekEndDate(15)).format('MM-DD')}>
                                    {'下两周(' + (moment(this.getNextWeekStartDate(15)).format('MM-DD') +
                                        '至' + moment(this.getNextWeekEndDate(15)).format('MM-DD')) + ')'}</Option>

                                <Option key='4' value={year + '-' + moment(this.getNextWeekStartDate(22)).format('MM-DD')
                                    + '||' + year + '-' + moment(this.getNextWeekEndDate(22)).format('MM-DD')}>
                                    {'下三周(' + (moment(this.getNextWeekStartDate(22)).format('MM-DD') +
                                        '至' + moment(this.getNextWeekEndDate(22)).format('MM-DD')) + ')'}</Option>

                                <Option key='5' value={year + '-' + moment(this.getNextWeekStartDate(29)).format('MM-DD')
                                    + '||' + year + '-' + moment(this.getNextWeekEndDate(29)).format('MM-DD')}>
                                    {'下四周(' + (moment(this.getNextWeekStartDate(29)).format('MM-DD') +
                                        '至' + moment(this.getNextWeekEndDate(29)).format('MM-DD')) + ')'}</Option>
                            </Select></Tooltip>
                            <Button onClick={this.confirmModal.bind(this)}>查询</Button>
                        </Col>
                        <Col span={6}>
                            <Button 
                                className={this.state.statusDr == '2' ? 'disSchBtn' : ''}
                                disabled={this.state.statusDr == '2'?true:false}
                                onClick={this.showScheduModal.bind(this, 'save')}
                                style={{marginRight: '15px'}}
                            >保存排班</Button>
                            <Button onClick={this.confirmCopyModal.bind(this)}>
                                复制排班
                            </Button>
                        </Col>
                    </Row>
                </Card>

                <Card style={{ marginTop: '10px' }}>
                    <Row gutter={40}>
                        <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: '#64A982' }}
                                    onClick={this.addDoctorModal.bind(this)}>
                                    <Icon type='plus' />添加医生到排班</span>
                            }
                            }
                            rowClassName={(data) => {
                                return data.statusID == '1' ? '' : 'rowClassStyle1'
                            }}
                            bordered
                            rowKey={(data) => {
                                return data.id
                            }}
                            pagination={false}>
                        </Table>
                    </Row>
                </Card>
            </div >
        )
    }
}

export default ScheduInformation;