<template>
  <div class="app-container duty-shift-page">
    <el-card shadow="never" class="filter-card">
      <div class="filter-header">
        <div class="title">
          <i class="el-icon-s-cooperation" />
          <span>值守排班筛选</span>
        </div>
      </div>
      <el-form ref="queryForm" :model="queryParams" label-width="88px" size="small" class="filter-form" @submit.native.prevent>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="queryParams.dateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                :clearable="false"
                :editable="false"
                placeholder="选择日期范围"
                range-separator="至"
                start-placeholder="开始"
                end-placeholder="结束"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4">
            <el-form-item label="班次类型">
              <el-select v-model="queryParams.shiftType" placeholder="全部" clearable filterable>
                <el-option
                  v-for="dict in dict.type.duty_shift_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4">
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="全部" clearable filterable>
                <el-option
                  v-for="dict in dict.type.duty_shift_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4" class="filter-actions">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="workspace-card">
      <div class="workspace-header">
        <div class="summary-block">
          <div class="summary-item">
            <div class="label">
              当前时间段值守
              <el-tooltip content="显示当前时刻正在值班的人员信息" placement="top">
                <i class="el-icon-question" style="margin-left: 4px; color: #909399; cursor: help;" />
              </el-tooltip>
            </div>
            <div class="value">{{ currentShift.name || '未排班' }}</div>
            <div class="meta" v-if="currentShift.name">
              <i class="el-icon-phone" /> {{ currentShift.phone || '暂无电话' }}
            </div>
          </div>
          <div class="summary-item">
            <div class="label">
              筛选结果
              <el-tooltip content="显示符合当前筛选条件（日期范围、班次类型、状态）的排班数量" placement="top">
                <i class="el-icon-question" style="margin-left: 4px; color: #909399; cursor: help;" />
              </el-tooltip>
            </div>
            <div class="value highlight">{{ statistics.rangeTotal }} 班</div>
          </div>
          <div class="summary-item">
            <div class="label">
              缺班告警
              <el-tooltip content="显示日期范围内没有任何有效排班的天数，用于提醒需要安排人员值班的日期" placement="top">
                <i class="el-icon-question" style="margin-left: 4px; color: #909399; cursor: help;" />
              </el-tooltip>
            </div>
            <div :class="['value', statistics.gaps > 0 ? 'danger' : 'safe']">
              {{ statistics.gaps }}
            </div>
          </div>
        </div>
        <div class="view-switch">
          <el-button-group>
            <el-button type="primary" icon="el-icon-s-order" size="mini" :plain="activeView !== 'table'" @click="activeView = 'table'">表格视图</el-button>
            <el-button type="primary" icon="el-icon-date" size="mini" :plain="activeView !== 'calendar'" @click="activeView = 'calendar'">日历视图</el-button>
          </el-button-group>
        </div>
      </div>

      <div class="toolbar">
        <div class="left">
          <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleCreate" v-hasPermi="['duty:shift:add']">新增排班</el-button>
        </div>
        <div class="right">
          <el-button type="text" icon="el-icon-message" @click="showAlerts = !showAlerts">
            {{ showAlerts ? '隐藏告警' : '显示告警' }}
          </el-button>
        </div>
      </div>

      <transition name="el-fade-in">
        <div v-if="showAlerts" class="alert-panel">
          <el-alert
            v-if="statistics.gaps > 0"
            type="warning"
            show-icon
            :closable="false"
            title="当前存在排班缺口"
            description="请尽快安排人员，或使用一键补班功能。"
          />
          <el-alert
            v-else
            type="success"
            show-icon
            :closable="false"
            title="排班正常"
            description="当前时段排班齐备，无缺班告警。"
          />
        </div>
      </transition>

      <div v-if="activeView === 'table'">
        <el-table
          ref="shiftTable"
          v-loading="tableLoading"
          :data="shiftList"
          border
          stripe
          highlight-current-row
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="排班日期" prop="shiftDate" width="140" sortable />
          <el-table-column label="班次类型" prop="shiftType" width="110">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.duty_shift_type" :value="scope.row.shiftType" />
            </template>
          </el-table-column>
          <el-table-column label="时间段" prop="timeRange" width="160">
            <template slot-scope="scope">
              {{ scope.row.startTime }} ~ {{ scope.row.endTime }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="120">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.duty_shift_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="主值班人" prop="leadName" min-width="150">
            <template slot-scope="scope">
              <div class="lead-cell">
                <span class="name">{{ scope.row.leadName || '-' }}</span>
                <span class="phone" v-if="scope.row.leadPhone"><i class="el-icon-phone" /> {{ scope.row.leadPhone }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="成员数" prop="memberCount" width="100" align="center" sortable />
          <el-table-column label="操作" width="220" fixed="right" class-name="action-column">
            <template slot-scope="scope">
              <el-button type="text" size="mini" icon="el-icon-view" @click="viewMembers(scope.row)">查看成员</el-button>
              <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)" v-hasPermi="['duty:shift:edit']">编辑</el-button>
              <el-button 
                type="text" 
                size="mini" 
                icon="el-icon-delete" 
                :disabled="scope.row.status === 'cancelled'" 
                @click="handleDelete(scope.row)" 
                v-hasPermi="['duty:shift:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="table-footer">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>

      <div v-else class="calendar-wrapper">
        <el-calendar v-model="calendarDate">
          <template slot="dateCell" slot-scope="{ data }">
            <div class="calendar-cell" :class="{ today: data.isSelected, 'is-range-date': rangeDateArr.includes(data.day), 'has-gap': calendarGaps.includes(data.day) }">
              <div class="date">{{ data.day.split('-').slice(2).join('-') }}</div>
              <div class="shifts" v-if="calendarMap[data.day] && calendarMap[data.day].length">
                <div
                  v-for="item in calendarMap[data.day]"
                  :key="item.id"
                  class="shift-chip"
                  :class="item.status"
                  @click.stop="viewMembers(item)"
                >
                  <span
                    class="badge" :class="{'badge-all': item.shiftType === 'all', 'badge-night': item.shiftType === 'night'}"
                  >{{ getShiftTypeLabel(item.shiftType) }}</span>
                  <span class="name">{{ item.leadName || '未指定' }}</span>
                </div>
              </div>
              <div class="empty" v-else>--</div>
            </div>
          </template>
        </el-calendar>
      </div>
    </el-card>

    <el-drawer
      title="排班成员"
      :visible.sync="memberDrawer.visible"
      size="800px"
      :destroy-on-close="true"
      @close="handleMemberDrawerClose"
    >
      <div class="drawer-content">
        <!-- 排班信息卡片 -->
        <el-card shadow="never" class="shift-info-card" :body-style="{ padding: '16px' }">
          <div class="shift-info-grid">
            <div class="info-item">
              <div class="info-label">排班日期</div>
              <div class="info-value">{{ memberDrawer.shift ? memberDrawer.shift.shiftDate : '-' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">时间段</div>
              <div class="info-value">{{ memberDrawer.shift ? memberDrawer.shift.startTime + ' ~ ' + memberDrawer.shift.endTime : '-' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">班次类型</div>
              <div class="info-value">
                <dict-tag v-if="memberDrawer.shift" :options="dict.type.duty_shift_type" :value="memberDrawer.shift.shiftType" />
                <span v-else>-</span>
              </div>
            </div>
            <div class="info-item">
              <div class="info-label">状态</div>
              <div class="info-value">
                <dict-tag v-if="memberDrawer.shift" :options="dict.type.duty_shift_status" :value="memberDrawer.shift.status" />
                <span v-else>-</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 成员列表 -->
        <div class="member-list-section">
          <div class="section-header">
            <span class="section-title">成员列表</span>
            <span class="member-count" v-if="memberDrawer.members && memberDrawer.members.length > 0">
              ({{ memberDrawer.members.length }}人)
            </span>
          </div>
          <el-table 
            :data="memberDrawer.members" 
            size="small" 
            border
            stripe
            empty-text="暂无成员"
            style="margin-top: 12px;"
          >
            <el-table-column prop="role" label="角色" width="100" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.role === 'leader' ? 'warning' : 'info'" size="small">
                  {{ scope.row.role === 'leader' ? '组长' : '成员' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="memberName" label="姓名" min-width="120" />
            <el-table-column prop="phone" label="联系电话" min-width="150" />
            <el-table-column prop="checkInTime" label="签到时间" min-width="160">
              <template slot-scope="scope">
                {{ scope.row.checkInTime || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="checkOutTime" label="签退时间" min-width="160">
              <template slot-scope="scope">
                {{ scope.row.checkOutTime || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button 
                  type="text" 
                  size="mini" 
                  icon="el-icon-edit" 
                  @click="handleOpenEditMember(scope.row)"
                  v-hasPermi="['duty:shift:member:edit']"
                >编辑</el-button>
                <el-button 
                  type="text" 
                  size="mini" 
                  icon="el-icon-delete" 
                  @click="handleDeleteMember(scope.row)"
                  v-hasPermi="['duty:shift:member:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 操作按钮 -->
        <div class="drawer-footer">
          <el-button size="small" type="primary" @click="handleOpenAddMember" v-hasPermi="['duty:shift:member:add']">添加成员</el-button>
          <el-button size="small" @click="memberDrawer.visible = false">关闭</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 添加/编辑成员对话框 -->
    <el-dialog :title="memberDialogTitle" :visible.sync="memberDialog.visible" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="memberForm" :model="memberForm" :rules="memberFormRules" label-width="100px">
        <el-form-item label="选择用户" prop="userId">
          <el-select v-model="memberForm.userId" placeholder="请选择用户" filterable style="width: 100%" :loading="userListLoading" :disabled="memberDialog.mode === 'edit'">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="memberForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="成员" value="member" />
            <el-option label="组长" value="leader" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="memberForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="memberDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveMember" :loading="memberLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改排班对话框 -->
    <el-dialog :title="formTitle" :visible.sync="formOpen" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="排班日期" prop="shiftDate">
          <el-date-picker
            v-model="form.shiftDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择排班日期"
            style="width: 100%"
            :picker-options="{
              disabledDate(time) {
                // 编辑模式下允许选择过去日期
                if (form.id) {
                  return false
                }
                // 新增模式下不允许选择过去日期
                const today = new Date()
                today.setHours(0, 0, 0, 0)
                return time.getTime() < today.getTime()
              }
            }"
          />
        </el-form-item>
        <el-form-item label="班次类型" prop="shiftType">
          <el-select v-model="form.shiftType" placeholder="请选择班次类型" clearable style="width: 100%" @change="handleShiftTypeChange">
            <el-option
              v-for="dict in dict.type.duty_shift_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            v-model="form.startTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker
            v-model="form.endTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="dict in dict.type.duty_shift_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getCurrentShift, listShifts, addShift, updateShift, deleteShift, listMembersByShift, addShiftMember, updateShiftMember, deleteShiftMembers } from '@/api/duty/shift'
import { listUser } from '@/api/system/user'

export default {
  name: 'DutyShiftIndex',
  dicts: ['duty_shift_type', 'duty_shift_status', 'duty_shift_member_role'],
  data() {
    return {
      queryParams: {
        dateRange: [],
        shiftType: undefined,
        status: undefined,
        pageNum: 1,
        pageSize: 10
      },
      activeView: 'table',
      showAlerts: true,
      calendarDate: dayjs().format('YYYY-MM-DD'),
      currentShift: {
        name: '',
        phone: ''
      },
      statistics: {
        rangeTotal: 0,
        gaps: 0
      },
      tableLoading: false,
      shiftList: [],
      total: 0,
      selectedRowKeys: [],
      memberDrawer: {
        visible: false,
        shift: null,
        members: []
      },
      memberDialog: {
        visible: false,
        mode: 'add' // 'add' or 'edit'
      },
      memberForm: {
        id: undefined,
        userId: undefined,
        role: 'member',
        phone: ''
      },
      memberFormRules: {
        userId: [
          { required: true, message: '请选择用户', trigger: 'change' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      userList: [],
      userListLoading: false,
      memberLoading: false,
      calendarData: [], // 用于日历视图的真实数据
      // 表单相关
      formOpen: false,
      formTitle: '',
      form: {
        id: undefined,
        shiftDate: null,
        shiftType: undefined,
        startTime: null,
        endTime: null,
        status: 'active'
      },
      formRules: {
        shiftDate: [
          { required: true, message: '排班日期不能为空', trigger: 'change' }
        ],
        shiftType: [
          { required: true, message: '班次类型不能为空', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '开始时间不能为空', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '结束时间不能为空', trigger: 'change' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    memberDialogTitle() {
      return this.memberDialog.mode === 'edit' ? '编辑成员' : '添加成员'
    },
    summaryText() {
      const parts = []
      if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        parts.push(`${this.queryParams.dateRange[0]} ~ ${this.queryParams.dateRange[1]}`)
      }
      if (this.queryParams.shiftType) {
        const dict = this.dict.type.duty_shift_type.find(item => item.value === this.queryParams.shiftType)
        parts.push(dict ? dict.label : this.queryParams.shiftType)
      }
      if (this.queryParams.status) {
        const dict = this.dict.type.duty_shift_status.find(item => item.value === this.queryParams.status)
        parts.push(dict ? dict.label : this.queryParams.status)
      }
      return parts.length ? parts.join('；') : '未设置筛选条件'
    },
    calendarMap() {
      const map = {}
      // 使用真实数据
      this.calendarData.forEach(item => {
        if (!map[item.shiftDate]) {
          map[item.shiftDate] = []
        }
        map[item.shiftDate].push(item)
      })
      // 对每个日期的班次按开始时间从早到晚排序
      Object.keys(map).forEach(date => {
        map[date].sort((a, b) => {
          const timeA = a.startTime || '00:00'
          const timeB = b.startTime || '00:00'
          return timeA.localeCompare(timeB)
        })
      })
      return map
    },
    calendarGaps() {
      // 计算缺班日期：在日期范围内但没有有效排班的日期（已取消的班次算作缺班）
      if (!this.queryParams.dateRange || this.queryParams.dateRange.length !== 2) {
        return []
      }
      // 获取所有有有效排班的日期（只统计 active 状态的，cancelled 不算有效排班）
      const activeShifts = this.calendarData.filter(item => item.status === 'active')
      const datesWithShifts = new Set(activeShifts.map(item => item.shiftDate))
      // 找出日期范围内没有有效排班的日期
      const gaps = []
      this.rangeDateArr.forEach(date => {
        if (!datesWithShifts.has(date)) {
          gaps.push(date)
        }
      })
      return gaps
    },
    rangeDateArr() {
      if (!this.queryParams.dateRange || this.queryParams.dateRange.length !== 2) {
        return []
      }
      const startDate = dayjs(this.queryParams.dateRange[0])
      const endDate = dayjs(this.queryParams.dateRange[1])
      const dateArr = []
      let currentDate = startDate
      while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {
        dateArr.push(currentDate.format('YYYY-MM-DD'))
        currentDate = currentDate.add(1, 'day')
      }
      return dateArr
    }
  },
  created() {
    this.initDefaults()
    this.getList()
  },
  methods: {
    initDefaults() {
      const start = dayjs().startOf('isoWeek') // ISO 周从周一开始
      const end = start.add(6, 'day') // 本周日
      this.queryParams.dateRange = [start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD')]
    },
    async updateStatistics() {
      // 使用后端返回的总数（已经按日期范围等条件过滤）
      this.statistics.rangeTotal = this.total
      
      // 计算缺班告警：只使用日期范围，不考虑shiftType和status过滤
      // 因为缺班告警应该反映实际覆盖缺口，而不是特定类型的排班缺口
      if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        try {
          // 构建查询参数（只使用日期范围，不传status，前端过滤）
          const params = {
            pageNum: 1,
            pageSize: 10000 // 设置一个很大的值以获取所有数据
          }
          
          // 只使用日期范围，不应用shiftType和status过滤
          params.beginShiftDate = this.queryParams.dateRange[0]
          params.endShiftDate = this.queryParams.dateRange[1]
          
          // 获取所有排班数据（不传status，获取所有状态的数据）
          const res = await listShifts(params)
          if (res.code === 200 && res.rows) {
            // 将所有排班数据（包括 cancelled）存储到 calendarData，用于日历视图
            this.calendarData = res.rows
            
            // 计算日期范围的总天数
            const rangeStart = dayjs(this.queryParams.dateRange[0])
            const rangeEnd = dayjs(this.queryParams.dateRange[1])
            const totalDays = rangeEnd.diff(rangeStart, 'day') + 1
            
            // 获取所有有有效排班的唯一日期（只统计 active 状态的排班，cancelled 不算有效排班）
            const activeShifts = res.rows.filter(shift => shift.status === 'active')
            const datesWithShifts = new Set()
            activeShifts.forEach(shift => {
              if (shift.shiftDate) {
                datesWithShifts.add(shift.shiftDate)
              }
            })
            
            // 缺班数 = 总天数 - 有有效排班的天数（已取消的班次算作缺班）
            this.statistics.gaps = totalDays - datesWithShifts.size
          } else {
            // 如果获取失败，清空 calendarData 并使用当前页数据估算
            this.calendarData = []
            this.statistics.gaps = this.shiftList.filter(item => !item.leadName).length
          }
        } catch (error) {
          console.error('计算缺班告警失败:', error)
          // 如果出错，清空 calendarData 并使用当前页数据估算
          this.calendarData = []
          this.statistics.gaps = this.shiftList.filter(item => !item.leadName).length
        }
      } else {
        // 没有日期范围时，清空 calendarData 并使用当前页数据
        this.calendarData = []
        this.statistics.gaps = this.shiftList.filter(item => !item.leadName).length
      }
    },
    async updateCurrentShift() {
      try {
        const res = await getCurrentShift()
        if (res.data) {
          this.currentShift = {
            name: res.data.leadName || '',
            phone: res.data.leadPhone || ''
          }
        } else {
          this.currentShift = {
            name: '',
            phone: ''
          }
        }
      } catch (error) {
        console.error('获取当前排班失败:', error)
        this.currentShift = {
          name: '',
          phone: ''
        }
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.initDefaults()
      this.queryParams.shiftType = undefined
      this.queryParams.status = undefined
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
    async getList() {
      this.tableLoading = true
      try {
        // 构建查询参数
        const params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        }
        
        // 日期范围
        if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
          params.beginShiftDate = this.queryParams.dateRange[0]
          params.endShiftDate = this.queryParams.dateRange[1]
        }
        
        // 班次类型
        if (this.queryParams.shiftType) {
          params.shiftType = this.queryParams.shiftType
        }
        
        // 状态
        if (this.queryParams.status) {
          params.status = this.queryParams.status
        }
        
        // 关键字（暂时保留，后续可能需要后端支持）
        // if (this.queryParams.keyword) {
        //   params.keyword = this.queryParams.keyword
        // }
        
        const res = await listShifts(params)
        if (res.code === 200) {
          this.shiftList = res.rows || [];
          this.total = res.total || 0;
          // !!!!!!!!!!!
        } else {
          this.$message.error(res.msg || '查询失败')
          this.shiftList = []
          this.total = 0
        }
      } catch (error) {
        console.error('查询排班列表失败:', error)
        this.$message.error('查询排班列表失败')
        this.shiftList = []
        this.total = 0
      } finally {
        this.tableLoading = false
        this.selectedRowKeys = []
        this.updateStatistics()
        this.updateCurrentShift()
      }
    },
    handleSelectionChange(selection) {
      this.selectedRowKeys = selection.map(item => item.id)
    },
    handleCreate() {
      this.resetForm()
      this.formTitle = '新增排班'
      this.formOpen = true
    },
    // 重置表单
    resetForm() {
      this.form = {
        id: undefined,
        shiftDate: dayjs().format('YYYY-MM-DD'),
        shiftType: undefined,
        startTime: null,
        endTime: null,
        status: 'active'
      }
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },
    // 班次类型变化时，自动设置时间
    handleShiftTypeChange(value) {
      if (!value) {
        this.form.startTime = null
        this.form.endTime = null
        return
      }
      // 根据班次类型设置默认时间
      if (value === 'day') {
        this.form.startTime = '08:00:00'
        this.form.endTime = '18:00:00'
      } else if (value === 'night') {
        this.form.startTime = '20:00:00'
        this.form.endTime = '08:00:00'
      } else if (value === 'all') {
        this.form.startTime = '00:00:00'
        this.form.endTime = '23:59:59'
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 转换日期格式为后端需要的格式
          const submitData = {
            shiftDate: this.form.shiftDate,
            shiftType: this.form.shiftType,
            startTime: this.form.startTime,
            endTime: this.form.endTime,
            status: this.form.status
          }
          
          // 如果是编辑模式，添加ID
          const isEditMode = this.form.id !== undefined && this.form.id !== null
          if (isEditMode) {
            submitData.id = this.form.id
          }
          
          const apiCall = isEditMode ? updateShift(submitData) : addShift(submitData)
          
          apiCall.then(response => {
            this.$modal.msgSuccess(isEditMode ? '修改成功' : '新增成功')
            this.formOpen = false
            
            // 如果是新增模式，检查新排班的日期是否在当前筛选范围内
            if (!isEditMode && this.form.shiftDate) {
              const shiftDate = this.form.shiftDate
              const dateRange = this.queryParams.dateRange
              
              // 如果日期范围为空，或者新排班日期不在范围内，调整日期范围
              if (!dateRange || dateRange.length !== 2 || 
                  shiftDate < dateRange[0] || shiftDate > dateRange[1]) {
                // 调整日期范围为包含新排班日期的那一周（周一到周日）
                const shiftDateObj = dayjs(shiftDate)
                const start = shiftDateObj.startOf('isoWeek') // 该周的周一
                const end = start.add(6, 'day') // 该周的周日
                this.queryParams.dateRange = [start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD')]
              }
            }
            
            this.getList()
          }).catch(error => {
            console.error(isEditMode ? '修改排班失败:' : '新增排班失败:', error)
            // Error message is already shown by request interceptor
          })
        }
      })
    },
    // 取消
    cancel() {
      this.formOpen = false
      this.resetForm()
    },
    handleEdit(row) {
      this.resetForm()
      this.form.id = row.id
      this.form.shiftDate = row.shiftDate
      this.form.shiftType = row.shiftType
      this.form.startTime = row.startTime
      this.form.endTime = row.endTime
      this.form.status = row.status
      this.formTitle = '修改排班'
      this.formOpen = true
    },
    handleDelete(row) {
      this.$confirm(`确定删除 ${row.shiftDate} 的排班吗？该操作将同步移除成员。`, '提示', {
        type: 'warning'
      }).then(() => {
        deleteShift(row.id).then(response => {
          this.$modal.msgSuccess('删除成功')
          this.getList()
        }).catch(error => {
          console.error('删除排班失败:', error)
          // Error message is already shown by request interceptor
        })
      }).catch(() => {})
    },
    async viewMembers(row) {
      this.memberDrawer.shift = row
      this.memberDrawer.visible = true
      
      // Fetch members from API
      try {
        const res = await listMembersByShift(row.id)
        if (res.code === 200) {
          this.memberDrawer.members = res.data || []
        } else {
          this.$message.error(res.msg || '获取成员列表失败')
          this.memberDrawer.members = []
        }
      } catch (error) {
        console.error('获取成员列表失败:', error)
        this.memberDrawer.members = []
      }
    },
    async handleOpenAddMember() {
      this.memberDialog.mode = 'add'
      this.resetMemberForm()
      
      // Load user list if not already loaded
      if (this.userList.length === 0) {
        await this.loadUserList()
      }
      
      this.memberDialog.visible = true
      
      // Clear validation
      this.$nextTick(() => {
        if (this.$refs.memberForm) {
          this.$refs.memberForm.clearValidate()
        }
      })
    },
    async loadUserList() {
      this.userListLoading = true
      try {
        const res = await listUser({ pageNum: 1, pageSize: 1000, status: '0' })
        if (res.code === 200) {
          this.userList = res.rows || []
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$message.error('获取用户列表失败')
      } finally {
        this.userListLoading = false
      }
    },
    resetMemberForm() {
      this.memberForm = {
        id: undefined,
        userId: undefined,
        role: 'member',
        phone: ''
      }
      if (this.$refs.memberForm) {
        this.$refs.memberForm.clearValidate()
      }
    },
    handleSaveMember() {
      this.$refs.memberForm.validate(valid => {
        if (valid) {
          this.memberLoading = true
          const isEdit = this.memberDialog.mode === 'edit'
          
          const memberData = isEdit ? {
            id: this.memberForm.id,
            userId: this.memberForm.userId,
            role: this.memberForm.role,
            phone: this.memberForm.phone || undefined
          } : {
            shiftId: this.memberDrawer.shift.id,
            userId: this.memberForm.userId,
            role: this.memberForm.role || 'member',
            phone: this.memberForm.phone || undefined
          }
          
          const apiCall = isEdit ? updateShiftMember(memberData) : addShiftMember(memberData)
          
          apiCall.then(response => {
            this.$modal.msgSuccess(isEdit ? '修改成功' : '添加成功')
            this.memberDialog.visible = false
            this.resetMemberForm()
            // Refresh member list
            this.viewMembers(this.memberDrawer.shift)
          }).catch(error => {
            console.error(isEdit ? '修改成员失败:' : '添加成员失败:', error)
          }).finally(() => {
            this.memberLoading = false
          })
        }
      })
    },
    handleDeleteMember(row) {
      this.$confirm(`确定删除成员 "${row.memberName || '该成员'}" 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        deleteShiftMembers(row.id).then(response => {
          this.$modal.msgSuccess('删除成功')
          // Refresh member list
          this.viewMembers(this.memberDrawer.shift)
        }).catch(error => {
          console.error('删除成员失败:', error)
        })
      }).catch(() => {})
    },
    handleMemberDrawerClose() {
      // 关闭 drawer 时刷新搜索
      this.handleQuery()
    },
    async handleOpenEditMember(row) {
      // Load user list if not already loaded
      if (this.userList.length === 0) {
        await this.loadUserList()
      }
      
      // Populate form with member data
      this.memberForm = {
        id: row.id,
        userId: row.userId,
        role: row.role || 'member',
        phone: row.phone || ''
      }
      
      this.memberDialog.mode = 'edit'
      this.memberDialog.visible = true
      
      // Clear validation
      this.$nextTick(() => {
        if (this.$refs.memberForm) {
          this.$refs.memberForm.clearValidate()
        }
      })
    },
    getShiftTypeLabel(value) {
      const dict = this.dict.type.duty_shift_type.find(item => item.value === value)
      return dict ? dict.label : value
    }
  }
}
</script>

<style lang="scss" scoped>
.duty-shift-page {
  min-height: calc(100vh - 84px);
  padding: 24px;
  background: #f5f7fa;

  .filter-card {
    margin-bottom: 20px;

    .filter-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;

      .title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 18px;
        font-weight: 600;
        color: #303133;

        i {
          font-size: 20px;
          color: #409eff;
        }
      }
    }

    .filter-actions {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 8px;
      padding-top: 4px;
    }
  }

  .workspace-card {
    .workspace-header {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;

      .summary-block {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;

        .summary-item {
          min-width: 160px;
          padding: 10px 16px;
          border-radius: 8px;
          background: #f4f6f8;

          .label {
            font-size: 12px;
            color: #909399;
          }

          .value {
            margin-top: 4px;
            font-size: 18px;
            font-weight: 600;
            color: #303133;

            &.highlight {
              color: #409eff;
            }

            &.danger {
              color: #f56c6c;
            }

            &.safe {
              color: #67c23a;
            }
          }

          .meta {
            margin-top: 4px;
            font-size: 12px;
            color: #606266;

            i {
              margin-right: 4px;
            }
          }
        }
      }

      .view-switch {
        display: flex;
        align-items: center;
      }
    }

    .toolbar {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      margin-bottom: 16px;

      .left {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
      }

      .right {
        display: flex;
        align-items: center;
      }
    }

    .alert-panel {
      margin-bottom: 16px;
    }

    .table-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 12px;
    }

    .lead-cell {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .phone {
        font-size: 12px;
        color: #909399;

        i {
          margin-right: 4px;
        }
      }
    }

    .action-column .el-dropdown-link {
      cursor: pointer;
      color: #409eff;
      margin-left: 8px;
    }

    .calendar-wrapper {
      ::v-deep .el-calendar-day {
        height: 110px;
      }
      .calendar-cell {
        // min-height: 120px;
        height: 95px;
        padding: 6px;
        border-radius: 6px;
        transition: background 0.2s;

        &.today {
          background: rgba(64, 158, 255, 0.08);
        }

        &.is-range-date {
          border: 1px dashed #13ce66;
        }
        &.has-gap {
          border: 1px dashed #f56c6c;
        }

        .shifts {
          height: calc(100% - 20px);
          overflow-y: auto;
        }

        .date {
          font-size: 12px;
          color: #909399;
          margin-bottom: 6px;
        }

        .shift-chip {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 4px 8px;
          margin-bottom: 4px;
          border-radius: 6px;
          background: #e7faf0;
          cursor: pointer;
          font-size: 12px;

          &.cancelled {
            // opacity: 0.6;
            background-color: #ffeded;
          }

          &:hover {
            background: #cef7e1;
            &.cancelled {
              background-color: #ffd9d9;
            }
          }

          .badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 0 6px;
            border-radius: 10px;
            background-color: #409eff;
            color: #fff;
            &.badge-night {
              background-color: #909399;
            }
            &.badge-all {
              background-color: #13ce66;
            }
          }

          .name {
            color: #303133;
          }
        }

        .empty {
          font-size: 12px;
          color: #c0c4cc;
        }
      }
    }
  }

  .drawer-content {
    padding: 20px;
  }

  .shift-info-card {
    margin-bottom: 20px;
    border: 1px solid #e4e7ed;
    
    .shift-info-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 16px;
      
      .info-item {
        display: flex;
        flex-direction: column;
        gap: 4px;
        
        .info-label {
          font-size: 12px;
          color: #909399;
          font-weight: 500;
        }
        
        .info-value {
          font-size: 14px;
          color: #303133;
          font-weight: 500;
        }
      }
    }
  }

  .member-list-section {
    margin-bottom: 20px;
    
    .section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
      
      .section-title {
        font-size: 14px;
        font-weight: 600;
        color: #303133;
      }
      
      .member-count {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .drawer-footer {
    margin-top: 20px;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;
    display: flex;
    gap: 8px;
    justify-content: flex-end;
  }
}
</style>