<template>
  <el-card shadow="never" class="info-card current-shift-card">
    <div class="card-header">
      <span>当前值守信息</span>
      <el-button v-if="currentShiftState === 'success' && currentShift" type="text" size="mini" @click="handleViewDetails">查看详情</el-button>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="currentShiftState === 'loading'" class="shift-loading">
      <i class="el-icon-loading"></i>
      <span>加载中...</span>
    </div>
    
    <!-- 有排班且有成员（正常状态） -->
    <div v-else-if="currentShiftState === 'success' && currentShift && currentShift.members && currentShift.members.length > 0" class="shift-body">
      <div class="primary-duty">
        <div class="label">主值班人</div>
        <div class="value">
          <span>{{ currentShift.leadName || '未指定' }}</span>
          <el-tag 
            v-if="currentShift.leadPhone" 
            size="mini" 
            type="info" 
            style="cursor: pointer; margin-left: 8px"
            @click="callPhone(currentShift.leadPhone)"
          >
            <i class="el-icon-phone"></i> {{ currentShift.leadPhone }}
          </el-tag>
        </div>
      </div>
      <div class="shift-range">
        <div class="label">时间段</div>
        <div class="value">{{ currentShift.timeRange }}</div>
      </div>
      <div class="shift-status" v-if="currentShift.status">
        <div class="label">状态</div>
        <div class="value">
          <el-tag size="mini" :type="currentShift.status === 'active' ? 'success' : 'info'">
            {{ currentShift.status === 'active' ? '有效' : '已取消' }}
          </el-tag>
        </div>
      </div>
      <div class="members">
        <div class="label">成员</div>
        <ul>
          <li v-for="member in currentShift.members" :key="member.id">
            <span>{{ member.memberName || member.name || '未知' }}</span>
            <el-tag size="mini" :type="member.role === 'leader' ? 'danger' : 'success'">
              {{ member.role === 'leader' ? '组长' : '成员' }}
            </el-tag>
            <span 
              v-if="member.phone" 
              class="phone clickable" 
              @click="callPhone(member.phone)"
              :title="'点击拨打: ' + member.phone"
            >
              <i class="el-icon-phone"></i> {{ member.phone }}
            </span>
            <span v-else class="phone">暂无电话</span>
          </li>
        </ul>
      </div>
    </div>
    
    <!-- 有排班但无成员（异常状态） -->
    <div v-else-if="currentShiftState === 'success' && currentShift && (!currentShift.members || currentShift.members.length === 0)" class="shift-body shift-warning">
      <div class="shift-range">
        <div class="label">时间段</div>
        <div class="value">{{ currentShift.timeRange }}</div>
      </div>
      <div class="shift-status" v-if="currentShift.status">
        <div class="label">状态</div>
        <div class="value">
          <el-tag size="mini" :type="currentShift.status === 'active' ? 'success' : 'info'">
            {{ currentShift.status === 'active' ? '有效' : '已取消' }}
          </el-tag>
        </div>
      </div>
      <div class="members">
        <div class="label">成员</div>
        <div class="empty-members">
          <el-alert
            title="暂无成员"
            type="warning"
            :closable="false"
            show-icon
          >
          </el-alert>
          <el-button type="primary" plain size="mini" style="margin-top: 12px" @click="handleArrangeShift">添加成员</el-button>
        </div>
      </div>
    </div>
    
    <!-- 无当前排班（正常状态，非错误） -->
    <div v-else-if="currentShiftState === 'empty'" class="empty-state">
      <el-alert
        title="当前时间段无人值守"
        type="info"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-button type="text" size="mini" style="margin-top: 12px" @click="handleArrangeShift">快速排班</el-button>
    </div>
    
    <!-- API错误（异常状态） -->
    <div v-else-if="currentShiftState === 'error'" class="error-state">
      <el-alert
        :title="shiftError || '获取排班信息失败，请稍后重试'"
        type="error"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-button type="primary" plain size="mini" style="margin-top: 12px" @click="handleRetry">重试</el-button>
    </div>
  </el-card>
</template>

<script>
import { getCurrentShift } from '@/api/duty/shift'

