/*
 * Creator:     ML
 * CreatDate:   2020-05-11
 * descripts：  互联网坐诊---排班设置 合肥普瑞 只允许查看 不可操作
*/
import React from 'react';
import { Form, Row, Col, Input, Button, message, Table, Select, Popconfirm, Modal, Radio, Checkbox } from 'antd';
import { $http } from '../../../containers/config/https';
import { Util, } from 'tools/index';
import TIM from 'tim-js-sdk';
import COS from 'cos-js-sdk-v5';
import LibGenerateTestUserSig from '../../../../public/lib-generate-test-usersig.min.js';
import store from '../../../store';
import Item from 'antd/lib/list/Item';
/**
 * 签名过期时间，建议不要设置的过短
 * <p>
 * 时间单位：秒
 * 默认时间：7 x 24 x 60 x 60 = 604800 = 7 天
 */

const EXPIRETIME = 604800;
const { TextArea } = Input;
const ShiftSetting = Form.create()(
    class ShiftSetting extends React.Component {
        constructor(props) {
            super(props)
            let userData = sessionStorage.getItem("userData") ? JSON.parse(sessionStorage.getItem("userData")) : {};
            this.state = {
                userData,
                year: 0,
                month: 0,
                date: ['日', '一', '二', '三', '四', '五', '六'],
                monthstr: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
                dateArr: [],
                isToday: 0,
                isTodayWeek: false,
                todayIndex: 0,
                activeKey: "",
                // 下拉选项
                accounts: [],
                accountIndex: 0,

                // 排班日历
                schedulings: [],
                // 排班情况列表
                schedulingsArr: [],

                // 初始状态
                isOnload: false,

                // 查看的日期 不使用isToday判断
                lookDate: "",
                rightData: [],
                timeIntervalStaus: false,
                visible: false,
                selectedRowKeys_right: [],//右侧勾选中行
                activeDate: "",
                nowYearMonthDate: 0,
                nowYearMDate: 0,
                newData: [],
                modalArr: [],
                modalArrOne: [],
                modalCenter: [],
                tips: false,
                statusObj: {},
                resDetailID: "",
                canStop: true,
                typeValue: "single",
                lookDateBatch: "",
                lookDateBLength: 0,//批量设置个数
                batchMorTime: [],
                batchAftTime: [],
                batchMorTimeData: [],
                batchAftTimeData: [],
                lookDateBArr: [],
                checkValue: false,
                allDate: [],
                batchSetingData: []

            }
        }
        componentDidMount() {
            this.props.onShiftSetting(this)

        }
        //国际化
        setMessage(name, message) {
            return this.props.localeProvider ? this.props.localeProvider[name][message] : ''
        }
        //判断医生是否可以自己停诊操作
        getCanStop = () => {
            const { userData } = this.state
            let { hospID, userID, locID } = userData
            let obj = {
                "params": [{
                    userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                    locID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).locID || "",
                    hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100117",
                data: obj,
                success: function (res) {
                    if (res.errorCode == "0") {
                        this.setState({
                            canStop: res.result == "Y" ? true : false
                        });
                    }
                }
            });
        }
        //动态获取  SDKAPPID  SECRETKEY  登录
        /**
         * 计算签名用的加密密钥
         */
        loadTencentCloud() {
            var params = {
                params: [{
                    hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                }]
            }
            $http.post('urlDeault', this, {
                code: "03100143",
                data: params,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setState({
                            tencentMsg: res.result,
                            imSecretKey: !Util.isEmpty(res.result) ? res.result.imSecret : '',
                            imAppID: !Util.isEmpty(res.result) ? Number(res.result.imAppID) : '',
                        }, () => {
                            this.loginTencent()
                        })
                    }
                }
            });
        }
        //是否申请、
        handleIsApplyTips = (result, code, desc) => {
            //申请成功
            if (result == "Y") {
                this.setState({
                    tips: false
                }, () => {
                    this.initHome()
                    // this.loadTencentCloud()
                })
            } else {
                //申请未完成 --- 提示 --点击回到坐诊申请页面
                this.setState({
                    tips: true,
                    statusObj: { ...this.state.statusObj, ...{ code, desc, } },
                })

            }

        }
        // 号别
        getSchedulingType = (activeKey) => {
            const { userData, shiftTypeDescripts } = this.state
            let { hospID } = userData;
            let data = {
                "params": [{
                    hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                    active: "",
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100079",
                data: data,
                success: function (res) {
                    if (res.errorCode == "0") {
                        if (res.result.length > 0) {
                            res.result.map((item, i) => {
                                if (!this.state.activeKey && item.defaultFlag == "Y") {
                                    this.setState({
                                        activeKey: item.id,
                                    })
                                }
                            })
                            this.setState({
                                accounts: res.result,
                                // activeKey: activeKey || res.result[0].id,
                                shiftTypeDescripts: shiftTypeDescripts || res.result[0].descripts
                            }, () => {
                                this.handleShiftType(this.state.activeKey);
                                this.changeCalendarAndDetail();
                                this.setState({ isOnload: true });//首次通过load加载
                            });
                        }
                    }
                }
            });
        }
        // 排班切换修改日历和排班情况
        changeCalendarAndDetail = () => {
            if (this.state.typeValue == "single") {
                this.getSchedulingCalendar();
                // 默认选择排班
                let now = new Date();
                let year = now.getFullYear();
                let month = now.getMonth() + 1;
                this.setState({
                    year: year, month: month, isToday: '' + year + "-" + month + "-" + now.getDate(),
                    activeDate: '' + year + "-" + month + "-" + now.getDate()
                });
                let lookDate = year + "-" + month + "-" + now.getDate();
                this.getSchedulingInfo(lookDate);
            } else {

            }
        }
        // 点击日历获取排班信息 上午 下午 默认和传入
        getSchedulingInfo = (lookDate, record) => {
            const { userData } = this.state
            let { hospID, userID, locID } = userData
            let obj = {
                "params": [{
                    userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                    locID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).locID || "",
                    hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                    resourceTypeID: this.state.activeKey, //出诊类型ID
                    date: lookDate
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100045",
                data: obj,
                success: function (res) {
                    if (this.state.typeValue == "single") {
                        if (res.errorCode == "0") {
                            // console.log("recordrecordrecordrecord----",record)
                            this.setState({
                                schedulingsArr: res.result,
                                rowId: record && record.timeRangeID || res.result[0].timeRangeID,
                                timeRange: record && record.timeRange || res.result[0].timeRange,
                                record: record && record || res.result[0],
                            });
                            if (record) {
                                res.result && res.result.map((i, s) => {
                                    if (record.resDetailID == i.resDetailID) {
                                        record = i
                                        this.setState({
                                            record,
                                        }, () => {
                                            this.getRight(this.state.record.timeRangeID, this.state.record.resDetailID, this.state.record)
                                        })
                                    }
                                })
                            } else {
                                this.getRight(res.result[0].timeRangeID, res.result[0].resDetailID, res.result[0])
                            }

                        }
                    } else {
                        //批量设置 动态获取 上中下晚等数据
                        // console.log("批量设置 动态获取 上中下晚等数据",res.result)
                        this.setState({
                            batchSetingData: res.result
                        }, () => {
                            let a = []
                            let b = []
                            res.result && res.result.map((y, z) => {
                                a.push(y.timeRangeID)
                                b.push(y)
                            })
                            this.setState({
                                timeRangeIDArr: a
                            }, () => {
                                // console.log("bbbbbbbb",b)
                                this.handleBatchTime(a)
                            })

                        })
                    }
                }
            });

        }
        // 排班日历
        getSchedulingCalendar = (setYear, setMonth, next) => {
            const { userData } = this.state
            let { hospID, userID, groupID, locID } = userData
            let obj = {
                "params": [{
                    groupID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).groupID || "",
                    userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                    locID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).locID || "",
                    hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                    resourceTypeID: this.state.activeKey, //出诊类型ID
                    year: setYear ? setYear : new Date().getFullYear(),
                    month: setMonth ? setMonth : (new Date().getMonth() + 1)
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100044",
                data: obj,
                success: function (res) {
                    if (res.errorCode == "0") {
                        this.setState({ schedulings: res.result, }, () => {
                            // console.log("setMonth",setMonth-1)
                            this.dateInit(setYear, setMonth - 1, next,);
                        });
                    }
                }
            });
        }
        // 获取出诊类型ID
        getIndexId = () => {
            let array = this.state.accounts;
            if (array.length > 0) {
                this.setState({
                    activeKey: array[this.state.accountIndex].id
                })
                return array[this.state.accountIndex].id
            }
        }

        //默认年月
        onInitData = () => {
            let now = new Date();
            let year = now.getFullYear();
            let month = now.getMonth() + 1;
            // console.log("默认当月",now.getDate(),new Date(now.getDate()).getTime())
            this.setState({
                year: year,
                month: month,
                isToday: '' + year + "-" + month + "-" + now.getDate(),
                activeDate: this.state.typeValue == "single" ? '' + year + "-" + month + "-" + now.getDate() : "",
                lookDate: year + "-" + month + "-" + now.getDate(),
                isday: year + month + now.getDate(),
                nowYearMonthDate: new Date(year + "/" + month + "/" + now.getDate()).getTime(),//时间戳 年月日
                nowYearMDate: new Date(year + "/" + month).getTime(),//时间戳 年月
            }, () => {

            });
            this.getSchedulingType();
        }
        //点击分类 图文咨询排班 视频问诊... 切换
        handleBlock = (item) => {
            this.setState({
                activeKey: item.id,
                shiftTypeDescripts: item.descripts,
                typeValue: "single"
            }, () => {
                this.changeCalendarAndDetail()
                this.handleShiftType(item.id)
                if (this.state.typeValue == "batch") {
                    // this.updateDate()
                    // // // this.initBatch()
                    // this.handleDefaultActive()
                    // this.handleBatchTime()
                } else {

                }
            })
        }
        //获取排版类型 长
        handleShiftType = (activeKey) => {
            const { userData } = this.state
            let { hospID, userID, locID, groupID } = userData
            let obj = {
                "params": [{
                    resTypeID: activeKey || "",
                    hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100130",
                data: obj,
                success: function (res) {
                    if (res.errorCode == "0") {
                        this.setState({
                            shiftTypeSelect: res.result.Data
                        })
                    }
                }
            });
        }
        //获取时间间隔
        handleTime = (id) => {
            let obj = {
                "params": [{
                    timeRangeID: id || ""
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100055",
                data: obj,
                success: function (res) {
                    if (res.errorCode == "0") {
                        this.setState({
                            timeRangeSelect: res.result
                        })
                    }
                }
            });
        }
        //获取右侧详细数据
        getRight = (id, resDetailID, record) => {
            this.handleTime(id, resDetailID, record)
            this.setState({
                shiftType: record.regTitleID,
                timeIntervalID: record.timeIntervalID
            })

        }
        //获取时间间隔
        handleTime = (id, resDetailID, record) => {
            let obj = {
                "params": [{
                    timeRangeID: id || ""
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100055",
                data: obj,
                success: function (res) {
                    if (res.errorCode == "0") {
                        this.setState({
                            timeRangeSelect: res.result
                        }, () => {
                            this.handleDetail(resDetailID, record)
                        })
                    }
                }
            });
        }
        //时段明细
        handleDetail = (resDetailID, record) => {
            const { userData } = this.state
            let { hospID, userID, locID, groupID } = userData
            let obj = {
                params: [{
                    resDetailID: resDetailID || ""
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100049",
                data: obj,
                success: function (res) {
                    if (res.errorCode == "0") {
                        res.result && res.result.map((i, s) => {
                            i.originNumber = i.registNum
                        })
                        this.setState({
                            rightData: res.result,
                        }, () => {
                            let modalArr = []
                            let modalArrOne = []
                            this.state.rightData && this.state.rightData.map((item, i) => {
                                if (item.statusID != "2") {
                                    modalArr.push(item)
                                }
                                if (item.statusID == "2") {
                                    modalArrOne.push(item)
                                }
                            })
                            this.setState({
                                modalArr,
                                modalArrOne,
                            })
                            if (res.result.length == 0) {
                                //没有排班信息
                                this.setState({
                                    timeIntervalStaus: false,
                                    shiftType: this.state.shiftTypeSelect && this.state.shiftTypeSelect.length > 0 ? this.state.shiftTypeSelect[0].id : "",
                                    timeIntervalID: this.state.timeRangeSelect && this.state.timeRangeSelect.length > 0 ? this.state.timeRangeSelect[0].id : "",
                                    record: record,
                                }, () => {
                                    this.handleDefalut()
                                })
                            } else {
                                this.setState({
                                    timeIntervalStaus: true
                                })
                            }
                        })
                    }
                }
            });
        }
        //获取默认时段设置
        handleDefalut = () => {
            const { userData, record, timeIntervalID } = this.state
            let { hospID, userID, locID, groupID } = userData
            let obj = {
                params: [{
                    userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                    locID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).locID || "",
                    hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                    timeRangeID: record.timeRangeID || "",
                    timeIntervalID: timeIntervalID || "",
                    resModelID: ""

                }]
            };
            $http.post('urlDeault', this, {
                code: "03100064",
                data: obj,
                success: function (res) {
                    if (res.errorCode == "0") {
                        res.result && res.result.map((i, s) => {
                            i.originNumber = i.registNum
                        })
                        this.setState({
                            rightData: res.result
                        }, () => {

                        })
                    }
                }
            });
        }

        //设置行属性-----排班table
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: () => {
                    if (this.state.rowId === '') {
                        // 保存行数据以及ID
                        this.setState({ rowId: record.timeRangeID, timeRange: record.timeRange, record })
                        // console.log("recordrecordrecord", record)
                        this.getRight(record.timeRangeID, record.resDetailID, record)
                    } else {
                        if (this.state.rowId !== record.timeRangeID) {
                            this.setState({
                                rowId: record.timeRangeID,
                                timeRange: record.timeRange,
                                record,
                            })
                            // console.log("recordrecordrecord", record)
                            this.getRight(record.timeRangeID, record.resDetailID, record)
                        } else {
                            // this.setState({
                            //    rowId: "",
                            // });
                        }
                    }
                },
            }
        }
        // 表格行的类名
        setRowClassName = (record) => {
            return record.timeRangeID === this.state.rowId ? 'clickRowStyle' : '';
        }
        //无排班时改变时段等条件
        changeDefalut = (item) => {
            if (item) {
                this.setState({
                    timeIntervalID: item.id
                }, () => {
                    this.handleDefalut()
                })
            }
        }
        //b保存
        handleSave = () => {
            const { userData, record, timeIntervalID, rightData, } = this.state
            let { hospID, userID, locID, groupID } = userData
            rightData && rightData.map((ii, ss) => {
                if (ii.registNum == "") {
                    ii.registNum = ii.originNumber && ii.originNumber || 0
                }
            })
            // console.log("rightData",rightData)
            this.setState({
                rightData,
            })
            //新增  修改
            if (!this.state.timeIntervalStaus) {
                let obj = {
                    params: [{
                        userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                        locID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).locID || "",
                        hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                        regTitleID: this.state.shiftType || "",
                        resourceTypeID: this.state.activeKey || "",
                        date: this.state.isToday || "",
                        timeRangeID: this.state.rowId || "",
                        timeIntervalID: this.state.timeIntervalID || "",//时间段id
                        roomID: "",
                        registNum: "",
                        addNum: "",
                        resTime: this.state.rightData


                    }]
                };
                $http.post('urlDeault', this, {
                    code: "03100063",
                    data: obj,
                    success: function (res) {
                        if (res.errorCode == "0") {
                            message.success("新增成功")
                            let objs = {}
                            objs = this.state.record
                            objs.resDetailID = res.result.resDetailID
                            // console.log("objs",objs)
                            this.setState({
                                record: objs
                            }, () => {
                                this.updateDate()
                            })
                        }
                    }
                });
            } else {
                let obj = {
                    params: [{
                        userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                        regTitleID: this.state.shiftType || "",
                        resDetailID: record.resDetailID || "",
                        roomID: "",
                        registNum: "",
                        addNum: "",
                        resTime: this.state.rightData
                    }]
                };
                $http.post('urlDeault', this, {
                    code: "03100062",
                    data: obj,
                    success: function (res) {
                        if (res.errorCode == "0") {
                            message.success("修改成功")
                            // this.getRight(record.timeRangeID, record.resDetailID, record)
                            this.updateDate()
                            // this.setState({
                            //     rightData:this.state.newData
                            // })
                            this.setState({
                                // rightData: res.result
                            }, () => {

                            })
                        }
                    }
                });
            }

        }
        //刷新当前日历所有信息
        updateDate = (flag) => {
            const { userData, shiftTypeDescripts, dateArr, activeKey, month, year } = this.state
            let { hospID } = userData;
            let data = {
                "params": [{
                    hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                    active: "",
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100079",
                data: data,
                success: function (res) {
                    if (res.errorCode == "0") {
                        if (res.result.length > 0) {
                            this.setState({
                                accounts: res.result,
                                activeKey: activeKey || res.result[0].id,
                                shiftTypeDescripts: shiftTypeDescripts || res.result[0].descripts
                            }, () => {
                                this.getSchedulingCalendar(year, month, flag)
                                dateArr && dateArr.map((item, i) => {
                                    if (item.isToday && item.isToday == this.state.isToday) {
                                        this.lookActive(item, this.state.record)
                                    }
                                    if (this.state.typeValue == "single") {

                                    } else {

                                    }
                                })

                            });
                        }
                    }
                }
            });
        }
        //上午下午停诊等操作
        handleStop = (re, flag) => {
            const { userData, record, timeIntervalID } = this.state
            let { hospID, userID, locID, groupID } = userData
            //flag S 停诊 N 坐诊
            let obj = {
                params: [{
                    resDetailID: this.state.record.resDetailID || "",
                    userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                    statusCode: flag
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100051",
                data: obj,
                success: function (res) {
                    if (res.errorCode == "0") {
                        //
                        message.success("操作成功")
                        this.updateDate()
                        // this.getSchedulingType(this.state.activeKey)
                        if (flag == "S") {
                            this.getUnTreatPatList();
                        }
                    }
                }
            });
        }
        //右侧 停诊
        handleRightStop = (num, data) => {
            this.setState({
                isMod: num,
                modalCenter: data
            }, () => {
                this.setState({
                    visible: true,
                    selectedRowKeys_right: []
                })
            })
        }
        // 监听是否被踢下线
        monitorKickedOut = (event) => {
            let { isKickedOut } = this.state;
            this.setState({ isKickedOut: false });
            if (isKickedOut) {
                message.warn('您的账号在别处登录，请重新登录')
            }
        }
        //登录Tim
        loginTencent() {
            const { userData } = this.state
            let options = {
                SDKAppID: this.state.imAppID
            }
            this.tim = TIM.create(options); // SDK 实例通常用 tim 表示
            // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
            this.tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
            // tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
            // 注册 COS SDK 插件
            this.tim.registerPlugin({ 'cos-js-sdk': COS });
            const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
            const userSig = generator.genTestUserSig(userData && userData.userID);
            let user = userSig;
            let promise = this.tim.login({ userID: userData && userData.userID, userSig: user });
            promise.then((imResponse) => {
                // console.log(imResponse)
                if (imResponse.data.errorCode == '0') {
                    this.setState({ isKickedOut: true }, () => {
                        // this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
                        this.tim.on(TIM.EVENT.KICKED_OUT, this.monitorKickedOut);
                        // if (type == 'video') {
                        //     setTimeout(() => {
                        //         this.handleSendVideoMsg()
                        //     }, 500)
                        // }
                    })
                    // if (type === "user") {
                    //     this.saveCommunicationUser();
                    //     setTimeout(() => {
                    //         this.signOut("user"); // 退出医生登录
                    //     }, 300)
                    // }
                }
            }).catch(function (imError) {
                console.warn('login error:', imError); // 登录失败的相关信息
            });
        }
        //退出登录
        signOut = (type) => {
            if (this.state.tips) {
                return
            }
            if(!this.tim){
                return
            }
            let { userData } = this.state;
            const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
            const userSig = generator.genTestUserSig('user' + (this.state.userData.userID));
            let promise = this.tim.logout();
            if (promise) {
                promise.then((imResponse) => {
                    console.log("用户退出成功");
                    if (type === "user") {
                        this.loginTencent(userSig || "");
                    }
                }).catch(function (imError) {
                    console.warn('logout error:', imError);
                });
            }
        }
        //获取未就诊患者列表
        getUnTreatPatList = (selectedRowKeys_right) => {
            let data = {
                "params": [{
                    locResID: this.state.record.resDetailID || "",
                    // locResID:"13||90"
                    timeData: selectedRowKeys_right || [],
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100101",
                data: data,
                success: function (res) {
                    if (res.errorCode == "0") {
                        if (res.result.length > 0) {
                            res.result.forEach(data => {
                                this.handleSendMessage("B", "医生停诊", "patient" + data.patID, data);
                            });
                        }
                    }
                }
            });
        }

        //点击停诊之后 通知小程序用户--患者
        handleSendMessage = (type, text, toUser, patientData) => {
            const userData = this.state.userData;
            let messageContent = {};
            messageContent.userID = userData.userID;
            messageContent.admID = patientData.admID;
            messageContent.patID = patientData.patID;
            messageContent.patName = patientData.patName;
            messageContent.userName = userData.userName;
            messageContent.type = type;
            messageContent.text = text;

            if (!toUser) {
                toUser = 'patient' + patientData.patID;
            }

            // console.log(JSON.stringify(messageContent));

            let message = this.tim.createTextMessage({
                to: toUser,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    text: JSON.stringify(messageContent),
                }
            });

            // 2. 发送消息
            let promise = this.tim.sendMessage(message);

            if (promise) {
                promise.then((imResponse) => {
                    if ((type != "M") && (type != "V") && (type != "I") && (type != "E")) {
                        let eventCode = "";
                        switch (type) {
                            case "B":
                                //医生停诊
                                eventCode = "2003";
                                break;
                            case "D":
                                //待支付订单
                                eventCode = "2005";
                                break;
                            case "F":
                                //待评价消息
                                eventCode = "2006";
                                break;
                            case "P":
                                //待确认处方
                                eventCode = "2008";
                                break;
                        }
                        this.saveMessage(eventCode, text, patientData)
                    }

                }).catch(function (imError) {
                    if (imError.code == '20003') {
                        message.warning('对方未开通消息接收,请联系管理员')
                        return false
                    }
                });
                return true;
            }
        }
        saveMessage = (eventCode, content, patientData) => {
            let userData = this.state.userData;
            let receiveUser = patientData.patID,
                receiveTypeCode = "P";
            if (eventCode == "2008") {
                receiveUser = userData.userID;
                receiveTypeCode = "U";
            }
            let params = {
                params: [{
                    sendUserName: userData.userName,
                    receiveUserName: patientData.patName,
                    eventCode: eventCode,
                    sendTypeCode: "U",
                    receiveTypeCode: receiveTypeCode,
                    sendUser: userData.userID,
                    receiveUser: receiveUser,
                    content: content,
                    userID: userData.userID,
                    admID: patientData.admID,
                }]
            }
            $http.post('urlDeault', this, {
                code: "03100096",
                data: params,
                success: function (res) {
                    if (res.errorCode == "0") { }
                }
            });
        }
        handleCancel = () => {
            this.setState({
                visible: false,
            })
        }
        handleOk = () => {
            // console.log("selectedRowKeys_right", this.state.selectedRowKeys_right)
            const { userData, record, timeIntervalID, isMod } = this.state
            let { hospID, userID, locID, groupID } = userData
            //flag S 停诊 N 坐诊
            let obj = {
                params: [{
                    resTime: this.state.selectedRowKeys_right || [""],
                    userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                    statusCode: isMod == "1" ? "S" : "N"
                }]
            };
            $http.post('urlDeault', this, {
                code: "03100052",
                data: obj,
                success: function (res) {
                    if (res.errorCode == "0") {
                        message.success("操作成功")
                        this.handleCancel()
                        this.updateDate()
                        if (isMod == "1") {
                            this.getUnTreatPatList(this.state.selectedRowKeys_right);
                        }
                    }
                }
            });
        }
        //回到坐诊申请
        handleBackApply = () => {
            this.props.handleHomeData("6")
        }
        initBatch = (flag) => {
            this.setState({
                lookDateBatch: "",
                checkValue: false,
                lookDateBArr: [],
                lookDateBLength: 0,
            }, () => {
                if (flag) {
                    const {batchSetingData} = this.state
                    batchSetingData&&batchSetingData.map((item,i)=>{
                        item.resTime&&item.resTime.map((items,index)=>{
                                items.registNum =""
                        })
                    })
                    this.setState({
                        batchSetingData,
                    },()=>{
                        this.updateDate(flag)
                    })
                    
                }
            })
        }
        //批量设置默认
        handleDefaultActive = () => {
            const { dateArr, nowYearMonthDate } = this.state
            let newArr = []
            try {
                dateArr && dateArr.map((item, i) => {
                    item.lookDateBActive = false
                    if (item.isToday) {
                        if (item.nowYearMonthDate >= this.state.nowYearMonthDate) {
                            newArr.push(item)
                        }
                        if (this.state.typeValue == "batch") {
                            arr = []
                            if (item.textCode == "U" && item.nowYearMonthDate >= this.state.nowYearMonthDate) {
                                arr.push(item)
                                this.setState({
                                    lookDateBatch: arr[0].dateLine
                                }, () => {
                                    this.handleDefalutChick(arr[0].dateLine, "1")
                                })
                                throw 'out';
                            }
                        }
                    }
                })
            } catch (e) {

            }

            this.setState({
                activeDate: this.state.typeValue == "single" ? newArr[0].isToday : "",
                dateArr,

            }, () => {

            })

            //  this.lookActive(newArr[0])
        }
        //重置面板
        initHome = (f) => {
            this.getCanStop();
            this.dateInit(f);
            this.onInitData();
        }
        //选择排班模式 切换
        handleType = (e) => {
            const { dateArr, nowYearMonthDate } = this.state
            this.setState({
                typeValue: e.target.value
            }, () => {
                if (e.target.value == "single") {
                    if(document.querySelector('.ant-table-body')){
                        var x = document.querySelectorAll(".sing-dom .ant-table-body");
                        // console.log("x",x)
                        for (var i = 0; i < x.length; i++) {
                          x[i].style.height = store.getState().tableHeight.y- 72 + 'px';
                          x[i].style.overflow = "auto";
                        }
                    }
                    dateArr && dateArr.map((item, i) => {
                        item.lookDateBActive = false
                    })
                    this.setState({
                        dateArr
                    }, () => {
                        this.initHome()
                    })
                } else {
                    this.initHome("1")
                    // this.initHome("1")


                }
            })
        }
        //获取操作行数据对象
        getRowByKey(key, newData, type, newDatas, a) {
            const { rightData, batchMorTimeData, batchAftTimeData, batchSetingData } = this.state;
            if (type == "batchInput") {
                return (newDatas || a).filter(item => item.timeDatail === key)[0];
            }
            else {
                return (newData || rightData).filter(item => item.timeDatail === key)[0];
            }
        }
        //文本框数据修改
        handleFieldChange = (e, fieldName, key, type, record, index) => {
            var value = e.target.value
            var reg = /^([1-9]\d*|0)(\.\d*[1-9])?$/ //可输入0 以以上的正整数 不可以00开头
            if (!reg.test(value) && e.target.value.length > 0) {
                // message.error('只允许输入正整数')
                return
            }
            const { rightData, batchSetingData } = this.state;
            let newData = []
            let newDatas = []
            let a = []
            if (type == "batchInput") {
                batchSetingData && batchSetingData.map((item, i) => {
                    if (item.timeRangeID == record.fatID) {
                        //找时段内的table
                        a = item.resTime
                        newDatas = a.map(item => ({ ...item }));
                    }
                })
            } else {
                newData = rightData.map(item => ({ ...item }));
            }
            const target = this.getRowByKey(key, newData, type, newDatas, a);
            if (target) {
                target[fieldName] = e.target.value;
                if (type == "batchInput") {
                    let indexO = this.handleFindIndex(batchSetingData, "timeRangeID", record.fatID);
                    let inputV = e.target.value
                    //   inputV.replace(/[^1-9]/g,'')
                    this.state.batchSetingData[indexO].resTime[index].registNum = inputV;
                    this.setState({ batchSetingData, });
                } else {
                    this.setState({
                        rightData: newData
                    })
                }
            }
        }
        handleFindIndex = (arr, key, target) => {
            return arr.findIndex((item) => {
                return item[key] === target;
            })
        }
        //上下月
        dateInit = (setYear, setMonth, next) => {
            //全部时间的月份都是按0~11基准，显示月份才+1
            let dateArr = []; //需要遍历的日历数组数据
            let arrLen = 0; //dateArr的数组长度
            let now = setYear && setYear != "1" ? new Date(setYear, setMonth) : new Date();
            let year = setYear && setYear != "1" ? setYear : now.getFullYear();
            let nextYear = 0;
            let month = setMonth || now.getMonth(); //没有+1方便后面计算当月总天数
            let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
            let startWeek = new Date(year + '/' + (month + 1) + '/' + 1).getDay(); //目标月1号对应的星期
            let dayNums = new Date(year, nextMonth, 0).getDate(); //获取目标月有多少天
            // console.log("new Date(year + '/' + (month + 1) + '/' + 1).getDay()",new Date(year + '/' + (month + 1) + '/' + 1).getDay(),"dayNums",dayNums)

            let obj = {};
            let num = 0;
            if (month + 1 > 11) {
                nextYear = year + 1;
                dayNums = new Date(nextYear, nextMonth, 0).getDate();
            }
            arrLen = startWeek + dayNums;
            for (let i = 0; i < arrLen; i++) {
                if (i >= startWeek) {
                    num = i - startWeek + 1;
                    obj = {
                        dateLine: '' + year + "" + (month + 1 > 9 ? month + 1 : "0" + (month + 1)) + "" + (num > 9 ? num : "0" + num),//日期格式 20200803
                        isToday: '' + year + "-" + (month + 1) + "-" + num,
                        dateNum: num,
                        nowYearMonthDate: new Date(year + "/" + (month + 1) + "/" + num).getTime(),//时间戳
                        nowYearMDate: new Date(year + "/" + (month + 1)).getTime(),//时间戳
                        lookDateBActive: false
                    }
                    if (this.state.schedulings.length > 0) {
                        let sObj = this.state.schedulings[num - 1];
                        obj.dateSub = sObj && sObj.text ? sObj.text : "";
                        obj.textCode = sObj && sObj.textCode ? sObj.textCode : "";
                    }


                } else {
                    obj = {};
                }
                dateArr[i] = obj;
            }
            this.setState({
                // allDate,
                dateArr,
                // result,
            }, () => {
                if (setYear == "1") {
                    this.handleDefaultActive()
                    this.initBatch()
                    this.updateDate("1")
                }
                let newArr = []
                let arr = []
                //点击下一个月
                if (next) {
                    try {
                        dateArr && dateArr.map((item, i) => {
                            item.lookDateBActive = false
                            if (item.isToday) {
                                if (item.nowYearMonthDate >= this.state.nowYearMonthDate) {
                                    newArr.push(item)
                                }
                                if (this.state.typeValue == "batch") {
                                    arr = []
                                    if (item.textCode == "U" && item.nowYearMonthDate >= this.state.nowYearMonthDate) {
                                        arr.push(item)
                                        this.handleDefalutChick(arr[0].dateLine, "1")
                                        throw 'out';
                                    }
                                }
                            }
                        })
                    } catch (e) {

                    }

                    this.setState({
                        activeDate: this.state.typeValue == "single" && newArr[0] ? newArr[0].isToday : "",
                        dateArr,

                    }, () => {

                    })

                    this.lookActive(newArr[0])
                }
                //点击上一个月 需注意当前月日 默认当日 不是月份第一天 
                if (next == "prev") {
                    if (this.state.typeValue == "batch") {
                        dateArr && dateArr.map((item, i) => {
                            item.lookDateBActive = false
                        })
                        this.setState({
                            activeDate: "",
                            dateArr,
                        }, () => {

                        })
                    }
                }
                //保存批量之后 再次默认
                if (next == "1") {
                    // this.handleDefaultActive()
                    // if (this.state.typeValue == "batch") {
                    this.handleDefaultActive()
                    // } 
                }
            });

        }
        /**
   * 上月切换
   */
        lastMonth = () => {
            //全部时间的月份都是按0~11基准，显示月份才+1
            let year = this.state.month - 2 < 0 ? this.state.year - 1 : this.state.year;
            let month = this.state.month - 2 < 0 ? 11 : this.state.month - 2;
            this.setState({
                year: year,
                month: (month + 1)
            });
            // this.dateInit(year, month);
            this.getSchedulingCalendar(year, month + 1, "prev");
        }
        /**
         * 下月切换
         */
        nextMonth = () => {
            //全部时间的月份都是按0~11基准，显示月份才+1
            let year = this.state.month > 11 ? this.state.year + 1 : this.state.year;
            let month = this.state.month > 11 ? 0 : this.state.month;
            this.setState({
                year: year,
                month: (month + 1)
            })
            // this.dateInit(year, month);
            this.getSchedulingCalendar(year, month + 1, "next");
        }
        handleDefalutChick = (lookDateBatch, flag) => {
            const { dateArr, } = this.state
            this.setState({
                // isToday: '' + year + "-" + month + "-" + item.dateNum,
                lookDateBatch: lookDateBatch,
                // activeDate: item.isToday,
            }, () => {
                let lookDateBArr = []
                dateArr && dateArr.map((item, i) => {
                    if (item.dateNum && item.dateLine == lookDateBatch) {
                        item.lookDateBActive = true
                        lookDateBArr.push(item)
                        this.setState({
                            lookDateBLength: lookDateBArr.length,
                            lookDateBArr,
                        })
                    }
                })
                this.setState({
                    dateArr
                })
                // this.handleBatchTime()
            });
        }
        //点击日历
        lookActive = (item, record) => {
            let { year, month, nowYearMonthDate, result, dateArr } = this.state
            let lookDate = year + "-" + month + "-" + item.dateNum;
            let lookDateBatch = year + "" + (month > 9 ? month : "0" + month) + "" + (item.dateNum > 9 ? item.dateNum : "0" + item.dateNum); //20200101
            if (this.state.typeValue == "single") {
                this.getSchedulingInfo(lookDate, record);
                this.setState({
                    isToday: '' + year + "-" + month + "-" + item.dateNum,
                    lookDate: lookDate,
                    activeDate: item.isToday,
                });
            } else {
                  //不允许点击操作
                  if(record=="N"){
                    return
                }
                //批量设置
                // console.log("lookDateBArr",this.state.lookDateBArr)
                if (this.state.lookDateBArr && this.state.lookDateBArr.length > 0) {
                    this.getSchedulingInfo(this.state.lookDateBArr && this.state.lookDateBArr[0].isToday)
                }

                if (this.state.lookDateBatch === "" && item.textCode == "U" && item.nowYearMonthDate >= nowYearMonthDate) {
                    this.handleDefalutChick(lookDateBatch)
                } else {
                    //点击的不是当前 20200101 20200111
                    console.log("lookDateBArr",this.state.lookDateBArr)
                    if (this.state.lookDateBatch !== lookDateBatch) {
                        // console.log("this.state.lookDateBatch", this.state.lookDateBatch, "lookDateBatchlookDateBatch", lookDateBatch,"dateArrdateArr",dateArr)
                        let lookDateBArr = []
                        dateArr && dateArr.map((item, i) => {
                            // let str = ""
                            item.lookDateBActive = false
                            if (item.dateNum) {
                                // str = item.isToday.split("-").join("");
                                // item["isTodayNoLine"] = str
                                //取范围 20200101 - 20200103 （ 1 2 3） 20200103-20200101(3 2 1)  大于 or 小于
                                if ((item.dateLine >= this.state.lookDateBatch && this.state.lookDateBatch < lookDateBatch &&
                                    item.dateLine <= lookDateBatch && item.textCode == "U")) {
                                    item.lookDateBActive = true
                                    lookDateBArr.push(item)
                                    this.setState({
                                        lookDateBLength: lookDateBArr.length,
                                        lookDateBArr,
                                    })
                                } if (item.dateLine <= this.state.lookDateBatch && this.state.lookDateBatch > lookDateBatch &&
                                    item.dateLine >= lookDateBatch && item.textCode == "U") {
                                    item.lookDateBActive = true
                                    lookDateBArr.push(item)
                                    this.setState({
                                        lookDateBLength: lookDateBArr.length,
                                        lookDateBArr,
                                    })
                                }

                            }
                        })

                        this.setState({
                            // isToday: '' + year + "-" + month + "-" + item.dateNum,
                            lookDateBatch: lookDateBatch,
                            // activeDate: item.isToday,
                            dateArr
                        }, () => {
                           
                        });
                       
                    } else {
                       

                    }
                }

            }

        }
        //批量排班
        //全选
        handleCheckAll = (e) => {
            const { dateArr, year, month, nowYearMDate, nowYearMonthDate } = this.state
            let lookDateBArr = []
            if (e.target.checked) {
                this.setState({
                    checkValue: e.target.checked
                })
                dateArr && dateArr.map((item, i) => {
                    if (item.dateNum && item.textCode == "U" && item.nowYearMonthDate >= nowYearMonthDate) {
                        item.lookDateBActive = true
                        lookDateBArr.push(item)
                        this.setState({
                            lookDateBLength: lookDateBArr.length,
                            lookDateBArr,
                        })

                    }
                })
                this.setState({
                    dateArr
                })
                // this.handleBatchTime()
            } else {
                this.setState({
                    checkValue: false
                })
                dateArr && dateArr.map((item, i) => {
                    if (item.dateNum && item.textCode == "U") {
                        item.lookDateBActive = false
                        this.setState({
                            lookDateBLength: 0,
                            lookDateBArr: []
                        })
                    }
                })
                this.setState({
                    dateArr
                })
            }
        }
        //获取时间段
        getTime(type,) {
            return new Promise((resolve, reject) => {
                let data = {}
                data = {
                    params: [{
                        timeRangeID: type || ""
                    }],
                }
                $http.post('urlS', this, {
                    code: "03100055",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            resolve(res.result);
                        }
                    },
                })

            })
        }
       
        //保存批量排班
        handleSaveBatch = () => {
            const { userData, lookDateBArr, batchMorTimeData, batchAftTimeData, batchSetingData } = this.state
            let { hospID, userID, locID, groupID } = userData
            let dateList = []
            let  newArr = []
            batchSetingData&&batchSetingData.map((item,i)=>{
                item.resTime&&item.resTime.map((items,index)=>{
                    if(items.registNum==""){
                        items.registNum=0
                    }
                    if(items.registNum>=0&&items.registNum!=""&&items.fatID==item.timeRangeID){
                        newArr.push(item)
                    }
                })
            })
            if(newArr&&!newArr.length>0){
                message.warning("请设置排班")
                return
            }
            if (lookDateBArr && lookDateBArr.length > 0) {
                lookDateBArr && lookDateBArr.map((item, i) => {
                    dateList.push(item.isToday)
                })

                let obj = {
                    params: [{
                        userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                        locID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).locID || "",
                        hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                        resourceTypeID: this.state.activeKey, //出诊类型ID
                        dateList: dateList || [],
                        resData: newArr || []
                    }]
                };
                $http.post('urlDeault', this, {
                    code: "03100151",
                    data: obj,
                    success: function (res) {
                        if (res.errorCode == "0") {
                            message.success("批量设置成功")
                            this.initBatch("1")
                        }
                    }
                });
            } else {
                message.warning("请选择排班日期")
            }
        }
        //获取批量排班各时间段
        handleBatchTime = (type, init) => {
            const { batchSetingData, shiftTypeSelect } = this.state
            let data = {}
            data = {
                params: [{
                    timeRangeID: "",
                    timeRangeList: type
                }],
            }
            $http.post('urlS', this, {
                code: "03100055",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        // console.log("获取批量排班各时间段",res)
                        //默认
                        let b = []
                        let batchArr = batchSetingData
                        batchArr && batchArr.map((item, i) => {
                            b.push(res.resultList[item.timeRangeID])
                            item.regTitleID = shiftTypeSelect[0].id
                            item["child"] = res.resultList[item.timeRangeID]
                            item["regShiftType"] = shiftTypeSelect
                            item.registNum=""
                            item["child"][i]
                            this.setState({
                                ["batchTime" + i]: item["child"][0].id,
                                ["batchType" + i]: shiftTypeSelect[0].id,
                            })
                           
                        })
                        this.setState({
                            batchSetingData: batchArr
                        }, () => {
                            b.forEach((item,index)=>{
                                if(this.state.timeRangeIDArr[index]){
                                    this.handleRegTimeID(item[0], this.state.timeRangeIDArr[index], "time")
                                }
                            });
                        })
                    }
                },
            })
        }
        //设置批量 号别  时段 id （时段获取table数据）
        handleRegTimeID = (items, id, time) => {
            const { batchSetingData, shiftTypeSelect, userData } = this.state
            let batchArr = batchSetingData
            batchArr && batchArr.map((item, i) => {
                if (item.timeRangeID == id) {
                    //点击时段
                    if (time) {
                        item.timeIntervalID = items.id
                        let obj = {
                            params: [{
                                userID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).userID || "",
                                locID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).locID || "",
                                hospID: sessionStorage.getItem("userData") && JSON.parse(sessionStorage.getItem("userData")).hospID || "",
                                timeRangeID: id || "",
                                timeIntervalID: items.id || "",
                                resModelID: ""

                            }]
                        };
                        $http.post('urlDeault', this, {
                            code: "03100064",
                            data: obj,
                            success: function (res) {
                                if (res.errorCode == "0") {
                                    // console.log("res.result设置每个时段的table数据",res.result),
                                    //设置每个时段的table数据
                                    res.result && res.result.map((items, i) => {
                                        items["fatID"] = id
                                        items.registNum = ""
                                    })
                                    item["resTime"] = res.result
                                    this.setState({
                                        batchSetingData: batchArr
                                    })
                                    // console.log("batchArr",batchArr)
                                }
                            }
                        });
                    } else {
                        //点击号别
                        item.regTitleID = items.id
                    }
                }
            })
            this.setState({
                batchSetingData: batchArr
            },()=>{
                // console.log("document.querySelector",document.querySelectorAll(".ant-table-body"))
                if(this.state.typeValue!="single"){
                     if(document.querySelector('.ant-table-body')){
                    var x = document.querySelectorAll(".batch-dom .ant-table-body");
                    for (var i = 0; i < x.length; i++) {
                      x[i].style.height = store.getState().tableHeight.y-520 + 'px';
                      x[i].style.overflow = "auto";
                    }
                }
                }
               
            })
            //    console.log("batchArr",batchArr)
        }
        render() {
            const { name, batchSetingData, userName, batchMorTime, batchAftTime, statusObj, tips, dateArr, date, month, year, monthstr, accounts, timeRangeSelect, shiftTypeSelect, rightData, nowYearMonthDate, nowYearMDate } = this.state
            let localeData = this.props.localeProvider
            let dateop = []
            date && date.map((item, i) => {
                dateop.push(<span className='weekMark'>{item}</span>)
            })
            let accountOp = []
            accounts && accounts.map((item, i) => {
                accountOp.push(
                    <span
                        style={{
                            display: "inline-block",
                            textAlign: "center",
                            marginRight: "10px",
                            borderRadius: "4px",
                            padding: "9px 15px",
                            cursor: "pointer",
                            color: (this.state.activeKey == item.id ? "#fff" : "#333"),
                            border: "1px solid #e8e8e8",
                            background: (this.state.activeKey == item.id ? "#40a9ff" : "")
                        }}
                        onClick={() => this.handleBlock(item)} key={item.id} value={item.id} title={item.descripts}>
                        {item.descripts}
                    </span>
                )
            })
            //时间间隔
            let timeIntervalOp = []
            timeRangeSelect && timeRangeSelect.map(item => {
                timeIntervalOp.push(<Option key={item.code} onClick={() => this.changeDefalut(item)} name={item.descripts} title={item.descripts} role={item.descripts + '^' + item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            //号别 
            let shiftTypeOp = []
            shiftTypeSelect && shiftTypeSelect.map(item => {
                shiftTypeOp.push(
                    <Option
                        // onClick={this.changeDefalut}
                        key={item.code}
                        name={item.descriptsSPCode}
                        title={item.descripts}
                        role={item.descripts + '^' + item.descriptsSPCode}
                        value={String(item.id)}>
                        {item.descripts}
                    </Option>)
            })
            //右侧 批量设置
            const rightBatchColumns = [
                {
                    align: "center",
                    title: '时段明细',
                    dataIndex: 'timeDatail',
                    key: 'diagCodeDetail',

                },

                {
                    width: 140,
                    align: "center",
                    title: '总号源',
                    dataIndex: 'registNum',
                    key: 'registNum',
                    render: (text, record, index) => {
                        // if (record.editable) {
                        if (record.statusID == "2") {
                            return (
                                <Input disabled style={{ height: "32px", resize: "none" }} type="number" value={text} />
                            )
                        } else {
                            return (
                                <Input disabled style={{ height: "32px", resize: "none" }}
                                    value={record.registNum}
                                    onChange={(e) => this.handleFieldChange(e, 'registNum', record.timeDatail, "batchInput", record, index)} />
                            )
                        }
                        return text;
                    },
                },
            ];
            //批量设置
            let batchSetingBlock = []
            batchSetingData && batchSetingData.map((item, i) => {
                batchSetingBlock.push(
                    <Row>
                        <Row className="right-title"><span></span>{item.timeRange}</Row>
                        <Row style={{marginBottom:"4px"}}>
                        <Col span={6}>
                                号别：<Select style={{ width: '68%' }}
                                    dropdownMatchSelectWidth={false}
                                    showSearch
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                    disabled
                                    value={this.state["batchType" + i]}
                                    onChange={Util.handleSelectChange.bind(this, "batchType" + i)}
                                    getPopupContainer={triggerNode => triggerNode.parentNode}
                                >
                                    {
                                        item.regShiftType && item.regShiftType.map((items, index) => {
                                            return (
                                                <Option key={items.code} onClick={() => this.handleRegTimeID(items, item.timeRangeID)}
                                                    name={items.descripts} title={items.descripts} role={items.descripts + '^' + items.descripts} value={items.id}>{items.descripts}</Option>
                                            )
                                        })

                                    }
                                </Select>
                            </Col>
                            <Col span={6}>
                                时间间隔：<Select style={{ width: '55%' }}
                                    showSearch
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                    disabled
                                    value={this.state["batchTime" + i]}
                                    onChange={Util.handleSelectChange.bind(this, "batchTime" + i)}
                                    getPopupContainer={triggerNode => triggerNode.parentNode}
                                >
                                    {
                                        //各时段根据全天不同
                                        item.child && item.child.map((items, index) => {
                                            return (
                                                <Option key={items.code} onClick={() => this.handleRegTimeID(items, item.timeRangeID, "time")}
                                                    name={items.descripts} title={items.descripts} role={items.descripts + '^' + items.descripts} value={items.id}>{items.descripts}</Option>
                                            )
                                        })

                                    }
                                </Select>
                            </Col>
                        </Row>
                        <Row className="batchMorDom">
                            <Table
                                columns={rightBatchColumns}
                                pagination={false}
                                dataSource={item.resTime}
                                rowKey={(row) => {
                                    return row.timeDetailID
                                }}
                                // style={{ height: store.getState().tableHeight.y - 520 + 'px', marginTop: "44px", overflow: "auto" }}
                                className="clearBackground"
                                // onRow={this.onClickRow}
                                // rowClassName={this.setRowClassName}
                                bordered
                            />
                        </Row>
                    </Row>
                )

            })
            const columns = [
                {
                    width: 40,
                    align: "center",
                    title: '时段',
                    dataIndex: 'timeRange',
                    key: '0',
                },
                {
                    width: 80,
                    align: "center",
                    title: '号源情况',
                    dataIndex: 'edi',
                    key: '1',
                    render: (text, record, index) => {
                        if (record.statusID == "") {
                            return (
                                <span style={{ color: "#bfbfbf" }}>
                                    {record.status || "--"}
                                </span>
                            )
                        } else {
                            return (
                                <span style={{ color: "rgba(245,162,47)" }}>
                                    <span>{record.usedNum}</span>
                                    <span>/</span>
                                    <span>{record.registNum}</span>
                                </span>
                            )
                        }
                        return text
                    }
                },
                {
                    width: 60,
                    align: "center",
                    title: '状态',
                    dataIndex: 'status',
                    key: '2',
                    render: (text, record, index) => {
                        return <span style={{ color: (record.statusID == "2" ? "rgb(217,0,27)" : record.statusID == "1" ? "#333" : record.statusID == "" ? "#bfbfbf" : "#bfbfbf") }}>
                            {record.status || "--"}
                        </span>
                    },
                },
                // {
                //     title: '操作',
                //     dataIndex: 'edit',
                //     key: '3',
                //     align: "center",
                //     width: 80,
                //     render: (text, record, index) => {
                //         if (record.statusID == "") {
                //             return (
                //                 <span>/</span>
                //             )
                //         } if (record.statusID == "1") {
                //             if(this.state.canStop){
                //                 return (
                //                     <span className="table-operation">
                //                         <Popconfirm title="确认停诊操作?" onConfirm={() => this.handleStop(record, "S")} >
                //                             <a style={{ border: "0", background: "0", boxShadow: "0 0 0", color: "rgb(217,0,27)" }} >停诊</a>
                //                         </Popconfirm>
                //                     </span>
                //                 )
                //             }else{
                //                 return (
                //                     <span title="该医生未授权操作">/</span>
                //                 )  
                //             }

                //         } if (record.statusID == "2") {
                //             if(this.state.canStop){
                //                 return (
                //                     <span className="table-operation">
                //                         <Popconfirm title="确认恢复坐诊操作" onConfirm={() => this.handleStop(record, "N")} >
                //                             <a style={{ border: "0", background: "0", boxShadow: "0 0 0", color: "#40a9ff" }} >恢复坐诊</a>
                //                         </Popconfirm>
                //                     </span>
                //                 )
                //             }else{
                //                 return (
                //                     <span title="该医生未授权操作">/</span>
                //                 )  
                //             }

                //         }
                //         return text

                //     }
                // }
            ];
            //右侧 单一设置
            const rightColumns = [
                {
                    align: "center",
                    title: '时段明细',
                    dataIndex: 'timeDatail',
                    key: 'diagCodeDetail',

                },
                {
                    align: "center",
                    title: '已使用',
                    dataIndex: 'usedNum',
                    key: 'diagCode',
                    render: (text, record, index) => {
                        return <span style={{ color: "rgba(245,162,47)" }}>
                            {record.usedNum || 0}
                        </span>
                    },
                },
                {
                    align: "center",
                    title: '总号源',
                    dataIndex: 'CMark',
                    key: 'CMark',
                    render: (text, record, index) => {
                        return <span>
                            {record.usableNum + record.usedNum || 0}
                        </span>
                    },
                },
                {
                    width: 200,
                    align: "center",
                    title: '新号源',
                    dataIndex: 'registNum',
                    key: 'registNum',
                    editable: false,
                    render: (text, record, index) => {
                        // if (record.editable) {
                        if (record.statusID == "2") {
                            return (
                                <Input disabled style={{ height: "32px", resize: "none" }} type="number" value={text} />
                            )
                        } else {
                            return (
                                <Input disabled style={{ height: "32px", resize: "none" }} min={0} value={text} onChange={(e) => this.handleFieldChange(e, 'registNum', record.timeDatail, "single")} />
                            )
                        }
                        return text;
                    },
                },
                {
                    align: "center",
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: (text, record, index) => {
                        return <span style={{ color: (record.statusID == "2" ? "rgb(217,0,27)" : record.statusID == "1" ? "#333" : record.statusID == "" ? "#bfbfbf" : "#bfbfbf") }}>
                            {record.status || "--"}
                        </span>
                    },
                },
            ];

            const columnsModal = [
                {
                    width: 40,
                    align: "center",
                    title: '时段明细',
                    dataIndex: 'timeDatail',
                    key: '0',
                },
                {
                    width: 80,
                    align: "center",
                    title: '号源情况',
                    dataIndex: 'edi',
                    key: '1',
                    render: (text, record, index) => {
                        return (
                            <span style={{ color: "rgba(245,162,47)" }}>
                                <span>{record.usedNum}</span>
                                <span>/</span>
                                <span>{record.usableNum + record.usedNum || 0}</span>
                            </span>
                        )
                    }
                },

            ];
            const rowSelection_right = {
                selectedRowKeys: this.state.selectedRowKeys_right,
                onChange: (selectedRowKeys, selectedRows) => {
                    let btnStatus = false;
                    let canSaveStatus = false;
                    let selectrow = "";
                    if (selectedRowKeys.length === 0) {
                        btnStatus = true;
                        canSaveStatus = true;
                    } else {
                        selectrow = selectedRowKeys[selectedRowKeys.length - 1];
                    }
                    this.setState({ btnStatus: btnStatus, canSaveStatus: canSaveStatus, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_right: selectedRowKeys });
                },
                onSelectAll: (selected, selectedRows, changeRows) => {
                    if (selectedRows.length > 0) {
                        this.setState({
                            btnStatus: false,
                            canSaveStatus: false,
                        })
                    } else {
                        this.setState({
                            btnStatus: true,
                            canSaveStatus: true,
                        })
                    }
                    this.setState({ selectedRow_right: selectedRows });
                }
            };

            // console.log("dateArr--", this.state.dateArr)
            return (
                <div className="nameTitle">
                    {
                        tips ? <div>
                            {/* <p>{
                               statusObj.code=="01"||statusObj.code=="04"?<span>您的坐诊申请正在审核中，请耐心等待...申请成功,可操作排班。<span onClick={this.handleBackApply} style={{color:"blue",marginLeft:"4px",cursor:"pointer"}}>查看申请</span></span>
                               :statusObj.code=="02"?<span>您的坐诊申请已被拒绝...请<span onClick={this.handleBackApply} style={{color:"blue",marginLeft:"4px",cursor:"pointer"}}>重新申请</span>,申请成功,可操作排班。</span>
                               :statusObj.code=="05"?<span>您的坐诊申请已撤回...请<span onClick={this.handleBackApply} style={{color:"blue",marginLeft:"4px",cursor:"pointer"}}>重新申请</span>,申请成功,可操作排班。</span>
                               :statusObj.code=="06"?<span>您暂未提交坐诊申请...<span onClick={this.handleBackApply} style={{color:"blue",marginLeft:"4px",cursor:"pointer"}}>立即申请</span>,申请成功,可操作排班。</span>
                               :""
                            }</p> */}
                            <p>{
                                statusObj.code == "01" || statusObj.code == "04" ? <span>您的坐诊申请正在审核中，请耐心等待...申请成功,可操作排班。</span>
                                    : statusObj.code == "02" ? <span>您的坐诊申请已被拒绝...请重新申请,申请成功,可操作排班。</span>
                                        : statusObj.code == "05" ? <span>您的坐诊申请已撤回...请重新申请,申请成功,可操作排班。</span>
                                            : statusObj.code == "06" ? <span>您暂未提交坐诊申请...立即申请,申请成功,可操作排班。</span>
                                                : ""
                            }</p>
                        </div> : <div>
                                <Row style={{
                                    borderBottom: "1px solid rgb(232, 232, 232)",
                                    paddingBottom: "10px"
                                }}>
                                    {
                                        accountOp
                                    }
                                </Row>
                                <Row>
                                    <Col span={8} style={{ borderRight: "1px solid rgb(232, 232, 232)", paddingRight: "10px" }}>
                                        <div className="title-flex">
                                            <span className="title-dom" >
                                                <span></span>
                                                <span>排班日历</span>
                                            </span>
                                            <Radio.Group className="type-dom" value={this.state.typeValue} buttonStyle="solid" onChange={(e) => this.handleType(e)}>
                                                <Radio.Button value="single">单一设置</Radio.Button>
                                                <Radio.Button value="batch">批量设置</Radio.Button>
                                            </Radio.Group>
                                        </div>
                                        {/* <!-- 日历年月 --> */}
                                        <div>
                                            <div className="calendar_head">{monthstr[month - 1]}月</div>
                                            <div className="calendar_title">
                                                <div title={new Date(year + "/" + month).getTime() <= nowYearMDate ? "历史月份排班不允许修改" : ""}
                                                    className={new Date(year + "/" + month).getTime() <= nowYearMDate ? "iconPrev" : "icon"}
                                                    onClick={new Date(year + "/" + month).getTime() <= nowYearMDate ? "" : this.lastMonth}>
                                                    <div >上个月</div>
                                                </div>
                                                <div className="calendar_head">{year}</div>
                                                <div className='icon' onClick={this.nextMonth}>
                                                    <div>下个月</div>
                                                </div>
                                            </div>
                                        </div>
                                        <div className='calendar'>
                                            <div className='header'>
                                                {dateop}
                                                <div></div>
                                            </div>
                                        </div>
                                        <div className='date-box'>
                                            <div className='nowDay'>
                                                <div className='date-head' data-year='{{year}}' data-month='{{month}}' data-datenum='{{item.dateNum}}'>
                                                    <div>
                                                        {
                                                            dateArr && dateArr.map((item, i) => {
                                                                return (
                                                                    <div className={item.isToday == this.state.activeDate &&
                                                                        this.state.typeValue == "single" ? "date-Block date-active"
                                                                        : item.lookDateBActive == true &&
                                                                            this.state.typeValue == "batch" ? "date-Block date-active" :
                                                                            "date-Block"} title={item.nowYearMonthDate < nowYearMonthDate ? "历史日期排班不允许修改" :
                                                                                ""} onClick={() => item.nowYearMonthDate < nowYearMonthDate ? "" : this.lookActive(item,"N")}>
                                                                        <div className={item.nowYearMonthDate < nowYearMonthDate ? "e8e8e-color" :
                                                                            item.textCode != "U" && this.state.typeValue == "batch" ?
                                                                                "e8e8e-color" : ""}>
                                                                            <div className={item.nowYearMonthDate < nowYearMonthDate ? "e8e8e-color"
                                                                                : item.textCode != "U" && this.state.typeValue == "batch" ?
                                                                                    "e8e8e-color" : "calendar_head"}>{item.dateNum}</div>
                                                                            <div className={item.textCode == "U" ? "gary-item base-item" :
                                                                                item.textCode == "S" ? "stop-item base-item" :
                                                                                    item.textCode == "N" ? "border-item base-item" :
                                                                                        ""}>{item.dateSub}
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                )
                                                            })
                                                        }

                                                    </div>
                                                </div>
                                            </div>
                                            {/* (如需跨月批量设置，请依次切换至下个月) */}
                                            <Checkbox checked={this.state.checkValue} disabled style={{ display: (this.state.typeValue == "batch" ? "block" : "none") }}
                                                onChange={this.handleCheckAll}>全选
                                                </Checkbox>
                                        </div>
                                        <div style={{ display: (this.state.typeValue == "batch" ? "block" : "none") }}>
                                            <span className="title-dom">
                                                <span></span>
                                                <span>批量排班提示</span>
                                            </span>
                                            <p>
                                                您已选择排班天数：<span>{this.state.lookDateBLength}天</span>
                                            </p>
                                            <p style={{ color: "#828282" }}>注意：批量设置仅提供批量添加排班的功能，且无法修改已排班的时段</p>
                                        </div>
                                        <div className="single-dom" style={{ display: (this.state.typeValue == "single") ? "block" : "none" }}>
                                            <span className="title-dom" >
                                                <span></span>
                                                <span>{this.state.isToday}<b>排班</b></span>
                                            </span>
                                            <Table
                                                style={{ height: store.getState().tableHeight.y - 532 + 'px', }}
                                                columns={columns}
                                                pagination={false}
                                                dataSource={this.state.schedulingsArr && this.state.schedulingsArr.length > 0 ? this.state.schedulingsArr : []}
                                                rowKey={(row) => {
                                                    return row.id
                                                }}
                                                className="clearBackground"
                                                onRow={this.onClickRow}
                                                rowClassName={this.setRowClassName}
                                                bordered
                                            />
                                        </div>
                                    </Col>
                                    <Col span={16} className="batch-dom" style={{ paddingLeft: "4px",height:"676px",overflowY:"auto",overflowX:"hidden", display: (this.state.typeValue == "batch") ? "block" : "none" }}>
                                        <span className="title-dom" style={{ marginBottom: "0" }}>
                                            <span></span>
                                            <span>批量设置</span>
                                        </span>
                                        {batchSetingBlock}
                                        <Row style={{ textAlign: "center", marginTop: "12px" }}>
                                            <Button disabled type="primary" onClick={this.handleSaveBatch}>保存排班</Button>
                                        </Row>
                                    </Col>
                                    <Col span={16} className="sing-dom" style={{ paddingLeft: "4px", display: (this.state.typeValue == "single") ? "block" : "none" }}>
                                        <span className="title-dom" >
                                            <span></span>
                                            <span>{this.state.isToday} / {this.state.timeRange}<b>排班设置</b></span>
                                        </span>
                                        <Row>
                                            <Col span={6}>
                                                号别：<Select style={{ width: '68%' }}
                                                    dropdownMatchSelectWidth={false}
                                                    showSearch
                                                    filterOption={(input, option) =>
                                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                        || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    }
                                                    value={this.state.shiftType}
                                                    onChange={Util.handleSelectChange.bind(this, "shiftType")}
                                                    getPopupContainer={triggerNode => triggerNode.parentNode}
                                                    disabled
                                                >
                                                    {shiftTypeOp}
                                                </Select>
                                            </Col>
                                            <Col span={6}>
                                                时间间隔：<Select style={{ width: '55%' }}
                                                    showSearch
                                                    filterOption={(input, option) =>
                                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                        || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    }
                                                    disabled
                                                    // disabled={this.state.timeIntervalStaus}
                                                    value={this.state.timeIntervalID}
                                                    onChange={Util.handleSelectChange.bind(this, "timeIntervalID")}
                                                    getPopupContainer={triggerNode => triggerNode.parentNode}
                                                >
                                                    {timeIntervalOp}
                                                </Select>
                                            </Col>
                                            <Col span={8} className="edit-button">
                                                <Button disabled type="primary" onClick={this.handleSave}>保存</Button>
                                                <Button disabled title={!this.state.canStop ? "该医生未授权操作" : this.state.modalArr.length == 0 ? "暂无可停诊数据" : ""}
                                                //  disabled={this.state.modalArr.length == 0 || !this.state.canStop}
                                                  style={{ margin: "0 8px" }} onClick={() => this.handleRightStop("1", this.state.modalArr)}>停诊</Button>
                                                <Button disabled title={!this.state.canStop ? "该医生未授权操作" : this.state.modalArrOne.length == 0 ? "暂无可恢复坐诊数据" : ""}
                                                //  disabled={this.state.modalArrOne.length == 0 || !this.state.canStop}
                                                  onClick={() => this.handleRightStop("2", this.state.modalArrOne)}>恢复坐诊</Button>
                                            </Col>
                                            <Table
                                                style={{ marginTop: "44px" }}
                                                columns={rightColumns}
                                                pagination={false}
                                                dataSource={this.state.rightData && this.state.rightData.length > 0 ? this.state.rightData : []}
                                                rowKey={(row) => {
                                                    return row.resTimeID
                                                }}
                                                className="clearBackground"
                                                // onRow={this.onClickRow}
                                                // rowClassName={this.setRowClassName}
                                                bordered
                                            />
                                        </Row>
                                    </Col>
                                </Row>
                                <Modal
                                    key='2'
                                    width='600px'
                                    visible={this.state.visible}
                                    title={this.state.isMod == "1" ? "请选择您需要停诊的时段" : "请选择需要恢复坐诊的时段"}
                                    onOk={this.handleOk}
                                    onCancel={this.handleCancel}
                                    footer={[
                                        <Button key="submitc" type="primary" onClick={this.handleCancel}>取消</Button>,
                                        <Button key="submits" type={this.state.isMod != "1" ? "primary" : "danger"} onClick={this.handleOk}>{this.state.isMod == "1" ? "确定停诊" : "确定恢复"}</Button>,
                                    ]}>
                                    <div>
                                        <Table
                                            rowSelection={rowSelection_right}
                                            columns={columnsModal}
                                            pagination={false}
                                            dataSource={this.state.modalCenter && this.state.modalCenter.length > 0 ? this.state.modalCenter : []}
                                            rowKey={(row) => {
                                                return row.resTimeID
                                            }}
                                            className="clearBackground"

                                            bordered
                                        />
                                    </div>
                                </Modal>
                            </div>
                    }

                </div>
            )
        }
    })
export default ShiftSetting    