<template>
  <div class="app-container app-calendar-container">
    <div style="display: flex;justify-content: space-between;">
      <div>
        <el-button type="primary" v-hasPermi="['ticketMr:schedulingConfiguration:add']" @click="handleAdd('ADD')">配置排期</el-button>
        <el-button type="primary" v-hasPermi="['ticketMr:schedulingConfiguration:delect']" @click="checkIsClear()">批量清空</el-button>
        <el-button type="primary" @click="quickQueryFun()">快速查询</el-button>
      </div>
      <div>
        <el-button type="primary" v-hasPermi="['ticketMr:schedulingConfiguration:release']" @click="clearCalendarPrice(1)">批量启用</el-button>
        <el-button type="primary" v-hasPermi="['ticketMr:schedulingConfiguration:release']" @click="clearCalendarPrice(2)">批量禁用</el-button>
      </div>
    </div>
    <div v-loading="loading" class="calendar-dialog">
      <el-calendar v-model="timeValue">
        <template
          slot="dateCell"
          slot-scope="{date, data}">
          <div 
          :class="['calendar_box', selectTime(data)]" 
          @mouseover="mouseoverFun(data)" 
          @click.stop="clickTimeFun(data)"
          >
            <div class="calendar_box-date" @click.stop="return ''">
              <span>
                {{ data.day.split('-').slice(1).join('-')  }}
                {{ data.day == moment().format("YYYY-MM-DD") ? '(今天)':''  }}
              </span>
              <span style="color: #BEBEBE;" @click.stop="handlePerFormList('ADD',data)" v-if="getPerFormList(data).length>0">详情</span>
            </div>
            <div 
            class="calendar_box-select"
            :style="{width: '100%', display: 'flex',flexWrap: 'wrap',height: height + 'px'}"
            
             >
              <div 
              :key="index"
              :style="{marginLeft: index%2 == 0?'':'20px',color: item.status == 1 ?'#6F86FA':'#909399'}"
              v-for="(item,index) in getPerFormList(data)"
              >
              {{ item.performTimeStart }}-{{ item.performTimeEnd }}
              </div>
            </div>
          </div>
        </template>
      </el-calendar>
    </div>
    <!-- 排期配置  -->
     <addAndEdit ref="addAndEdit"  @getList="getList" />
  
    <!-- 排期列表 -->
    <perFormListBox ref="perFormListBox" @getList="getList" />

    <!-- 快速查询 -->
     <quickQuery ref="quickQuery" />
  </div>
</template>

<script>

import { 
  calendarList,
  deleteByDateApi,
  updateStatusByDateApi
 } from '@/api/ticketMr/schedulingConfiguration'

import moment from "moment"
import calendarBox from './dialog/calendarBox.vue';

