<template>
  <div class="appointment-calendar-container">
    <div class="NCC-common-layout-center" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
      <!-- 搜索条件区域 -->
      <div class="filter-section">
        <el-card class="filter-card" shadow="hover">
          <div class="filter-content">
            <el-form ref="queryForm" :model="query" @submit.native.prevent class="filter-form">
              <div class="filter-item">
                <label class="filter-label">单据门店：</label>
                <el-form-item prop="djmd" :rules="[{ required: true, message: '请选择单据门店', trigger: 'change' }]" style="margin: 0;">
                  <el-select v-model="query.djmd" placeholder="请选择单据门店" style="width: 300px">
                    <el-option v-for="(item, index) in djmdOptions" :key="index" :label="item.fullName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </div>
              <div class="filter-item">
                <label class="filter-label">邀约人：</label>
                <userSelect v-model="query.yyr" placeholder="请选择邀约人" style="width: 300px" />
              </div>
              <div class="filter-item">
                <label class="filter-label">预约状态：</label>
                <el-select v-model="query.F_Status" placeholder="预约状态" clearable style="width: 200px">
                  <el-option label="已确认" value="已确认" />
                  <el-option label="已取消" value="已取消" />
                  <el-option label="已预约" value="已预约" />
                </el-select>
              </div>
              <div class="filter-item">
                <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
                <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
              </div>
            </el-form>
          </div>
        </el-card>
      </div>

      <!-- 日历视图区域 -->
      <div class="calendar-section">
        <el-card shadow="hover" class="calendar-card">
          <!-- <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"
            />
          </div>
        </el-card>
      </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 - 40 // 减去 padding (20px * 2)
          this.calendarHeight = Math.max(height, 600) // 最小高度 600px
        } else {
          // 如果找不到元素，使用默认高度
          this.calendarHeight = 700
        }
      })
    },
    /**
     * 获取单据门店选项
     */
    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>
.appointment-calendar-container {
  padding: 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #e8f3ff 100%);
  min-height: calc(100vh - 84px);
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;

  // 背景装饰
  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 500px;
    height: 500px;
    background: radial-gradient(circle, rgba(59, 130, 246, 0.08) 0%, transparent 70%);
    pointer-events: none;
    z-index: 0;
  }

  > * {
    position: relative;
    z-index: 1;
  }

  .filter-section {
    margin-bottom: 24px;

    .filter-card {
      border-radius: 16px;
      border: 1px solid rgba(226, 232, 240, 0.8);
      background: rgba(255, 255, 255, 0.9);
      backdrop-filter: blur(12px);
      box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      &:hover {
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
        transform: translateY(-2px);
      }

      ::v-deep .el-card__body {
        padding: 24px;
      }

      .filter-content {
        .filter-form {
          display: flex;
          align-items: center;
          gap: 20px;
          flex-wrap: wrap;

          .filter-item {
            display: flex;
            align-items: center;

            .filter-label {
              font-size: 14px;
              font-weight: 600;
              color: #1e293b;
              margin-right: 12px;
              white-space: nowrap;
              letter-spacing: -0.01em;
            }

            ::v-deep .el-select {
              .el-input__inner {
                border-radius: 10px;
                border: 1.5px solid #e2e8f0;
                transition: all 0.3s;

                &:hover {
                  border-color: #3b82f6;
                }

                &:focus {
                  border-color: #3b82f6;
                  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
                }
              }
            }

            .el-button {
              border-radius: 10px;
              font-weight: 500;
              transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 16px rgba(59, 130, 246, 0.3);
              }
            }
          }
        }
      }
    }
  }

  .calendar-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;

    .calendar-card {
      flex: 1;
      display: flex;
      flex-direction: column;
      border-radius: 16px;
      border: 1px solid rgba(226, 232, 240, 0.8);
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(16px);
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
      overflow: hidden;

      ::v-deep .el-card__body {
        padding: 0;
        flex: 1;
        display: flex;
        flex-direction: column;
        min-height: 0;
      }

      .calendar-header {
        padding: 16px 24px;
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.02) 0%, rgba(96, 165, 250, 0.02) 100%);
        border-bottom: 2px solid #f1f5f9;
        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: 20px;
        background: #fff;
        min-height: 0;
        position: relative;
        display: flex;
        flex-direction: column;
      }
    }
  }
}
</style>

