<template>
  <el-drawer
    title="队伍详情"
    :visible.sync="drawerVisible"
    direction="rtl"
    size="600px"
    :before-close="handleClose"
    @opened="handleOpened"
  >
    <div v-if="loading" class="drawer-loading">
      <i class="el-icon-loading"></i>
      <span>加载中...</span>
    </div>
    
    <div v-else-if="teamData" class="team-drawer-content">
      <!-- Header Section -->
      <div class="drawer-header">
        <div class="team-title">
          <span class="team-name">{{ teamData.teamName }}</span>
          <el-tag :type="getStatusTagType(teamData.status)" size="medium">
            {{ getStatusLabel(teamData.status) }}
          </el-tag>
        </div>
      </div>

      <!-- Basic Information -->
      <el-divider content-position="left">基本信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="队伍名称">{{ teamData.teamName }}</el-descriptions-item>
        <el-descriptions-item label="队伍类型">{{ getTeamTypeLabel(teamData.teamType) }}</el-descriptions-item>
        <el-descriptions-item label="所属单位">{{ teamData.belongOrgName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="单位类型">{{ getOrgTypeLabel(teamData.belongOrgType) }}</el-descriptions-item>
        <el-descriptions-item label="外部单位">
          <el-tag :type="teamData.externalFlag === 'Y' ? 'warning' : 'success'" size="small">
            {{ teamData.externalFlag === 'Y' ? '外部联动单位' : '内部单位' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(teamData.status)" size="small">
            {{ getStatusLabel(teamData.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- Contact Information -->
      <el-divider content-position="left">联系信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="联系人">{{ teamData.contactPerson || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">
          <span class="phone-number">{{ teamData.contactPhone || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="联系地址" :span="2">
          {{ teamData.contactAddress || '-' }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- Location Information -->
      <el-divider content-position="left">位置信息</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="驻扎点">{{ teamData.locationName || '-' }}</el-descriptions-item>
        <el-descriptions-item v-if="hasLocation()" label="坐标">
          {{ teamData.longitude }}, {{ teamData.latitude }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- Capabilities -->
      <el-divider content-position="left">能力标签</el-divider>
      <div class="capabilities-section">
        <el-tag
          v-for="tag in formatCapabilities(teamData.capabilities)"
          :key="tag"
          size="small"
          type="success"
          class="capability-tag"
        >
          {{ tag }}
        </el-tag>
        <span v-if="!formatCapabilities(teamData.capabilities).length" class="text-placeholder">-</span>
      </div>

      <!-- Map Section (if coordinates available) -->
      <div v-if="hasLocation() && mapReady" class="drawer-map-section">
        <el-divider content-position="left">位置地图</el-divider>
        <div class="map-container">
          <Amap
            container-id="team-detail-map"
            width="100%"
            height="300px"
            :center="[teamData.longitude, teamData.latitude]"
            :zoom="15"
            :markers="[{
              lat: teamData.latitude,
              lng: teamData.longitude,
              title: teamData.locationName || teamData.teamName,
              content: teamData.locationName || teamData.teamName
            }]"
          />
        </div>
      </div>

      <!-- Remark -->
      <el-divider v-if="teamData.remark" content-position="left">备注</el-divider>
      <div v-if="teamData.remark" class="remark-section">
        {{ teamData.remark }}
      </div>
    </div>
    
    <div v-else class="drawer-error">
      <el-alert
        title="加载失败"
        type="error"
        :closable="false"
        show-icon
      >
        <template slot="default">
          <p>无法加载队伍详情，请稍后重试</p>
          <el-button size="mini" @click="loadTeamDetail">重试</el-button>
        </template>
      </el-alert>
    </div>
  </el-drawer>
</template>

<script>
import Amap from '@/components/Amap'
import { getTeam } from '@/api/resource/team'

export default {
  name: 'TeamDetailDrawer',
  components: {
    Amap
  },
  dicts: ['team_org_type', 'team_type'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    teamId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      drawerVisible: false,
      loading: false,
      teamData: null,
      mapReady: false
    }
  },
  watch: {
    visible(newVal) {
      this.drawerVisible = newVal
      if (newVal && this.teamId) {
        this.loadTeamDetail()
      }
    },
    teamId(newVal) {
      if (newVal && this.drawerVisible) {
        this.loadTeamDetail()
      }
    },
    drawerVisible(newVal) {
      if (!newVal) {
        this.$emit('update:visible', false)
        this.reset()
      }
    }
  },
  methods: {
    async loadTeamDetail() {
      if (!this.teamId) return
      
      this.loading = true
      this.mapReady = false
      try {
        const response = await getTeam(this.teamId)
        if (response.code === 200) {
          this.teamData = response.data
        } else {
          this.$message.error(response.msg || '加载失败')
          this.teamData = null
        }
      } catch (error) {
        console.error('加载队伍详情失败:', error)
        this.$message.error('加载失败，请稍后重试')
        this.teamData = null
      } finally {
        this.loading = false
      }
    },
    handleClose(done) {
      this.reset()
      done()
    },
    handleOpened() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.mapReady = true
        }, 100)
      })
    },
    reset() {
      this.teamData = null
      this.mapReady = false
    },
    hasLocation() {
      return this.teamData && 
             this.teamData.longitude && 
             this.teamData.latitude
    },
    formatCapabilities(capabilities) {
      if (!capabilities) return []
      try {
        const result = JSON.parse(capabilities)
        if (Array.isArray(result)) {
          return result.map(item => item && item.toString()).filter(Boolean)
        }
      } catch (e) {
        // ignore parse error
      }
      return capabilities
        .split(/[,，\s]+/)
        .map(item => item.trim())
        .filter(item => !!item)
    },
    getStatusLabel(status) {
      const statusMap = {
        'available': '可用',
        'busy': '占用',
        'offline': '停用'
      }
      return statusMap[status] || status || '未知'
    },
    getStatusTagType(status) {
      const typeMap = {
        'available': 'success',
        'busy': 'warning',
        'offline': 'danger'
      }
      return typeMap[status] || 'info'
    },
    getOrgTypeLabel(orgType) {
      if (!orgType) return '-'
      // Use dictionary if available
      if (this.dict && this.dict.type && this.dict.type.team_org_type) {
        const dict = this.dict.type.team_org_type.find(item => item.value === orgType)
        if (dict) return dict.label
      }
      // Fallback to hardcoded mapping (including communication)
      const orgTypeMap = {
        'transportation': '交通委',
        'police': '公安',
        'firefighting': '消防',
        'medical': '医疗',
        'emergency': '应急',
        'company': '社会企业',
        'communication': '通信',
        'other': '其他'
      }
      return orgTypeMap[orgType] || orgType || '-'
    },
    getTeamTypeLabel(teamType) {
      if (!teamType) return '-'
      // Use dictionary if available
      if (this.dict && this.dict.type && this.dict.type.team_type) {
        const dict = this.dict.type.team_type.find(item => item.value === teamType)
        if (dict) return dict.label
      }
      // Fallback: return the raw value if dictionary not available
      return teamType
    }
  }
}
</script>

<style lang="scss" scoped>
.drawer-loading {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

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

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

.team-drawer-content {
  padding: 20px;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.team-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.team-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.phone-number {
  font-family: monospace;
  color: #409eff;
}

.capabilities-section {
  padding: 12px 0;
  
  .capability-tag {
    margin-right: 8px;
    margin-bottom: 8px;
  }
  
  .text-placeholder {
    color: #909399;
  }
}

.drawer-map-section {
  margin-top: 20px;
}

.map-container {
  border-radius: 4px;
  overflow: hidden;
}

.remark-section {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-word;
}

.drawer-error {
  padding: 20px;
}
</style>