<template>
    <div class="main-contain">
        <div class="position">
            <bread-crumb :crumbs="crumbs"></bread-crumb>
            <div style="display:flex;align-items:center">
                <el-button type="primary" @click="DeleteStaffSchedule">清除</el-button>
                <el-button type="primary" @click="copyStaffSchedule">复制</el-button>
                <el-button type="primary" icon="el-icon-printer" @click="toPrint">打印</el-button>
            </div>
        </div>
        <div class="app-container">
            <div class="cell clearfix">
                <el-input
                size="small"
                style="width: 150px;"
                class="filter-item"
                v-model.trim="keywords"
                placeholder="请输入医护人员姓名"
                @keyup.enter.native='toSearch'
                />
                <el-button
                size="small"
                class="filter-item"
                type="primary"
                icon="el-icon-search"
                @click="toSearch"
                >搜索</el-button
                >
                <el-select style="margin-left:10px;width:150px;" v-model="typeValue" placeholder="请选择" @change="changeOption">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
               <el-button @click="lastclick" type="text" style="margin:0 10px;">&lt;上一周({{ weekNum - 1 }})</el-button>
                <div class="dateBox">{{ weekDayArr[0] }}-{{ weekDayArr[6] }}({{ weekNum }})</div>
                <el-button @click="nextclick" type="text" style="margin:0 10px;">下一周({{ weekNum + 1 }})&gt;</el-button>
            </div>
            <div class="schedulingTable" style="display:flex;justify-content: space-between;">
                <div style="width: 70%">
                    <el-table :data="tableData" border :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)', color: '#606266'}" :row-style="{ color: '#303133' }"  @cell-click="clickThis" :cell-style="tableCellStyle">
                        <el-table-column prop="name" label="医护姓名" style="width:16%" align="center">
                            <template slot-scope="scope">
                                 {{scope.row.user_name}}
                            </template>
                        </el-table-column>
                        <el-table-column :label="'周一\n(' + weekDayArr[0] + ')'" style="width:200px" align="center">
                            <template slot-scope="scope">
                                <div @click="hangdleClick(scope.row,scope.$index,0)">
                                    <el-dropdown trigger="click" @command="changeSchedule">
                                        <span class="el-dropdown-link">
                                        {{ getClass(scope.row.user_name,1) }}<i v-if="getTimestamp(weekDayArr[0])>=timeNow && scope.row.admin_user_id!=1000000?true:false" class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                                        <el-dropdown-menu slot="dropdown" >
                                            <el-dropdown-item  :command="item.id" icon="el-icon-plus" :disabled="getTimestamp(weekDayArr[0])<timeNow?true:false" v-for="(item,index) in schedulelist" :key="index">{{item.class_name}}</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" :label="'周二\n(' + weekDayArr[1] + ')'" style="width:14%" align="center">
                             <template slot-scope="scope">
                                <div @click="hangdleClick(scope.row,scope.$index,1)">
                                    <el-dropdown trigger="click" @command="changeSchedule">
                                        <span class="el-dropdown-link">
                                        {{ getClass(scope.row.user_name,2) }}<i v-if="getTimestamp(weekDayArr[1])>=timeNow&&scope.row.admin_user_id!=1000000?true:false" class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                                        <el-dropdown-menu slot="dropdown" >
                                            <el-dropdown-item  :command="item.id" icon="el-icon-plus" :disabled="getTimestamp(weekDayArr[1])<timeNow?true:false" v-for="(item,index) in schedulelist" :key="index">{{item.class_name}}</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" :label="'周三\n(' + weekDayArr[2] + ')'" style="width:14%" align="center">
                             <template slot-scope="scope">
                                <div @click="hangdleClick(scope.row,scope.$index,2)">
                                    <el-dropdown trigger="click" @command="changeSchedule">
                                        <span class="el-dropdown-link">
                                        {{ getClass(scope.row.user_name,3) }}<i v-if="getTimestamp(weekDayArr[2])>=timeNow&&scope.row.admin_user_id!=1000000?true:false" class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                                        <el-dropdown-menu slot="dropdown" >
                                            <el-dropdown-item  :command="item.id" icon="el-icon-plus" :disabled="getTimestamp(weekDayArr[2])<timeNow?true:false" v-for="(item,index) in schedulelist" :key="index">{{item.class_name}}</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" :label="'周四\n(' + weekDayArr[3] + ')'" style="width:14%" align="center">
                             <template slot-scope="scope">
                                <div @click="hangdleClick(scope.row,scope.$index,3)">
                                    <el-dropdown trigger="click" @command="changeSchedule">
                                        <span class="el-dropdown-link">
                                        {{ getClass(scope.row.user_name,4) }}<i v-if="getTimestamp(weekDayArr[3])>=timeNow&&scope.row.admin_user_id!=1000000?true:false" class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                                        <el-dropdown-menu slot="dropdown" >
                                            <el-dropdown-item  :command="item.id" icon="el-icon-plus" :disabled="getTimestamp(weekDayArr[3])<timeNow?true:false" v-for="(item,index) in schedulelist" :key="index">{{item.class_name}}</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" :label="'周五\n(' + weekDayArr[4] + ')'" style="width:14%" align="center">
                             <template slot-scope="scope">
                                <div @click="hangdleClick(scope.row,scope.$index,4)">
                                    <el-dropdown trigger="click" @command="changeSchedule">
                                        <span class="el-dropdown-link">
                                        {{ getClass(scope.row.user_name,5) }}<i v-if="getTimestamp(weekDayArr[4])>=timeNow&&scope.row.admin_user_id!=1000000?true:false" class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                                        <el-dropdown-menu slot="dropdown" >
                                            <el-dropdown-item  :command="item.id" icon="el-icon-plus" :disabled="getTimestamp(weekDayArr[4])<timeNow?true:false" v-for="(item,index) in schedulelist" :key="index">{{item.class_name}}</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" :label="'周六\n(' + weekDayArr[5] + ')'" style="width:14%" align="center">
                             <template slot-scope="scope">
                                <div @click="hangdleClick(scope.row,scope.$index,5)">
                                    <el-dropdown trigger="click" @command="changeSchedule">
                                        <span class="el-dropdown-link">
                                        {{ getClass(scope.row.user_name,6) }}<i v-if="getTimestamp(weekDayArr[5])>=timeNow&&scope.row.admin_user_id!=1000000?true:false" class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                                        <el-dropdown-menu slot="dropdown" >
                                            <el-dropdown-item  :command="item.id" icon="el-icon-plus" :disabled="getTimestamp(weekDayArr[5])<timeNow?true:false" v-for="(item,index) in schedulelist" :key="index">{{item.class_name}}</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" :label="'周日\n(' + weekDayArr[6] + ')'" style="width:14%" align="center">
                             <template slot-scope="scope">
                                <div @click="hangdleClick(scope.row,scope.$index,6)">
                                    <el-dropdown trigger="click" @command="changeSchedule">
                                        <span class="el-dropdown-link">
                                        {{ getClass(scope.row.user_name,0) }}<i v-if="getTimestamp(weekDayArr[6])>=timeNow&&scope.row.admin_user_id!=1000000?true:false" class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                                        <el-dropdown-menu slot="dropdown" >
                                            <el-dropdown-item  :command="item.id" icon="el-icon-plus" :disabled="getTimestamp(weekDayArr[6])<timeNow?true:false" v-for="(item,index) in schedulelist" :key="index">{{item.class_name}}</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="classBox">
                    <div class="classTitle">班种</div>
                    <div class="classMain">
                        <div class="classMainBox">
                           <p v-for="(item,index) in schedulelist" :key="index">
                            {{item.class_name}}&nbsp;({{item.timeone_start}}~{{item.timeone_type}}{{item.timeone_end}} <span v-if="item.timetwo_start!=''">{{item.timetwo_start}}~{{item.timetwo_type}}{{item.timetwo_end}}</span> )
                           </p>
                        </div>
                        <el-checkbox style="text-align:center;padding-bottom: 10px;"  v-model="isChecked" @change="toContinuous">连续排班</el-checkbox>
                    </div>
                </div>
            </div>
            <el-dialog
                title="复制排班"
                width="600px"
                :visible.sync="newVisible"
            >
            <el-form :model="form"  ref="form" label-width="90px" :rules="rules">
                <el-form-item label="复制到 : " required  prop="copyWeek">
                    <el-select v-model="form.copyWeek" placeholder="请选择">
                        <el-option
                        v-for="item in typeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="newVisible=false">取 消</el-button>
                <el-button type="primary" @click="submitAction('form')">保 存</el-button>
            </div>
            </el-dialog>
        </div>
    </div>
