<template>
  <el-drawer
    title="仓库详情"
    :visible.sync="drawerVisible"
    direction="rtl"
    size="560px"
    :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="warehouseData" class="warehouse-drawer-content">
      <div class="drawer-header">
        <div class="warehouse-title">
          <span class="warehouse-name">{{ warehouseData.warehouseName }}</span>
          <el-tag :type="getStatusTagType(warehouseData.status)" size="medium">
            {{ getStatusLabel(warehouseData.status) }}
          </el-tag>
        </div>
        <div class="warehouse-code">{{ warehouseData.warehouseCode }}</div>
      </div>

      <el-divider content-position="left">基本信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="仓库类型">{{ getWarehouseTypeLabel(warehouseData.warehouseType) }}</el-descriptions-item>
        <el-descriptions-item label="容量">{{ warehouseData.capacity != null ? `${warehouseData.capacity} ㎡` : '-' }}</el-descriptions-item>
        <el-descriptions-item label="所属单位">{{ warehouseData.belongOrgName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="单位类型">{{ getOrgTypeLabel(warehouseData.belongOrgType) }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">位置信息</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="详细地址">{{ warehouseData.address || '-' }}</el-descriptions-item>
        <el-descriptions-item v-if="hasLocation()" label="坐标">
          {{ warehouseData.longitude }}, {{ warehouseData.latitude }}
        </el-descriptions-item>
      </el-descriptions>

      <div v-if="hasLocation() && mapReady" class="drawer-map-section">
        <el-divider content-position="left">位置地图</el-divider>
        <div class="map-container">
          <Amap
            container-id="warehouse-detail-map"
            width="100%"
            height="280px"
            :center="[warehouseData.longitude, warehouseData.latitude]"
            :zoom="15"
            :markers="[
              {
                lat: warehouseData.latitude,
                lng: warehouseData.longitude,
                title: warehouseData.warehouseName || '仓库'
              }
            ]"
          />
        </div>
      </div>

      <el-divider content-position="left">联系信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="负责人">{{ warehouseData.manager || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">
          <span class="phone-number">{{ warehouseData.contactPhone || '-' }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider v-if="warehouseData.remark" content-position="left">备注</el-divider>
      <div v-if="warehouseData.remark" class="remark-section">
        {{ warehouseData.remark }}
      </div>
    </div>

    <div v-else class="drawer-error">
      <el-alert
        title="加载失败"
        type="error"
        :closable="false"
        show-icon
      >
        <template #default>
          <p>无法加载仓库详情，请稍后重试</p>
          <el-button size="mini" @click="loadWarehouseDetail">重试</el-button>
        </template>
      </el-alert>
    </div>
  </el-drawer>
</template>

<script>
import Amap from '@/components/Amap'
import { getWarehouse } from '@/api/resource/warehouse'

export default {
  name: 'WarehouseDetailDrawer',
  components: {
    Amap
  },
  dicts: ['warehouse_status', 'warehouse_type', 'team_org_type'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    warehouseId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      drawerVisible: false,
      loading: false,
      warehouseData: null,
      mapReady: false
    }
  },
  watch: {
    visible(newVal) {
      this.drawerVisible = newVal
      if (newVal && this.warehouseId) {
        this.loadWarehouseDetail()
      }
    },
    warehouseId(newVal) {
      if (newVal && this.drawerVisible) {
        this.loadWarehouseDetail()
      }
    },
    drawerVisible(newVal) {
      if (!newVal) {
        this.$emit('update:visible', false)
        this.reset()
      }
    }
  },
  methods: {
    async loadWarehouseDetail() {
      if (!this.warehouseId) return
      this.loading = true
      this.mapReady = false
      try {
        const response = await getWarehouse(this.warehouseId)
        if (response.code === 200) {
          this.warehouseData = response.data
        } else {
          this.$message.error(response.msg || '加载失败')
          this.warehouseData = null
        }
      } catch (error) {
        console.error('加载仓库详情失败:', error)
        this.$message.error('加载失败，请稍后重试')
        this.warehouseData = null
      } finally {
        this.loading = false
      }
    },
    handleClose(done) {
      this.reset()
      done()
    },
    handleOpened() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.mapReady = true
        }, 100)
      })
    },
    reset() {
      this.warehouseData = null
      this.mapReady = false
    },
    hasLocation() {
      return (
        this.warehouseData &&
        this.warehouseData.longitude &&
        this.warehouseData.latitude
      )
    },
    getStatusLabel(status) {
      if (this.dict?.type?.warehouse_status) {
        const dict = this.dict.type.warehouse_status.find(item => item.value === String(status))
        if (dict) return dict.label
      }
      return status === '0' ? '正常' : status === '1' ? '停用' : '未知'
    },
    getStatusTagType(status) {
      return status === '0' ? 'success' : status === '1' ? 'info' : 'default'
    },
    getWarehouseTypeLabel(type) {
      if (!type) return '-'
      if (this.dict?.type?.warehouse_type) {
        const dict = this.dict.type.warehouse_type.find(item => item.value === type)
        if (dict) return dict.label
      }
      return type
    },
    getOrgTypeLabel(orgType) {
      if (!orgType) return '-'
      if (this.dict?.type?.team_org_type) {
        const dict = this.dict.type.team_org_type.find(item => item.value === orgType)
        if (dict) return dict.label
      }
      return orgType
    }
  }
}
</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); }
}

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

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

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

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

.warehouse-code {
  font-size: 13px;
  color: #909399;
}

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

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

.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>