import perFormListBox from './dialog/perFormListBox.vue';
import addAndEdit from "./dialog/addAndEdit";
import quickQuery from './dialog/quickQuery.vue';
export default {
  name: "SchedulingConfiguration",
  dicts: [],
  components: { calendarBox,perFormListBox,addAndEdit,quickQuery },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        startDate: null,
        endDate: null,
      },
      timeValue: new Date(),
      timeValueObj: {
        prev: null,
        next: null,
        hover: null
      },

      perFormList: [],
      showCalendar: false,
      today: moment().format("YYYY-MM-DD"),
      height: 86,
    };
  },
  created() {
    this.showCalendar = false
    this.queryParams = {
        startDate: moment(this.timeValue).startOf('month').format("YYYY-MM-DD"),
        endDate: moment(this.timeValue).endOf('month').format("YYYY-MM-DD"),
      }
    this.getList();
  },
  methods: {
    moment,
    /** 查询列表 */
    getList() {
      this.loading = true;
      let params = JSON.parse(JSON.stringify(this.queryParams))
      calendarList(this.addDateRange({...params}, this.dateRange))
      .then(response => {
          // console.log(response)
          let list = response.data.rows || []
          let l = 1
          list.forEach((item,index)=>{
            if(item.list && item.list.length>l) {
              l = item.list.length
            }
          })
          this.height = (Math.floor(l/2) * 30 < 90) ? 90 : (Math.floor(l/2) * 30)
          this.perFormList = list
          this.showCalendar = true
          this.loading = false;
        }
      ).catch(() => {
        this.loading = false;
      });
    },
    getPerFormList(data) {
      let list = []
      this.perFormList.forEach((item,index)=>{
        if(item.performDate == data.day) {
          list = item.list
        }
      })
      return list
    },
    /** 选中得时间  */
    selectTime(data) {
      let srt = ''
      let newTime = moment(data.day).startOf('day').valueOf()
      let newTime1 = moment().startOf('day').valueOf()
      if(newTime < newTime1 ) {
        return "disable_time"
      }
      if( this.timeValueObj ) {
        if( this.timeValueObj.prev && this.timeValueObj.next ) {
          let minTime = moment(this.timeValueObj.prev).valueOf()
          let maxTime = moment(this.timeValueObj.next).valueOf()
          if(newTime == minTime || newTime == maxTime) {
            return 'is-select_time_self'
          }
          if(minTime > maxTime){
            if(minTime >= newTime && maxTime <= newTime){
              srt = 'is-select_time'
            }
          }else {
            if(minTime <= newTime && maxTime >= newTime){
              srt = 'is-select_time'
            }
          }
        }else if( this.timeValueObj.prev && !this.timeValueObj.next && this.timeValueObj.hover ){
          let minTime = moment(this.timeValueObj.prev).valueOf()
          let maxTime = moment(this.timeValueObj.hover).valueOf()
          if(newTime == minTime || newTime == maxTime) {
            return 'is-select_time_self'
          }
          if(minTime > maxTime){
            if(minTime >= newTime && maxTime <= newTime){
              srt = 'is-select_time_hover'
            }
          }else {
            if(minTime <= newTime && maxTime >= newTime){
              srt = 'is-select_time_hover'
            }
          }
        }else if(this.timeValueObj.prev) {
          let minTime = moment(this.timeValueObj.prev).valueOf()
          if(newTime == minTime) {
            return 'is-select_time_self'
          }
        }
      }
      return srt
    },
    clickTimeFun(data) {
      let newTime1 = moment(data.day).startOf('day').valueOf()
      let newTime = moment().startOf('day').valueOf()
      if(newTime1 < newTime ) {
        return 
      }
      if(moment(data.day).format("YYYY-MM") != moment(this.timeValue).format("YYYY-MM") ) {
        return
      }
      if( !this.timeValueObj || !this.timeValueObj.prev ) {
        this.timeValueObj.prev = moment(data.day).format("YYYY-MM-DD")
      }else if( this.timeValueObj.prev && !this.timeValueObj.next ){
        this.timeValueObj.next = moment(data.day).format("YYYY-MM-DD")
      }else if( this.timeValueObj.prev && this.timeValueObj.next ) {
        this.timeValueObj.prev = moment(data.day).format("YYYY-MM-DD")
        this.timeValueObj.next = null
      }
    },
    mouseoverFun(data) {
      if(moment(data.day).format("YYYY-MM") != moment(this.timeValue).format("YYYY-MM") ) {
        return
      }
      if( this.timeValueObj.prev && !this.timeValueObj.next ){
        this.timeValueObj.hover = moment(data.day).format("YYYY-MM-DD")
        this.timeValue = new Date(this.timeValueObj.hover)
      }
    },
    
    /** 新增按钮操作 */
    handleAdd(type) {
      if( this.timeValueObj.prev && this.timeValueObj.next ) {
        this.openPrice = true
        this.formPrice = {}
        let obj = {}
        let minTime = moment(this.timeValueObj.prev).valueOf()
        let maxTime = moment(this.timeValueObj.hover).valueOf()
        if(minTime > maxTime){
          obj['next'] = this.timeValueObj.prev
          obj['prev'] = this.timeValueObj.next
        }else {
          obj['prev'] = this.timeValueObj.prev
          obj['next'] = this.timeValueObj.next
        }
        this.$nextTick(()=>{
          this.$refs["addAndEdit"].openDialog("配置排期", obj, type);
        })
      }else {
        this.$message.error("请选择时间区间!!!");
      }
    },
    quickQueryFun(type){
      this.$refs["quickQuery"].openDialog("快速查询", null, type);
    },
    /** 排期列表 */
    handlePerFormList(type,data) {
      this.$refs["perFormListBox"].openDialog("排期详情", {performDate: data.day},type);
    },
    // 获取日历显示时间范围
    getRange(date){
      // 日历第一天
      let firstDay = '';
      // 日历最后一天
      let lastDay = '';
      // 今天
      const today = date ? date : new Date()
      // 上月
      const m = today.getMonth()
      // 本月
      const cm = m + 1
      // 下月
      const lm = m + 2 > 12 ? 1 : m + 2
      // 要显示的本月
      const currentMonth = cm < 10 ? '0' + cm : cm
      // 要显示的本本年
      const currentYear = today.getFullYear()
      // 要显示的上个月的年份，m = 0 则当前1月，上月则是去年12月
      const prevYear = m == 0 ? currentYear - 1 : currentYear
      const prevMonth = m == 0 ? 12 : m < 10 ? '0' + m : m
      // 上个月天数
      const pmd = new Date(prevYear, m, 0).getDate()
      // 下个月的年份，当前12月，则需要加一年
      const lastYear = cm + 1 > 12 ? currentYear + 1 : currentYear
      const lastMonth = lm < 10 ? '0' + lm : lm
      // 1号是周几
      const firstWeek = new Date(today.setDate(1)).getDay()
      // 如果是周日，则不需要显示上个月
      if (firstWeek == 0) {
        firstDay = `${currentYear}-${currentMonth}-01`
      }
      // 其他周几，对应用上个月的天数往前推算
      else {
        firstDay = `${prevYear}-${prevMonth}-${pmd - (firstWeek - 1)}`
      }
      // 这个月天数
      const currentMonthDate = new Date(currentYear, cm, 0).getDate()
      // 最后一天是周几
      const lastWeek = new Date(today.setDate(currentMonthDate)).getDay()
      // 周六显示当月最后一天
      if (lastWeek == 6) {
        lastDay = `${currentYear}-${currentMonth}-${currentMonthDate}`
      }
      // 其他周几，对应往后推算
      else {
        const day = ['06', '05', '04', '03', '02', '01']
        lastDay = `${lastYear}-${lastMonth}-${day[lastWeek]}`
      }
      // console.log('第一天', firstDay)
      // console.log('最后一天', lastDay)
      this.queryParams = {
        startDate: firstDay,
        endDate: lastDay,
      }
      this.getList();
    },
    /**  时间调整顺序  */
    setTimeValueObj(){
      if (this.timeValueObj.prev && this.timeValueObj.next) {
        let minTime = moment(this.timeValueObj.prev).valueOf()
        let maxTime = moment(this.timeValueObj.next).valueOf()
        let startDate = null
        let endDate = null
        if (minTime > maxTime) {
          startDate = this.timeValueObj.next
          endDate = this.timeValueObj.prev
        } else {
          startDate = this.timeValueObj.prev
          endDate = this.timeValueObj.next
        }
        return {
          startDate,
          endDate
        }
      } else {
        this.$message.error("请选择时间区间!!!");
        return false
      }
    },
    checkIsClear(){
      if (this.timeValueObj.prev && this.timeValueObj.next) {
        let minTime = moment(this.timeValueObj.prev).valueOf()
        let maxTime = moment(this.timeValueObj.next).valueOf()
        let startDate = null
        let endDate = null
        if (minTime > maxTime) {
          startDate = this.timeValueObj.next
          endDate = this.timeValueObj.prev
        } else {
          startDate = this.timeValueObj.prev
          endDate = this.timeValueObj.next
        }
        this.$modal.confirm('确定要清空勾选"' + startDate + '——' + endDate + '"的日期范围内的数据吗？').then(()=> {
          this.deleteCalendarPrice()
        }).catch(() => {});
      } else {
        this.$message.error("请选择时间区间!!!");
      }
    },
    /** 一键清除  */
    async deleteCalendarPrice() {
      try {
        if( this.timeValueObj.prev && this.timeValueObj.next ) {
          let minTime = moment(this.timeValueObj.prev).valueOf()
          let maxTime = moment(this.timeValueObj.next).valueOf()
          let startDate = null
          let endDate = null
          if(minTime > maxTime){
            startDate = this.timeValueObj.next
            endDate = this.timeValueObj.prev
          }else {
            startDate = this.timeValueObj.prev
            endDate = this.timeValueObj.next
          }
          let res = await deleteByDateApi({
            startDate: startDate,
            endDate: endDate
          })
          if(res.code == 200) {
            this.openPrice = false
            this.$modal.msgSuccess(res.msg);
            this.getList()
          }
        }else {
          this.$message.error("请选择时间区间!!!");
        }
      } catch (error) {
        
      }
    },
    /** 批量禁用/启用  */
    async clearCalendarPrice(type) {
      try {
        let timeS = this.setTimeValueObj()
        if(!timeS) return
        this.$modal.confirm(`确定要批量${ type == 1 ? '启用' : '禁用' }" ${timeS.startDate} —— ${timeS.endDate} "的日期范围内的场次吗？`).then(async ()=> {
          let res = await updateStatusByDateApi({
            startDate: timeS.startDate,
            endDate: timeS.endDate,
            status: type
          })
          if (res.code == 200) {
            this.$modal.msgSuccess(res.msg);
            this.timeValueObj = {
              prev: null,
              next: null,
              hover: null
            }
            this.getList()
          }
        }).catch(() => {});
      } catch (error) {
        
      }
    },
  },
  watch:{
    timeValue(newValue,oldValue){
      let time = moment(newValue).format("YYYY-DD-MM")
      if (newValue.getFullYear() !== oldValue.getFullYear() || newValue.getMonth() !== oldValue.getMonth()) {
        this.getRange(newValue)
      }
    }
  }
};
</script>
<style scoped lang="scss">
.is-selected {
  color: #1989FA;
}
.app-calendar-container ::v-deep .el-calendar-day {
  padding-bottom: 0px !important;
  padding-left: 0px !important;
  padding-right: 0px !important;
  padding-top: 0px !important;
  height: auto;
    //min-height: 86px;
}
.app-calendar-container ::v-deep .is-today {
  background-color: rgba(255, 240, 24, 0);
  .calendar_box {
    border: 1px solid #0F40F5;
  }
}
.app-calendar-container ::v-deep .prev {
  background-color: rgba(223, 230, 236,0.5) !important;
}
.app-calendar-container ::v-deep .next {
  background-color: rgba(223, 230, 236,0.5) !important;
}
.today_yes {

}
.today_no {

}

/**  今天 */
.el-calendar-table td.is-today {
  .calendar_box {
    color: #0F40F5;
  }
}

.calendar_box{
  width: 100%;
  min-height: 86px;
  padding: 8px;
  .calendar_box-date {
    display: flex;
    width: 100% ;
    justify-content: space-between;
    

  }
}

.disable_time {
  .calendar_box-select {
    padding-top: 10px;
    user-select: none;
    cursor: not-allowed;
  }
}

.is-select_time_self {
  background-color: #C2D4FF;
}

.is-select_time {
  background-color: #E4ECFF;
}

.is-select_time_hover {
  background-color: #E4ECFF;
}
</style>
<style lang="scss">
.calendar-dialog ::v-deep .el-calendar-table .el-calendar-day {
  padding: none !important;
  height: auto;
}
</style>