<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <!-- 搜索条件区域 -->
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form ref="queryForm" :model="query" @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="单据门店" prop="djmd" :rules="[{ required: true, message: '请选择单据门店', trigger: 'change' }]">
              <el-select v-model="query.djmd" placeholder="请选择单据门店">
                <el-option v-for="(item, index) in djmdOptions" :key="index" :label="item.fullName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="邀约人">
              <userSelect v-model="query.yyr" placeholder="请选择邀约人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预约状态">
              <el-select v-model="query.F_Status" placeholder="预约状态" clearable>
                <el-option label="已确认" value="已确认" />
                <el-option label="已取消" value="已取消" />
                <el-option label="已预约" value="已预约" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <!-- 日历视图区域 -->
      <div class="NCC-common-layout-main NCC-flex-main calendar-container">
        <div class="calendar-header">
          <div class="calendar-header-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false" @click="refresh()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <div class="calendar-wrapper" v-loading="listLoading">
          <FullCalendar
            class="demo-app-calendar"
            ref="fullCalendar"
            defaultView="dayGridMonth"
            :header="{
              left: 'prev,next today',
              center: 'title',
              right: 'dayGridMonth,timeGridWeek,timeGridDay'
            }"
            :plugins="calendarPlugins"
            :weekends="calendarWeekends"
            :events="calendarEvents"
            locale="zh-cn"
            :buttonText="buttonText"
            :height="calendarHeight"
            :eventLimit="true"
            allDayText="全天"
            :editable="false"
            @datesRender="datesRender"
          />
          <!--@dateClick="handleDateClick"     @eventClick="eventClick" -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import { previewDataInterface } from '@/api/systemData/dataInterface'
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import bootstrapPlugin from '@fullcalendar/bootstrap'