<style lang="scss">
// FullCalendar 样式覆盖
.demo-app-calendar {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .fc-view-container {
    flex: 1;
    min-height: 0;
  }

  .fc-toolbar.fc-header-toolbar {
    padding: 24px 28px;
    margin-bottom: 0;
    border-bottom: 2px solid #f1f5f9;
    background: linear-gradient(135deg, rgba(59, 130, 246, 0.02) 0%, rgba(96, 165, 250, 0.02) 100%);
  }

  .fc-toolbar-title {
    font-size: 20px;
    font-weight: 700;
    color: #1e293b;
    letter-spacing: -0.02em;
    background: linear-gradient(135deg, #1e293b 0%, #3b82f6 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }

  .fc-button-primary {
    background-color: #3b82f6;
    border-color: #3b82f6;
    height: 36px;
    line-height: 36px;
    padding: 0 16px;
    font-size: 13px;
    font-weight: 500;
    border-radius: 10px;
    border: 1.5px solid #e2e8f0;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &:hover {
      border-color: #3b82f6;
      background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(96, 165, 250, 0.05) 100%);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
    }

    &:active {
      transform: translateY(0);
    }
  }

  .fc-button-primary:not(:disabled):active,
  .fc-button-primary:not(:disabled).fc-button-active {
    background-color: #2563eb;
    border-color: #2563eb;
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  }

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

  // 表头样式 - 使用多个选择器确保覆盖
  .fc-unthemed th,
  .fc-daygrid-header th,
  .fc-daygrid-header .fc-col-header-cell {
    height: 70px !important;
    min-height: 70px !important;
    line-height: 70px !important;
    font-size: 14px !important;
    color: #64748b !important;
    font-weight: 700 !important;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%) !important;
    border-bottom: 2px solid #e2e8f0 !important;
    padding: 16px 8px !important;
    vertical-align: middle !important;
    box-sizing: border-box !important;
  }

  // 表头内容区域
  .fc-daygrid-header .fc-col-header-cell-cushion {
    height: 70px !important;
    line-height: 70px !important;
    padding: 0 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    font-size: 14px !important;
    font-weight: 700 !important;
  }

  // 表头行
  .fc-daygrid-header .fc-col-header {
    height: 70px !important;
  }

  .fc-daygrid-header .fc-col-header tr {
    height: 70px !important;
  }

  .fc-center {
    color: #1e293b;
  }

  .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: #f1f5f9;
    color: #1e293b;
  }

  .fc-daygrid-day {
    min-height: 120px;
    height: auto;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    padding: 8px;

    &:hover {
      background: linear-gradient(135deg, rgba(59, 130, 246, 0.04) 0%, rgba(96, 165, 250, 0.04) 100%);
    }

    .fc-daygrid-day-frame {
      min-height: 100px;
    }

    .fc-daygrid-day-top {
      padding: 4px 0;
    }

    .fc-daygrid-day-number {
      font-size: 14px;
      font-weight: 600;
      padding: 4px 8px;
    }

    .fc-daygrid-day-events {
      margin-top: 6px;
      min-height: 20px;
    }
  }

  .fc-day-today {
    background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(96, 165, 250, 0.05) 100%);

    .fc-daygrid-day-number {
      background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
      color: #fff;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
    }
  }

  .fc-event {
    cursor: pointer;
    border-radius: 6px;
    padding: 4px 8px;
    font-size: 12px;
    font-weight: 500;
    border: none;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      z-index: 10;
    }
  }

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

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

    .fc-event {
      font-size: 12px;
      padding: 4px 8px;
      margin: 2px 4px;
      line-height: 1.4;
      border-radius: 6px;
    }

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

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

  // 事件弹出框滚动优化
  .fc-more-popover {
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    border: 1px solid rgba(226, 232, 240, 0.8);

    .fc-event-container {
      max-height: 400px !important;
      overflow-y: auto !important;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: rgba(148, 163, 184, 0.5);
        border-radius: 3px;

        &:hover {
          background: rgba(148, 163, 184, 0.7);
        }
      }
    }
  }

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

    &::-webkit-scrollbar {
      width: 8px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f5f9;
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(148, 163, 184, 0.5);
      border-radius: 4px;

      &:hover {
        background: rgba(148, 163, 184, 0.7);
      }
    }
  }

  .fc-timeGridWeek-view .fc-scroller,
  .fc-timeGridDay-view .fc-scroller {
    max-height: none;
    height: 100%;
  }
  .fc-day-header{
    font-size: 14px !important;
    color: #64748b !important;
    font-weight: 700 !important;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%) !important;
    border-bottom: 2px solid #e2e8f0 !important;
    padding: 15px 8px !important;
    vertical-align: middle !important;
    box-sizing: border-box !important;
  }
}
</style>

