<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="expertData" class="expert-drawer-content">
      <div class="drawer-header">
        <div class="expert-title">
          <span class="expert-name">{{ expertData.expertName }}</span>
          <el-tag :type="getStatusTagType(expertData.status)" size="medium">
            {{ getStatusLabel(expertData.status) }}
          </el-tag>
        </div>
        <div class="expert-code">{{ expertData.expertCode || '-' }}</div>
      </div>

      <el-divider content-position="left">基本信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="所属单位">{{ expertData.organization || '-' }}</el-descriptions-item>
        <el-descriptions-item label="身份证">{{ expertData.idCard || '-' }}</el-descriptions-item>
        <el-descriptions-item label="评分">
          <el-rate :value="expertData.rating || 0" disabled allow-half show-score />
        </el-descriptions-item>
        <el-descriptions-item label="资格状态">
          <dict-tag :options="dict.type.expert_status" :value="expertData.status" />
        </el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">专长领域</el-divider>
      <div class="chip-list">
        <el-tag
          v-for="(item, index) in expertData.specialtiesArray"
          :key="index"
          size="small"
          class="chip-item"
        >
          {{ getSpecialtyLabel(item) }}
        </el-tag>
        <span v-if="!expertData.specialtiesArray.length" class="text-placeholder">暂无</span>
      </div>

      <el-divider content-position="left">能力标签</el-divider>
      <div class="chip-list">
        <el-tag
          v-for="(item, index) in expertData.capabilitiesArray"
          :key="index"
          size="small"
          type="success"
          class="chip-item"
        >
          {{ item }}
        </el-tag>
        <span v-if="!expertData.capabilitiesArray.length" class="text-placeholder">暂无</span>
      </div>

      <el-divider content-position="left">联系方式</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="电话">{{ expertData.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ expertData.email || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更多联系方式">
          <div v-if="expertData.contactsArray.length" class="contact-list">
            <div v-for="(item, index) in expertData.contactsArray" :key="index" class="contact-item">
              <strong>{{ contactTypeLabel(item.type) }}</strong>
              <span v-if="item.label">（{{ item.label }}）</span>
              <span>：{{ item.value }}</span>
            </div>
          </div>
          <span v-else>-</span>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">常驻位置</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="地址">{{ expertData.locationName || expertData.address || '-' }}</el-descriptions-item>
        <el-descriptions-item v-if="hasLocation()" label="坐标">
          {{ expertData.longitude }}, {{ expertData.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="expert-detail-map"
            width="100%"
            height="260px"
            :center="[expertData.longitude, expertData.latitude]"
            :zoom="15"
            :markers="[
              {
                lat: expertData.latitude,
                lng: expertData.longitude,
                title: expertData.locationName || expertData.expertName
              }
            ]"
          />
        </div>
      </div>

      <el-divider v-if="expertData.remark" content-position="left">备注</el-divider>
      <div v-if="expertData.remark" class="remark-section">
        {{ expertData.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="loadExpertDetail">重试</el-button>
        </template>
      </el-alert>
    </div>
  </el-drawer>
</template>

<script>
import Amap from '@/components/Amap'
import { getExpert } from '@/api/resource/expert'

export default {
  name: 'ExpertDetailDrawer',
  components: {
    Amap
  },
  dicts: ['expert_status'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    expertId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      drawerVisible: false,
      loading: false,
      expertData: null,
      mapReady: false
    }
  },
  watch: {
    visible(newVal) {
      this.drawerVisible = newVal
      if (newVal && this.expertId) {
        this.loadExpertDetail()
      }
    },
    expertId(newVal) {
      if (newVal && this.drawerVisible) {
        this.loadExpertDetail()
      }
    },
    drawerVisible(newVal) {
      if (!newVal) {
        this.$emit('update:visible', false)
        this.reset()
      }
    }
  },
  methods: {
    async loadExpertDetail() {
      if (!this.expertId) return
      this.loading = true
      this.mapReady = false
      try {
        const response = await getExpert(this.expertId)
        if (response.code === 200) {
          this.expertData = this.decorateExpert(response.data || {})
        } else {
          this.$message.error(response.msg || '加载失败')
          this.expertData = null
        }
      } catch (error) {
        console.error('加载专家详情失败:', error)
        this.$message.error('加载失败，请稍后重试')
        this.expertData = null
      } finally {
        this.loading = false
      }
    },
    decorateExpert(data) {
      const clone = { ...data }
      clone.specialtiesArray = this.safeJsonArray(clone.specialties)
      clone.capabilitiesArray = this.safeJsonArray(clone.capabilities)
      clone.contactsArray = this.safeJsonArray(clone.contacts)
      return clone
    },
    safeJsonArray(val) {
      if (!val) return []
      try {
        const arr = JSON.parse(val)
        return Array.isArray(arr) ? arr : []
      } catch (e) {
        return []
      }
    },
    handleClose(done) {
      this.reset()
      done()
    },
    handleOpened() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.mapReady = true
        }, 100)
      })
    },
    reset() {
      this.expertData = null
      this.mapReady = false
    },
    hasLocation() {
      return this.expertData && this.expertData.longitude && this.expertData.latitude
    },
    getStatusLabel(status) {
      if (!status) return '-'
      if (this.dict?.type?.expert_status) {
        const dict = this.dict.type.expert_status.find(item => item.value === status)
        if (dict) return dict.label
      }
      const map = {
        active: '启用',
        inactive: '停用',
        blacklisted: '黑名单'
      }
      return map[status] || status
    },
    getStatusTagType(status) {
      const map = {
        active: 'success',
        inactive: 'info',
        blacklisted: 'danger'
      }
      return map[status] || 'default'
    },
    getSpecialtyLabel(value) {
      return value || '-'
    },
    contactTypeLabel(type) {
      const map = {
        phone: '电话',
        mobile: '手机',
        email: '邮箱',
        wechat: '微信',
        emergency: '紧急联系人'
      }
      return map[type] || '其他'
    }
  }
}
</script>

<style scoped lang="scss">
.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); }
}

.expert-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;
}

.expert-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

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

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

.chip-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 28px;
}

.chip-item {
  margin-right: 0;
}

.contact-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.contact-item {
  font-size: 13px;
}

.text-placeholder {
  color: #c0c4cc;
}

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