export default {
  name: 'lqYyjlCalendar',
  components: {
    FullCalendar
  },
  data() {
    return {
      listLoading: false,
      query: {
        djmd: undefined,
        yyr: undefined,
        F_Status: undefined
      },
      djmdOptions: [],
      calendarPlugins: [
        dayGridPlugin,
        timeGridPlugin,
        bootstrapPlugin,
        interactionPlugin
      ],
      calendarWeekends: true,
      calendarEvents: [],
      buttonText: {
        today: '今日',
        month: '月',
        week: '周',
        day: '日'
      },
      startTime: '',
      endTime: '',
      calendarHeight: 'auto'
    }
  },
  mounted() {
    this.calculateCalendarHeight()
    window.addEventListener('resize', this.calculateCalendarHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateCalendarHeight)
  },
  created() {
    // 处理路由参数
    if (this.$route.query.employeeId) {
      this.query.yyr = this.$route.query.employeeId
    }
    if (this.$route.query.storeId) {
      this.query.djmd = this.$route.query.storeId
    }
    if (this.$route.query.type) {
      this.query.F_Status = this.$route.query.type
    }
    this.getdjmdOptions()
    // 如果有路由参数设置了门店，初始化时也需要加载数据
    if (this.$route.query.storeId) {
      this.$nextTick(() => {
        this.initData()
      })
    }
  },
  methods: {
    /**
     * 计算日历高度
     */
    calculateCalendarHeight() {
      this.$nextTick(() => {
        const wrapper = this.$el.querySelector('.calendar-wrapper')
        if (wrapper) {
          const height = wrapper.clientHeight - 24 // 减去 padding
          this.calendarHeight = Math.max(height, 600) // 最小高度 600px
        }
      })
    },
    /**
     * 获取单据门店选项
     */
    async getdjmdOptions() {
      await previewDataInterface('730960205902251269').then(res => {
        this.djmdOptions = res.data
        // this.query.djmd = this.djmdOptions[0].id || ''
      })
    },
    /**
     * 日历视图改变时触发
     */
    datesRender(calendar) {
      let view = calendar.view
      this.startTime = this.ncc.toDate(view.activeStart, 'yyyy-MM-dd HH:mm:ss')
      this.endTime = this.ncc.toDate(view.activeEnd, 'yyyy-MM-dd HH:mm:ss')
      if(this.query.djmd) {
        this.initData()
      }
    },
    /**
     * 点击日期
     */
    handleDateClick(arg) {
      // 可以在此处添加点击日期后的逻辑，比如跳转到列表页并筛选该日期
      const clickDate = this.ncc.toDate(arg.date, 'yyyy-MM-dd')
      this.$router.push({
        path: '/lqYyjl',
        query: {
          startTime: new Date(clickDate + ' 00:00:00').getTime(),
          endTime: new Date(clickDate + ' 23:59:59').getTime()
        }
      })
    },
    /**
     * 点击事件
     */
    eventClick(data) {
      const eventData = data.event.extendedProps
      if (eventData && eventData.InviteId) {
        // 如果有关联邀约号，跳转到邀约记录页面
        this.$router.push({
          path: '/lqYaoyjl',
          query: { id: eventData.InviteId }
        })
      }
    },
    /**
     * 初始化数据
     */
    initData() {
      this.listLoading = true
      let _query = {
        ...this.query
      }
      
      // 添加时间范围查询条件
      if (this.startTime && this.endTime) {
        _query.yysj = [new Date(this.startTime).getTime(), new Date(this.endTime).getTime()].join()
      }

      let query = {}
      for (let key in _query) {
        if (_query[key] !== undefined && _query[key] !== null && _query[key] !== '') {
          query[key] = _query[key]
        }
      }

      // 日历视图需要获取更多数据，不设置分页限制
      request({
        url: '/api/Extend/LqYyjl',
        method: 'GET',
        data: {
          ...query,
          currentPage: 1,
          pageSize: 1000 // 获取足够多的数据用于日历显示
        }
      }).then(res => {
        this.listLoading = false
        if (res.code === 200 && res.data && res.data.list) {
          // 将预约记录转换为日历事件
          this.calendarEvents = res.data.list.map(item => {
            // 根据预约状态设置不同颜色
            let color = '#409EFF' // 默认蓝色（已预约）
            if (item.F_Status === '已确认') {
              color = '#67C23A' // 绿色
            } else if (item.F_Status === '已取消') {
              color = '#F56C6C' // 红色
            }

            // 构建事件标题
            let title = `${item.gkxm || '无'} - ${item.yyrName || '无'}`
            if (item.yyjksName) {
              title += ` (${item.yyjksName})`
            }

            return {
              id: item.id,
              title: title,
              start: item.yysj ? new Date(item.yysj).toISOString() : new Date().toISOString(),
              end: item.yyjs ? new Date(item.yyjs).toISOString() : new Date().toISOString(),
              color: color,
              editable: false,
              allDay: false,
              extendedProps: {
                ...item
              }
            }
          })
        } else {
          this.calendarEvents = []
        }
      }).catch(() => {
        this.listLoading = false
        this.calendarEvents = []
      })
    },
    /**
     * 搜索
     */
    search() {
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          this.initData()
        } else {
          this.$message.warning('请选择单据门店')
          return false
        }
      })
    },
    /**
     * 重置
     */
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      // 清除表单验证状态
      this.$nextTick(() => {
        if (this.$refs.queryForm) {
          this.$refs.queryForm.clearValidate()
        }
      })
      // 重置后不自动查询，因为单据门店是必选的
    },
    /**
     * 刷新
     */
    refresh() {
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          this.initData()
        } else {
          this.$message.warning('请选择单据门店')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
// FullCalendar 样式导入
@import '~@fullcalendar/core/main.css';
@import '~@fullcalendar/daygrid/main.css';
@import '~@fullcalendar/timegrid/main.css';
@import '~@fullcalendar/bootstrap/main.css';
</style>

<style lang="scss" scoped>
.calendar-container {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .calendar-header {
    padding: 12px;
    background: #fff;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-shrink: 0;

    .calendar-header-right {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }

  .calendar-wrapper {
    flex: 1;
    padding: 12px;
    background: #fff;
    min-height: 0;
    height: 0;
    position: relative;
  }
}
</style>

<style lang="scss">
// FullCalendar 样式覆盖
.demo-app-calendar {
  .fc-toolbar.fc-header-toolbar {
    padding: 10px;
    margin-bottom: 0;
  }

  .fc-button-primary {
    background-color: #409EFF;
    border-color: #409EFF;
    height: 32px;
    line-height: 32px;
    padding: 0 0.65em;
    font-size: 12px;
  }

  .fc-button-primary:not(:disabled):active,
  .fc-button-primary:not(:disabled).fc-button-active {
    background-color: #66b1ff;
    border-color: #66b1ff;
  }

  .fc-button .fc-icon {
    line-height: 16px;
  }

  .fc-unthemed th {
    height: 40px;
    line-height: 40px;
    font-size: 12px;
    color: #909399;
    font-weight: normal;
    background: #f5f7fa;
  }

  .fc-center {
    color: #606266;
  }

  .fc-unthemed th,
  .fc-unthemed td,
  .fc-unthemed thead,
  .fc-unthemed tbody,
  .fc-unthemed .fc-divider,
  .fc-unthemed .fc-row,
  .fc-unthemed .fc-content,
  .fc-unthemed .fc-popover,
  .fc-unthemed .fc-list-view,
  .fc-unthemed .fc-list-heading td {
    border-color: #ebeef5;
    color: #606266;
  }

  .fc-event {
    cursor: pointer;
  }

  // 周视图优化
  .fc-timeGridWeek-view,
  .fc-timeGridDay-view {
    .fc-time-grid {
      min-height: 600px;
    }

    .fc-time-slot {
      min-height: 40px;
    }

    .fc-event {
      font-size: 12px;
      padding: 2px 4px;
      margin: 1px 2px;
      line-height: 1.4;
    }

    .fc-event-time {
      font-size: 11px;
    }

    .fc-event-title {
      font-size: 12px;
    }
  }

  // 事件弹出框滚动优化
  .fc-more-popover {
    .fc-event-container {
      max-height: 400px !important;
      overflow-y: auto !important;
    }
  }

  // 周视图滚动条样式优化
  .fc-scroller {
    overflow-y: auto !important;
    overflow-x: hidden !important;
  }

  .fc-timeGridWeek-view .fc-scroller,
  .fc-timeGridDay-view .fc-scroller {
    max-height: none;
    height: 100%;
  }
}
</style>