</template>


<script>
const moment = require('moment')
import BreadCrumb from '@/xt_pages/components/bread-crumb'
import { getDoctorList,getScheduleList,addSchedule,getStaffScheduleList,getNextWeekList,getScheduleByDoctorId,toSearchScheduleList,DeleteStaffSchedule,copyStaffSchedule,UpdateContinusSchedule } from '@/api/doctorSchedule'
export default {
    components:{
        BreadCrumb
    },
    data(){
        return{
            crumbs: [
                { path: false, name: '医护排班' },
                { path: '/medicalScheduling/index', name: '医护排班' }
            ],
            keywords:'',
            options: [{
                value: '0',
                label: '全部'
            }, {
                value: '2',
                label: '医生'
            }, {
                value: '3',
                label: '护士'
            }],
            typeValue:'0',
            tableData: [],
            isChecked:true,
            schedulelist:[],
            weekNum:'',
            weekDayArr:[],
            todayDate:'',
            clen:7,
            nowYear: new Date().getFullYear(),
            schedule_week:0,
            docobj:{},
            class_name:"",
            doctorlist:[],
            schedule_date:"",
            newVisible:false,
            typeOptions:[],
            timeOptions:[],
            copyWeek:'',
            weekList: [],
            currentFirstDate1: '',
            form:{
              copyWeek:"",
            },
           rules: {
             copyWeek: [{ required: true, message: "请选择复制时间段", trigger: "blur" }],  
           },
           timeNow:0,
           arrZero:[],
           arrOne:[],
           arrTwo:[],
           arrThree:[],
           arrFour:[],
           arrFive:[],
           arrSix:[],
           arrSeven:[],
        }
    },
    methods:{
        search(){},
        toPrint(){
            this.$router.push({
                path: '/medicalScheduling/schedule/print?starttime='+this.getTimestamp(this.weekDayArr[0])+"&endtime="+this.getTimestamp(this.weekDayArr[6])+"&weekArr="+ this.weekDayArr+'&typeValue='+this.typeValue,
            })
        },
        getDoctorList(){
            getDoctorList().then(response=>{
                if(response.data.state == 1){
                    var list =  response.data.data.list
                    // console.log("医护列表",list)
                    this.tableData = list
                    this.doctorlist = list
                    //获取班种列表
                    this.getStaffScheduleList()
                }
            })
        },
        getScheduleList(){
            getScheduleList().then(response=>{
                if(response.data.state == 1){
                    var schedulelist = response.data.data.scheduleList
                    // console.log("schedulelist",schedulelist)
                    for(let i=0;i<schedulelist.length;i++){
                    if(schedulelist[i].timeone_type == 1){
                        schedulelist[i].timeone_type = "当日"
                    }
                    if(schedulelist[i].timeone_type == 2){
                        schedulelist[i].timeone_type = "次日"
                    }
                    if(schedulelist[i].timetwo_type == 1){
                        schedulelist[i].timetwo_type = "当日"
                    }
                    if(schedulelist[i].timetwo_type == 2){
                        schedulelist[i].timetwo_type = "次日"
                    }
                    }
                    this.schedulelist = schedulelist
                }
            }) 
        },
        hangdleClick(val,index,num){
        //  console.log("val",val)
         this.docobj = val
         if(this.getTimestamp(this.weekDayArr[num]) < this.timeNow){
            this.$message.error("过去日期不可以编辑")
            return
         }
        },
        clickThis(row, column, cell, event){
            var week = (column.label).split('');
            var weeks = week[0]+week[1]
            if(weeks == "周日"){
            this.schedule_week = 0
            this.schedule_date = this.weekDayArr[6]
            }
            if(weeks == "周一"){
            this.schedule_week = 1
            this.schedule_date = this.weekDayArr[0]
            }
            if(weeks=="周二"){
            this.schedule_week = 2
            this.schedule_date = this.weekDayArr[1]
            }
            if(weeks=="周三"){
            this.schedule_week = 3
            this.schedule_date = this.weekDayArr[2]
            }
            if(weeks=="周四"){
            this.schedule_week = 4
            this.schedule_date = this.weekDayArr[3]
            }
            if(weeks == "周五"){
            this.schedule_week = 5
            this.schedule_date = this.weekDayArr[4]
            }
            if(weeks== "周六"){
            this.schedule_week = 6
            this.schedule_date = this.weekDayArr[5]
            }
        },
        changeSchedule(id){
            var class_name = ""
            for(let i=0;i<this.schedulelist.length;i++){
            if(id == this.schedulelist[i].id){
                class_name = this.schedulelist[i].class_name
            }
            }
            let arr = [...this.tableData]
            // console.log("arr===",arr)
            for(let i=0;i<arr.length;i++){
            if(this.docobj.id == arr[i].id){
                arr[i].class_name = class_name
                arr[i].class_index = this.schedule_week
            }
            }
            // console.log("arr",arr)
            this.tableData = arr
            const params = {
            doctor_id:this.docobj.admin_user_id,
            doctor_type:this.docobj.user_type,
            schedule_type:id,
            schedule_week:this.schedule_week,
            start_time:this.getTimestamp(this.weekDayArr[0]),
            end_time:this.getTimestamp(this.weekDayArr[6]),
            schedule_date:this.getTimestamp(this.schedule_date)
            }
            // console.log("params",params)
            
            addSchedule(params).then(response=>{
            if(response.data.state == 1){
                var schedule = response.data.data.schedule
                // console.log("schedule",schedule)
                this.$message.success("保存成功")
                this.getStaffScheduleList()
                }
            })
        },
        formatDate(date){      
            var year = date.getFullYear()+'.'       
            var month = (date.getMonth()+1)+'.';
            var day = date.getDate();
            return year+month+day
        }, 
        formatDateTwo(date){      
            var year = date.getFullYear()+'.'       
            var month = (date.getMonth()+1)+'.';
            var day = date.getDate();
            return year+month+day
        }, 
        addDate(date,n){        
            date.setDate(date.getDate()+n);        
            return date;
        },  
            //
        setDate(date){           
            var week = date.getDay()-1;
            date = this.addDate(date,week*-1);
            this.currentFirstDate = new Date(date);
            this.currentDate = new Date(date)
            for(var i = 0;i<this.clen; i++){     
                this.weekDayArr.push(this.formatDate(i==0 ? date : this.addDate(date,1)))
            }         
        },
            //上一周 
        lastclick(){
            this.weekDayArr=[]
            this.setDate(this.addDate(this.currentFirstDate,-7));   
            if (this.weekNum == 1) {
                let year = this.nowYear - 1
                let month = 12
                let date = 31
                this.weekNum = this.getYearWeek(year, month, date)
                this.nowYear = this.nowYear - 1
            }
            this.weekNum = this.weekNum - 1
            this.getNextWeekList()
        },
            //下一周
        nextclick(){ 
            this.weekDayArr=[]                
            this.setDate(this.addDate(this.currentFirstDate,7));
            this.weekNum = this.weekNum + 1
            if (this.weekNum == 53) {
                let year = this.nowYear + 1
                let month = 1
                let date = 1
                this.weekNum = this.getYearWeek(year, month, date)
                this.nowYear = this.nowYear + 1
            }
            this.getNextWeekList()
        },

        getYearWeek(year,month,date){
        /*  
            dateNow是当前日期 
            dateFirst是当年第一天  
            dataNumber是当前日期是今年第多少天  
            用dataNumber + 当前年的第一天的周差距的和在除以7就是本年第几周  
        */      
        let dateNow = new Date(year, parseInt(month) - 1, date);
        let dateFirst = new Date(year, 0, 1);
        let dataNumber = Math.round((dateNow.valueOf() - dateFirst.valueOf()) / 86400000);
        return Math.ceil((dataNumber + ((dateFirst.getDay() + 1) - 1)) / 7);        
        },
        getTimestamp(time) { //把时间日期转成时间戳
        return (new Date(time)).getTime() / 1000
        },
        beforeHandleCommand(item,row){
            return {
                'command': item,
                'row': row
            }
        },

        //获取所有医护排班数据
        getStaffScheduleList(){
            const params = {
            start_time:this.getTimestamp(this.weekDayArr[0]),
            end_time:this.getTimestamp(this.weekDayArr[6])
            }
            getStaffScheduleList(params).then(response=>{
                if(response.data.state == 1){
                    var staffList =  response.data.data.staffList                
                    var sevenStr = ""
                    var oneStr = ""
                    var twoStr = ""
                    var threeStr = ""
                    var fourStr = ""
                    var fiveStr = ""
                    var sixStr = ""
                    this.arrZero = []
                    this.arrOne = []
                    this.arrTwo = []
                    this.arrThree = []
                    this.arrFour = []
                    this.arrFive = []
                    this.arrSix = []
                
                    for(let i=0;i<staffList.length;i++){
                    if(staffList[i].schedule_week == 0){
                        staffList[i].class_index = 0
                         var arr = []
                        this.arrZero.push(staffList[i].class_name)
                        console.log("this.arrZero",this.arrZero)
                        for(let i=0;i<this.arrZero.length;i++){
                           if(this.arrZero[i]!=''){
                              arr.push(this.arrZero[i])
                           }
                        }
                        console.log("arr",arr)
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        var zeroStr = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            zeroStr += item + objVal[index] + '\n'
                        })
                        sevenStr = zeroStr
                    }
                    if(staffList[i].schedule_week == 1){
                        staffList[i].class_index = 1
                        var arr = []
                        this.arrOne.push(staffList[i].class_name)
                        for(let i=0;i<this.arrOne.length;i++){
                           if(this.arrOne[i]!=''){
                              arr.push(this.arrOne[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strOne = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strOne += item + objVal[index] + '\n'
                        })
                        oneStr  = strOne
                    }
                    if(staffList[i].schedule_week == 2){
                        staffList[i].class_index = 2
                         var arr = []
                        this.arrTwo.push(staffList[i].class_name)
                        for(let i=0;i<this.arrTwo.length;i++){
                           if(this.arrTwo[i]!=''){
                              arr.push(this.arrTwo[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strTwo = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strTwo += item + objVal[index] + '\n'
                        })
                         twoStr = strTwo
                    }
                    if(staffList[i].schedule_week == 3){
                        staffList[i].class_index = 3
                         var arr = []
                        this.arrThree.push(staffList[i].class_name)
                        for(let i=0;i<this.arrThree.length;i++){
                           if(this.arrThree[i]!=''){
                              arr.push(this.arrThree[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strThree = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strThree += item + objVal[index] + '\n'
                        })
                        threeStr = strThree
                    }
                    if(staffList[i].schedule_week == 4){
                        staffList[i].class_index = 4
                        var arr = []
                        this.arrFour.push(staffList[i].class_name)
                        for(let i=0;i<this.arrFour.length;i++){
                           if(this.arrFour[i]!=''){
                              arr.push(this.arrFour[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strFour = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strFour += item + objVal[index] + '\n'
                        })
                        fourStr = strFour
                    }
                    if(staffList[i].schedule_week == 5){
                        staffList[i].class_index = 5

                         var arr = []
                        this.arrFive.push(staffList[i].class_name)
                        for(let i=0;i<this.arrFive.length;i++){
                           if(this.arrFive[i]!=''){
                              arr.push(this.arrFive[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strFive = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strFive += item + objVal[index] + '\n'
                        })
                         fiveStr = strFive
                    }
                    if(staffList[i].schedule_week == 6){
                        staffList[i].class_index = 6
                         var arr = []
                        this.arrSix.push(staffList[i].class_name)
                        for(let i=0;i<this.arrSix.length;i++){
                           if(this.arrSix[i]!=''){
                              arr.push(this.arrSix[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strSix = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strSix += item + objVal[index] + '\n'
                        })
                        sixStr = strSix
                     }
                    }
                    console.log("周一",oneStr)
                    console.log("周er",twoStr)
                    console.log("周三",threeStr)
                    console.log("周四",fourStr)
                    console.log("周五",fiveStr)
                    console.log("周六",sixStr)
                    console.log("周日",sevenStr)
                    let tempArr = [], newArr = []
                    for (let i = 0; i < staffList.length; i++) {
                        if (tempArr.indexOf(staffList[i].user_name) === -1) {
                            newArr.push({
                                user_name: staffList[i].user_name,
                                admin_user_id:staffList[i].admin_user_id,
                                user_type:staffList[i].doctor_type,
                                list: [{class_name:staffList[i].class_name,schedule_week:staffList[i].schedule_week}]
                            })
                            tempArr.push(staffList[i].user_name);
                        } else {
                            for (let j = 0; j < newArr.length; j++) {
                                if (newArr[j].user_name == staffList[i].user_name) {
                                    newArr[j].list.push({class_name:staffList[i].class_name,admin_user_id:staffList[i].admin_user_id,schedule_week:staffList[i].schedule_week,user_type:staffList[i].doctor_type})
                                }
                            }
                        }
                    }
                    let arr = [...newArr]
                    arr.sort(this.compare('admin_user_id'))
                    this.doctorlist.sort(this.compare('admin_user_id'))
                    this.doctorlist.forEach((item, index) => {
                      if (arr[index] && item.admin_user_id == arr[index].admin_user_id) {
                    
                      }else{
                        arr.splice(index, 0, {user_name: item.user_name, admin_user_id: item.admin_user_id, list: [],user_type:item.user_type})
                      }
                    })
                    arr.sort(this.compare('user_type'))
                    
                    let arr2 = []
                    arr2.push({class_name:oneStr,schedule_week:1})
                    arr2.push({class_name:twoStr,schedule_week:2})
                    arr2.push({class_name:threeStr,schedule_week:3})
                    arr2.push({class_name:fourStr,schedule_week:4})
                    arr2.push({class_name:fiveStr,schedule_week:5})
                    arr2.push({class_name:sixStr,schedule_week:6})
                    arr2.push({class_name:zeroStr,schedule_week:0})
                    var obj = {}
                     obj.admin_user_id = "1000000"
                     obj.user_name = "合计"
                     obj.user_type = 10
                     obj.list = arr2
                     arr.push(obj)
                     console.log("arr------",arr)
                    this.tableData = []
                    this.tableData = arr
        
                
                }
            })
        },

        getClass(name,index){
            if(name != undefined){
                let newClass = '';
                this.tableData.map(item => {
                if(item.user_name == name){
                    if(item.list){
                        item.list.map(it => {
                            if(it.schedule_week == index){
                                newClass = it.class_name
                            }
                        })
                    }
                    
                }
                })
                return newClass
            }
        
        },

     unique(arr) { 
        const res = new Map();
        return arr.filter((arr) => !res.has(arr.admin_user_id) && res.set(arr.admin_user_id, 1))
     },
        
        //获取上一周下一周的排班数据
        getNextWeekList(){
            const params = {
                start_time:this.getTimestamp(this.weekDayArr[0]),
                end_time:this.getTimestamp(this.weekDayArr[6])
            }
            getNextWeekList(params).then(response=>{
                if(response.data.state == 1){
                    var staffList = response.data.data.staffList
                     var sevenStr = ""
                    var oneStr = ""
                    var twoStr = ""
                    var threeStr = ""
                    var fourStr = ""
                    var fiveStr = ""
                    var sixStr = ""
                           for(let i=0;i<staffList.length;i++){
                    if(staffList[i].schedule_week == 0){
                        staffList[i].class_index = 0
                         var arr = []
                        this.arrZero.push(staffList[i].class_name)
                        for(let i=0;i<this.arrZero.length;i++){
                           if(this.arrZero[i]!=''){
                              arr.push(this.arrZero[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        var zeroStr = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            zeroStr += item + objVal[index] + '\n'
                        })
                        sevenStr = zeroStr
                    }
                    if(staffList[i].schedule_week == 1){
                        staffList[i].class_index = 1
                        var arr = []
                        this.arrOne.push(staffList[i].class_name)
                        for(let i=0;i<this.arrOne.length;i++){
                           if(this.arrOne[i]!=''){
                              arr.push(this.arrOne[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strOne = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strOne += item + objVal[index] + '\n'
                        })
                        oneStr  = strOne
                    }
                    if(staffList[i].schedule_week == 2){
                        staffList[i].class_index = 2
                         var arr = []
                        this.arrTwo.push(staffList[i].class_name)
                        for(let i=0;i<this.arrTwo.length;i++){
                           if(this.arrTwo[i]!=''){
                              arr.push(this.arrTwo[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strTwo = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strTwo += item + objVal[index] + '\n'
                        })
                         twoStr = strTwo
                    }
                    if(staffList[i].schedule_week == 3){
                        staffList[i].class_index = 3
                         var arr = []
                        this.arrThree.push(staffList[i].class_name)
                        for(let i=0;i<this.arrThree.length;i++){
                           if(this.arrThree[i]!=''){
                              arr.push(this.arrThree[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strThree = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strThree += item + objVal[index] + '\n'
                        })
                        threeStr = strThree
                    }
                    if(staffList[i].schedule_week == 4){
                        staffList[i].class_index = 4
                        var arr = []
                        this.arrFour.push(staffList[i].class_name)
                        for(let i=0;i<this.arrFour.length;i++){
                           if(this.arrFour[i]!=''){
                              arr.push(this.arrFour[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strFour = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strFour += item + objVal[index] + '\n'
                        })
                        fourStr = strFour
                    }
                    if(staffList[i].schedule_week == 5){
                        staffList[i].class_index = 5

                         var arr = []
                        this.arrFive.push(staffList[i].class_name)
                        for(let i=0;i<this.arrFive.length;i++){
                           if(this.arrFive[i]!=''){
                              arr.push(this.arrFive[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strFive = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strFive += item + objVal[index] + '\n'
                        })
                         fiveStr = strFive
                    }
                    if(staffList[i].schedule_week == 6){
                        staffList[i].class_index = 6
                         var arr = []
                        this.arrSix.push(staffList[i].class_name)
                        for(let i=0;i<this.arrSix.length;i++){
                           if(this.arrSix[i]!=''){
                              arr.push(this.arrSix[i])
                           }
                        }
                        var countedNames = arr.reduce(function (allNames, name) { 
                            if (name in allNames) {
                                allNames[name]++;
                            }
                            else {
                                allNames[name] = 1;
                            }
                            return allNames;
                        }, {});
                        let objKey = Object.keys(countedNames)
                        let objVal = Object.values(countedNames)
                        let strSix = ''
                        objKey.map((item,index) => {
                        let objVal = Object.values(countedNames)
                            strSix += item + objVal[index] + '\n'
                        })
                        sixStr = strSix
                     }
                    }
                    let tempArr = [], newArr = []
                    for (let i = 0; i < staffList.length; i++) {
                        if (tempArr.indexOf(staffList[i].user_name) === -1) {
                        newArr.push({
                            user_name: staffList[i].user_name,
                            admin_user_id:staffList[i].admin_user_id,
                            user_type:staffList[i].doctor_type,
                            list: [{class_name:staffList[i].class_name,schedule_week:staffList[i].schedule_week}]
                        })
                        tempArr.push(staffList[i].user_name);
                        } else {
                        for (let j = 0; j < newArr.length; j++) {
                            if (newArr[j].user_name == staffList[i].user_name) {
                            newArr[j].list.push({class_name:staffList[i].class_name,admin_user_id:staffList[i].admin_user_id,schedule_week:staffList[i].schedule_week, user_type:staffList[i].doctor_type,})
                            }
                        }
                        }
                    }
                    let arr = [...newArr]
                    arr.sort(this.compare('admin_user_id'))
                    this.doctorlist.sort(this.compare('admin_user_id'))
                    this.doctorlist.forEach((item, index) => {
                      if (arr[index] && item.admin_user_id == arr[index].admin_user_id) {
                    
                      }else{
                        arr.splice(index, 0, {user_name: item.user_name, admin_user_id: item.admin_user_id, list: [],user_type:item.user_type})
                        // console.log("arr",arr)
                      }
                    })
                    arr.sort(this.compare('user_type'))
                    let arr2 = []
                    arr2.push({class_name:oneStr,schedule_week:1})
                    arr2.push({class_name:twoStr,schedule_week:2})
                    arr2.push({class_name:threeStr,schedule_week:3})
                    arr2.push({class_name:fourStr,schedule_week:4})
                    arr2.push({class_name:fiveStr,schedule_week:5})
                    arr2.push({class_name:sixStr,schedule_week:6})
                    arr2.push({class_name:zeroStr,schedule_week:0})
                    var obj = {}
                     obj.admin_user_id = "1000000"
                     obj.user_name = "合计"
                     obj.user_type = 10
                     obj.list = arr2
                     arr.push(obj)
                    this.tableData = arr
                }
            })
        },

        changeOption(id){
            const params = {
            start_time:this.getTimestamp(this.weekDayArr[0]),
            end_time:this.getTimestamp(this.weekDayArr[6]),
            doctor_id:id 
            }
            getScheduleByDoctorId(params).then(response=>{
                if(response.data.state == 1){
                    var  staffList =  response.data.data.staffList
                    // console.log("staffList",staffList)
    
                    let tempArr = [], newArr = []
                    for (let i = 0; i < staffList.length; i++) {
                        if (tempArr.indexOf(staffList[i].user_name) === -1) {
                            newArr.push({
                                user_type:staffList[i].doctor_type,
                                user_name: staffList[i].user_name,
                                admin_user_id:staffList[i].admin_user_id,
                                list: [{class_name:staffList[i].class_name,schedule_week:staffList[i].schedule_week}]
                            })
                            tempArr.push(staffList[i].user_name);
                        } else {
                            for (let j = 0; j < newArr.length; j++) {
                                if (newArr[j].user_name == staffList[i].user_name) {
                                    newArr[j].list.push({class_name:staffList[i].class_name,admin_user_id:staffList[i].admin_user_id,schedule_week:staffList[i].schedule_week, user_type:staffList[i].doctor_type})
                                }
                            }
                        }
                    }

                    if(id == 0){
                        let arr = [...newArr]
                        arr.sort(this.compare('admin_user_id'))
                        this.doctorlist.sort(this.compare('admin_user_id'))
                        this.doctorlist.forEach((item, index) => {
                          if (arr[index] && item.admin_user_id == arr[index].admin_user_id) {
                        
                          }else{
                            arr.splice(index, 0, {user_name: item.user_name, admin_user_id: item.admin_user_id, list: [],user_type:item.user_type})
                            // console.log("arr",arr)
                          }
                        })
                        arr.sort(this.compare('user_type'))
                        this.tableData = arr
                    }
                    if(id == 2){
                        let arr = [...newArr]
                        arr.sort(this.compare('admin_user_id'))
                        this.doctorlist.sort(this.compare('admin_user_id'))
                        let newDoctor = []
                        this.doctorlist.map(item => {
                        if (item.user_type == 2) {
                            newDoctor.push(item)
                        }
                        })
                        newDoctor.map((item, index) => {
                        if (arr[index] && item.admin_user_id == arr[index].admin_user_id) {
                        
                          }else{
                            arr.splice(index, 0, {user_name: item.user_name, admin_user_id: item.admin_user_id, list: []})
                            // console.log("arr",arr)
                          }
                        })
                        this.tableData = arr
                    }
                    if(id == 3){
                        let arr = [...newArr]
                        arr.sort(this.compare('admin_user_id'))
                        this.doctorlist.sort(this.compare('admin_user_id'))
                        let newDoctor = []
                        this.doctorlist.map(item => {
                        if (item.user_type == 3) {
                            newDoctor.push(item)
                        }
                        })
                        newDoctor.map((item, index) => {
                        if (arr[index] && item.admin_user_id == arr[index].admin_user_id) {
                        
                          }else{
                            arr.splice(index, 0, {user_name: item.user_name, admin_user_id: item.admin_user_id, list: []})
                            // console.log("arr",arr)
                          }
                        })
                        this.tableData = arr
                    }

            }
        })
        },
        toSearch(){
            const params = {
            user_name: this.keywords,
            start_time:this.getTimestamp(this.weekDayArr[0]),
            end_time:this.getTimestamp(this.weekDayArr[6])
            }
            toSearchScheduleList(params).then(response=>{
                if(response.data.state == 1){
                    var staffList =  response.data.data.staffList
                    let tempArr = [], newArr = []
                    for (let i = 0; i < staffList.length; i++) {
                        if (tempArr.indexOf(staffList[i].user_name) === -1) {
                            newArr.push({
                                user_name: staffList[i].user_name,
                                admin_user_id:staffList[i].admin_user_id,
                                list: [{class_name:staffList[i].class_name,schedule_week:staffList[i].schedule_week}]
                            })
                            tempArr.push(staffList[i].user_name);
                        } else {
                            for (let j = 0; j < newArr.length; j++) {
                                if (newArr[j].user_name == staffList[i].user_name) {
                                    newArr[j].list.push({class_name:staffList[i].class_name,admin_user_id:staffList[i].admin_user_id,schedule_week:staffList[i].schedule_week})
                                }
                            }
                        }
                    }

                    if(this.keywords != ''){
                        this.tableData = newArr
                    }else{
                        let arr = [...newArr]
                        arr.sort(this.compare('admin_user_id'))
                        this.doctorlist.sort(this.compare('admin_user_id'))
                        this.doctorlist.forEach((item, index) => {
                          if (arr[index] && item.admin_user_id == arr[index].admin_user_id) {
                        
                          }else{
                            arr.splice(index, 0, {user_name: item.user_name, admin_user_id: item.admin_user_id, list: []})
                            // console.log("arr",arr)
                          }
                        })
                        // console.log("arr",arr)
                        this.tableData = arr
                    }
                }
            })
        },

        DeleteStaffSchedule(){
            const params = {
            start_time:this.getTimestamp(this.weekDayArr[0]),
            end_time:this.getTimestamp(this.weekDayArr[6])
            }
            this.$confirm(
            '是否要清除当周排班? <br>清除后,信息将无法恢复',
            '删除提示',
            {
                dangerouslyUseHTMLString: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
            ).then(()=>{
            DeleteStaffSchedule(params).then(response=>{
                if(response.data.state == 1){
                    var msg =  response.data.data.msg
                    this.$message.success("清除成功")
                    this.getStaffScheduleList()
                }
            })
            })
        },

        copyStaffSchedule(){
            this.newVisible = true
            // const params = {
            //     start_time:this.getTimestamp(this.weekDayArr[0]),
            //     end_time:this.getTimestamp(this.weekDayArr[6])
            // }
            // copyStaffSchedule(params).then(response=>{
            //     if(response.data.state == 1){
            //     var msg =  response.data.data.msg
            //     console.log("msg",msg)
            //     this.$message.success("复制成功")
            //     }else{
            //     this.$message.error("排班已存在")
            //     }
            // }) 
        },
        toContinuous(){
            var is_status = 0
            if(this.isChecked == false){
            is_status = 0
            }
            if(this.isChecked == true){
            is_status = 1
            }
            const params = {
                is_status:is_status
            }
            UpdateContinusSchedule(params).then(response=>{
                if(response.data.state == 1){
                var schedule =  response.data.data.schedule
                this.$message.success("保存成功")
                }
            })
        },
        setDate1 (date) {
            var week = date.getDay() - 1
            date = this.addDate(date, week * -1)
            this.currentDate = new Date(date)
            let arr1 = []
            for (var i = 0; i < this.clen; i++) {
                arr1.push(this.formatDate(i == 0 ? date : this.addDate(date, 1)))
            }
            this.weekList.push(arr1)
            let num = this.weekNum
            this.currentFirstDate1 = num + 1
        },
        submitAction(formName){
            var label = ""
            for(let i=0;i<this.timeOptions.length;i++){
               if(this.form.copyWeek == this.timeOptions[i].value){
                 label = this.timeOptions[i].label
               }
            }
           var start = label.split('~')
           var copy_startime = this.getTimestamp(start[0])   
           var copy_endtime = this.getTimestamp(start[1]) 

            const params = {
              start_time:this.getTimestamp(this.weekDayArr[0]),
              end_time:this.getTimestamp(this.weekDayArr[6]),
              copy_startime:copy_startime,
              copy_endtime:copy_endtime,
            }
           this.$refs[formName].validate(valid=>{
              if(valid){
                copyStaffSchedule(params).then(response=>{
                   if(response.data.state == 1){
                     var msg = response.data.data.msg
                     this.$message.success("复制成功")
                     this.newVisible = false
                   }else{
                    this.$message.error("排班已存在")
                  }
                })
              }
           })
        },
        compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        },
       tableCellStyle (row, rowIndex, column) {
        // console.log("row",row.column.label)
         var week = (row.column.label).split('');
        //  console.log("week",week)
         var weeks = ""
         if (week.length == 14) {
            weeks = week[4]+week[5]+week[6]+week[7]+week[8]+week[9]+week[10]+week[11]+week[12]
         }
         if(week.length == 13){
           weeks = week[4]+week[5]+week[6]+week[7]+week[8]+week[9]+week[10]+week[11]
         }
        //  console.log("week",week)
        // console.log("weeks",weeks)
         var weekdate =  this.getTimestamp(weeks)
        //  console.log("日期",weekdate)
        //  console.log("当前日期",this.timeNow)
         if(weekdate  < this.timeNow){
           return 'background-color:#e5e5e5;'
          }
       },
    },
    created(){
        //获取医护人员
        this.getDoctorList()
        //获取班种
        this.getScheduleList()

        let year = new Date().getFullYear()
        let month = new Date().getMonth() + 1
        let date = new Date().getDate()
        this.weekNum = this.getYearWeek(year,month,date)
        this.todayDate=this.formatDate(new Date())
        this.setDate(new Date())

        for (var i = 0; i <= 9; i++) {
            this.setDate1(this.addDate(this.currentDate, 7))
        }
        let newNum = 0
        for(let i = 0; i < this.weekList.length; i++){
            if(this.weekNum + i + 1 <= 53){
                let num = this.weekNum + i + 1
                let str = this.weekList[i][0] + '~' + this.weekList[i][6] + '(' + num + ')'
                this.typeOptions.push({value:i,label:str})
                let stt = this.weekList[i][0] +"~"+this.weekList[i][6]
                this.timeOptions.push({value:i,label:stt})
            }else{
                
                newNum++
                let str = this.weekList[i][0] + '~' + this.weekList[i][6] + '(' + newNum + ')'
                this.typeOptions.push({value:i,label:str}) 
                let stt = this.weekList[i][0] +"~"+this.weekList[i][6]
                this.timeOptions.push({value:i,label:stt}) 
            }
            
        }
      var now = moment().locale('zh-cn').format('YYYY-MM-DD 00:00:00')
      this.timeNow = this.getTimestamp(now)
      
    }
}
</script>

<style lang="scss" scoped>
.dateBox{
    border: 1px solid #DCDFE6;
    height: 36px;
    line-height: 36px;
    text-align: center;
    padding: 0 10px;
    border-radius: 4px;
}
.classBox{
    width:28%;
    height: 100%;
    border: 1px solid #d0d3da;
    .classTitle{
        height: 42px;
        text-align: center;
        line-height: 42px;
        background-color: rgb(245, 247, 250);
        color: rgb(96, 98, 102);
        font-weight:bold;
        
    }
    .classMain{
        height: 400px;
        padding: 0 0 0 20px;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        >div>p{
            line-height: 30px;
            color: rgb(48, 49, 51);
        }
        .classMainBox{
            height: 350px;
            overflow-y: auto;
        }
    }
}
</style>
<style lang="scss">
.schedulingTable{
    .el-table th .cell {
        white-space: pre-line;/*保留换行符*/
    }
}

</style>
