<template>
  <div class="page-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">门店信息详情</span>
          <el-select v-model="currentStoreId" placeholder="选择门店" @change="handleStoreChange" style="width: 250px">
            <el-option v-for="store in stores" :key="store.id" :label="store.name" :value="store.id" />
          </el-select>
        </div>
      </template>

      <div v-loading="loading">
        <el-descriptions :column="2" border class="store-info-descriptions">
          <!-- Logo -->
          <el-descriptions-item label="门店Logo" :span="2">
            <el-avatar v-if="storeForm.logo" :size="80" shape="square" :src="storeForm.logo" />
            <span v-else>无</span>
          </el-descriptions-item>

          <!-- Name -->
          <el-descriptions-item label="门店名称">
            {{ storeForm.name || '-' }}
          </el-descriptions-item>

          <!-- Category -->
          <el-descriptions-item label="商户分类">
            {{ storeForm.category || '-' }}
          </el-descriptions-item>

          <!-- Services -->
          <el-descriptions-item label="服务项目" :span="2">
            <div class="service-tags">
              <el-tag v-for="tag in selectedServiceNames" :key="tag" type="success" effect="plain">
                {{ tag }}
              </el-tag>
              <span v-if="selectedServiceNames.length === 0">-</span>
            </div>
          </el-descriptions-item>

          <!-- Contact -->
          <el-descriptions-item label="联系人">
            {{ storeForm.contactPerson || '-' }}
          </el-descriptions-item>

          <el-descriptions-item label="联系电话">
            {{ storeForm.contactPhone || '-' }}
          </el-descriptions-item>

          <!-- Business hours -->
          <el-descriptions-item label="营业时间">
            {{ storeForm.businessHours[0] && storeForm.businessHours[1] ? `${storeForm.businessHours[0]} 至 ${storeForm.businessHours[1]}` : '-' }}
          </el-descriptions-item>

          <!-- Valid Until -->
          <el-descriptions-item label="有效期至">
            <el-tag type="warning" effect="dark">{{ storeForm.validUntil || '-' }}</el-tag>
          </el-descriptions-item>

          <!-- Address -->
          <el-descriptions-item label="详细地址" :span="2">
            {{ fullAddress || '-' }}
          </el-descriptions-item>

          <!-- Lat Lng -->
          <el-descriptions-item label="经纬度">
            <div v-if="storeForm.longitude && storeForm.latitude">
              <span>经度: {{ storeForm.longitude }}</span>
              <span style="margin-left: 20px">纬度: {{ storeForm.latitude }}</span>
            </div>
            <span v-else>-</span>
          </el-descriptions-item>

          <!-- License -->
          <el-descriptions-item label="营业执照" :span="2">
            <el-image
              v-if="storeForm.license"
              style="width: 200px; height: 140px; border-radius: 4px; border: 1px solid #dcdfe6"
              :src="storeForm.license"
              :preview-src-list="[storeForm.license]"
              fit="cover"
            />
            <span v-else>未上传</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue';
import { listOnMerchantStoreInfo, getStoreInfo } from '@/api/system/store';
import { listAllService as listOnStore } from '@/api/service/list';
import { useRegionData } from '@/hooks/useRegionData';

const { codeToName, loadRegionData } = useRegionData();
const currentStoreId = ref('');
const loading = ref(false);
const stores = ref([]);
const serviceOptions = ref([]);

const storeForm = reactive({
  id: '',
  logo: '',
  license: '',
  name: '',
  services: [],
  category: '',
  contactPerson: '',
  contactPhone: '',
  businessHours: ['', ''],
  validUntil: '',
  address: '',
  longitude: '',
  latitude: '',
  areaCode: '',
  selectedArea: []
});

// 计算选中的服务项目名称
const selectedServiceNames = computed(() => {
  return storeForm.services
    .map((id) => {
      const option = serviceOptions.value.find((item) => item.id === id);
      return option ? option.name : null;
    })
    .filter((name) => name !== null);
});

// 计算完整地址
const fullAddress = computed(() => {
  let areaText = '';
  if (storeForm.selectedArea && storeForm.selectedArea.length > 0) {
    areaText = storeForm.selectedArea.map((code) => codeToName(code)).join('');
  }
  return areaText + (storeForm.address || '');
});

// 获取门店列表
const getStoreList = async () => {
  try {
    const res = await listOnMerchantStoreInfo();
    const data = res.data;
    if (data && data.length > 0) {
      stores.value = data;
      currentStoreId.value = data[0].id;
      handleStoreChange(currentStoreId.value);
    }
  } catch (error) {
    console.error('获取门店列表失败:', error);
  }
};

// 获取服务项目选项
const getServiceOptions = async () => {
  try {
    const res = await listOnStore();
    if (res.data) {
      serviceOptions.value = res.data;
    }
  } catch (error) {
    console.error('获取服务项目失败:', error);
  }
};

// 切换门店加载详情
const handleStoreChange = async (val) => {
  if (!val) return;
  loading.value = true;
  try {
    const res = await getStoreInfo(val);
    const data = res.data;
    if (data) {
      storeForm.id = data.id;
      storeForm.logo = data.logoUrl || '';
      storeForm.license = data.businessLicenseUrl || '';
      storeForm.name = data.name || '';
      storeForm.services = data.services || [];
      storeForm.category = data.tenantCatergoriesName || '';
      storeForm.contactPerson = data.contact || '';
      storeForm.contactPhone = data.contactNumber || '';

      const start = data.startBusinessTime ? data.startBusinessTime.split(' ')[1]?.substring(0, 5) : '';
      const end = data.endBusinessTime ? data.endBusinessTime.split(' ')[1]?.substring(0, 5) : '';
      storeForm.businessHours = [start, end];

      storeForm.validUntil = data.validity ? data.validity.split(' ')[0] : '';

      storeForm.address = data.detailAddress || '';
      storeForm.longitude = data.longitude ? String(data.longitude) : '';
      storeForm.latitude = data.latitude ? String(data.latitude) : '';
      storeForm.areaCode = data.areaCode || '';

      if (data.areaCode) {
        if (Array.isArray(data.areaCode)) {
          storeForm.selectedArea = data.areaCode;
        } else if (typeof data.areaCode === 'string') {
          storeForm.selectedArea = data.areaCode.split(',');
        }
      } else {
        storeForm.selectedArea = [];
      }
    }
  } catch (error) {
    console.error('获取详细信息失败:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadRegionData();
  getServiceOptions();
  getStoreList();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}
.store-info-descriptions {
  margin-top: 20px;
}
.service-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
:deep(.el-descriptions__label) {
  width: 140px;
  justify-content: center !important;
  text-align: center !important;
  background-color: #f8f9fb !important;
  font-weight: bold;
  color: #606266;
}
:deep(.el-descriptions__content) {
  padding: 16px 20px;
}
</style>

