<template>
  <div class="app-container app-calendar-container">
    <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 v-loading="loading" class="calendar-dialog">
      <el-calendar v-model="timeValue">
        <template
          slot="dateCell"
          slot-scope="{date, data}">
          <div 
          :class="['calendar_box', selectTime(data)]" 
          @click.stop="()=>''"
          >
            <div class="calendar_box-date">
              <span>{{ data.day.split('-').slice(1).join('-') }}</span>
              <span @click.stop="handlePerFormList('ADD',data)">详情</span>
            </div>
            
            <div 
            style="width: 100%; display: flex;flex-wrap: wrap;"
            @mouseover="mouseoverFun(data)" 
            @click.stop="clickTimeFun(data)"
             >
              <div 
              :key="index"
              :style="{marginLeft: index%2 == 0?'':'20px',color: item.status == 1 ?'#67c23a':'#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,
 } 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")
    };
  },
  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: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      let params = JSON.parse(JSON.stringify(this.queryParams))
      calendarList(this.addDateRange({...params}, this.dateRange))
      .then(response => {
          console.log(response)
          this.perFormList = response.data.rows
          this.showCalendar = true
          this.loading = false;
        }
      ).catch(() => {
        this.loading = false;
      });
    },
    getPerFormList(data) {
      let list = []
      this.perFormList.forEach((item,index)=>{
        if(item.performDate == data.day) {
          console.log("dsfsdfdsfdsf")
          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'
            }
          }
        }
      }
      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 = {}
        this.$nextTick(()=>{
          this.$refs["addAndEdit"].openDialog("配置排期", this.timeValueObj, 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();
    },
    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.clearCalendarPrice()
        }).catch(() => {});
      } else {
        this.$message.error("请选择时间区间!!!");
      }
      
    },
    /** 一键清除  */
    async clearCalendarPrice() {
      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.getCalendarPrice()
          }
        }else {
          this.$message.error("请选择时间区间!!!");
        }
      } 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-table .el-calendar-day {
    height: auto;
    min-height: 86px;
}
.app-calendar-container ::v-deep .is-today {
  background-color: rgba(255, 240, 24, 0);
  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;
  .calendar_box-date {
    display: flex;
    width: 100% ;
    justify-content: space-between;

  }
}

.disable_time {
  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: #C2D4FF;
}
</style>
<style lang="scss">
.calendar-dialog ::v-deep .el-calendar-table .el-calendar-day {
  padding: none !important;
  height: auto;
}
</style>