export default {
  name: 'CurrentShiftCard',
  props: {
    autoLoad: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      currentShiftState: 'loading',
      currentShift: null,
      shiftError: null
    }
  },
  mounted() {
    if (this.autoLoad) {
      this.loadCurrentShift()
    }
  },
  methods: {
    async loadCurrentShift() {
      this.currentShiftState = 'loading'
      this.shiftError = null
      try {
        const res = await getCurrentShift()
        if (res.code === 200) {
          const shiftData = res.data
          if (shiftData) {
            this.currentShift = this.transformShiftData(shiftData)
            this.currentShiftState = 'success'
          } else {
            this.currentShift = null
            this.currentShiftState = 'empty'
          }
        } else {
          this.currentShift = null
          this.currentShiftState = 'error'
          this.shiftError = res.msg || '获取排班信息失败'
        }
      } catch (error) {
        this.currentShift = null
        this.currentShiftState = 'error'
        this.shiftError = error.message || '网络错误，请稍后重试'
      }
    },
    transformShiftData(shiftData) {
      if (!shiftData) {
        return null
      }
      const timeRange = this.formatTimeRange(
        shiftData.startTime,
        shiftData.endTime,
        shiftData.shiftType
      )
      const members = (shiftData.members || []).map((member) => ({
        id: member.id,
        memberName: member.memberName,
        name: member.memberName,
        role: member.role,
        phone: member.phone
      }))
      return {
        id: shiftData.id,
        leadName: shiftData.leadName,
        leadPhone: shiftData.leadPhone,
        timeRange,
        status: shiftData.status,
        shiftType: shiftData.shiftType,
        shiftDate: shiftData.shiftDate,
        members
      }
    },
    formatTimeRange(startTime, endTime, shiftType) {
      if (!startTime || !endTime) {
        return '时间未设置'
      }
      const start = startTime.substring(0, 5)
      const end = endTime.substring(0, 5)
      const startHour = parseInt(start.split(':')[0], 10)
      const endHour = parseInt(end.split(':')[0], 10)
      const isNightShift = endHour < startHour || shiftType === 'night'
      let typeLabel = ''
      if (shiftType === 'day') {
        typeLabel = '（白班）'
      } else if (shiftType === 'night') {
        typeLabel = '（夜班）'
      } else if (shiftType === 'all') {
        typeLabel = '（全天）'
      } else if (isNightShift) {
        typeLabel = '（夜班）'
      }
      return `${start} - ${end}${typeLabel}`
    },
    /**
     * 拨打电话
     */
    callPhone(phone) {
      if (!phone) {
        this.$message.warning('电话号码为空')
        return
      }
      
      // 清理电话号码（移除空格、横线等）
      const cleanPhone = phone.replace(/[\s\-\(\)]/g, '')
      
      // 使用 tel: 协议打开拨号界面
      window.location.href = `tel:${cleanPhone}`
    },
    
    /**
     * 打开排班详情抽屉
     */
    handleViewDetails() {
      if (!this.currentShift || !this.currentShift.id) {
        this.$message.warning('排班信息不完整')
        return
      }
      
      // 跳转到排班管理页面并定位到当前排班
      this.$router.push({
        path: '/duty/shift',
        query: {
          shiftId: this.currentShift.id
        }
      })
    },
    
    /**
     * 跳转到排班管理页面
     */
    handleArrangeShift() {
      this.$router.push({
        path: '/duty/shift'
      })
    },
    
    /**
     * 重试加载
     */
    handleRetry() {
      this.loadCurrentShift()
    }
  }
}
</script>

<style lang="scss" scoped>
.current-shift-card {
  flex: unset !important;
  
  .shift-body {
    // max-height: 300px;
    // overflow-y: auto;
    .label {
      color: #909399;
      font-size: 12px;
      margin-bottom: 4px;
    }
    .value {
      font-size: 14px;
      margin-bottom: 12px;
    }
  }
}

.members ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.members li {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f2f5;
}

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

/* 加载状态 */
.shift-loading {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.shift-loading i {
  font-size: 24px;
  margin-right: 8px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 20px 0 0;
  color: #909399;
}

/* 错误状态 */
.error-state {
  text-align: center;
  padding: 20px 0 0;
}

/* 警告状态（有排班但无成员） */
.shift-warning {
  opacity: 0.9;
}

.empty-members {
  text-align: center;
  padding: 12px 0;
}

/* 可点击的电话号码 */
.phone.clickable {
  color: #409eff;
  cursor: pointer;
  transition: color 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.phone.clickable:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.phone.clickable i {
  font-size: 12px;
}

/* 排班状态 */
.shift-status {
  margin-bottom: 12px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 14px;
}
</style>