<template>
  <div class="branch-management">
    <el-card class="main-card">
      <el-row :gutter="20" class="full-height">
        <!-- 左侧导航栏 -->
        <el-col :span="4">
          <div class="nav-container">
            <!-- 添加分店按钮 -->
            <el-button 
              type="primary" 
              class="add-btn"
              @click="showAddBranchDialog"
            >
              <el-icon><Plus /></el-icon> 添加分店
            </el-button>

            <!-- 三级导航菜单 -->
            <el-menu
              :default-active="activeIndex"
              class="vertical-menu"
              @select="handleMenuSelect"
            >
              <!-- 一级菜单：省份 -->
              <el-sub-menu 
                v-for="(province, provinceIndex) in provinces" 
                :key="province.name" 
                :index="`1-${provinceIndex + 1}`"
                @open="loadProvinceStores(province.name, provinceIndex)"
              >
                <template #title>
                  <div class="menu-title">
                    <el-icon><Location /></el-icon>
                    <span>{{ province.name }}</span>
                    <span v-if="province.stores.length > 0" class="store-count">({{ province.stores.length }})</span>
                  </div>
                </template>

                <!-- 如果该省份有分店，则显示分店列表 -->
                <el-sub-menu 
                  v-for="(store, storeIndex) in province.stores" 
                  :key="store.branchId" 
                  :index="`1-${provinceIndex + 1}-${storeIndex + 1}`" 
                >
                  <template #title>
                    <el-icon><OfficeBuilding /></el-icon>
                    {{ store.branchName }}
                  </template>

                  <!-- 三级菜单：功能页 -->
                  <el-menu-item :index="`1-${provinceIndex + 1}-${storeIndex + 1}-1`">
                    <el-icon><InfoFilled /></el-icon>基本信息
                  </el-menu-item>
                  <el-menu-item :index="`1-${provinceIndex + 1}-${storeIndex + 1}-2`">
                    <el-icon><UserFilled /></el-icon>负责人管理
                  </el-menu-item>
                  <el-menu-item :index="`1-${provinceIndex + 1}-${storeIndex + 1}-5`">
                    <el-icon><PieChart /></el-icon>营业情况
                  </el-menu-item>
                </el-sub-menu>
                
                <!-- 无分店时显示提示 -->
                <el-menu-item v-if="province.stores.length === 0" disabled class="no-stores">
                  <el-icon><Warning /></el-icon>暂无分店
                </el-menu-item>
              </el-sub-menu>
            </el-menu>
          </div>
        </el-col>

        <!-- 右侧内容区 -->
        <el-col :span="20">
          <!-- 空状态提示 -->
          <div v-if="!hasStores" class="empty-state">
            <el-empty description="暂无分店数据" class="empty-content">
              <el-button type="primary" @click="showAddBranchDialog" class="empty-btn">
                添加分店
              </el-button>
            </el-empty>
          </div>
          
          <!-- 基本信息 -->
          <el-card v-if="hasStores && currentTab === 'info'" class="content-card" v-loading="loading">
            <template #header>
              <div class="card-header">
                <h3 class="card-title">分店基本信息 - {{ currentBranch.branchName }}</h3>
                <div class="card-actions">
                  <el-button type="primary" @click="showEditBranchDialog" class="action-btn">
                    <el-icon><Edit /></el-icon>编辑信息
                  </el-button>
                  <el-button type="success" @click="navigateToBranch(currentBranch)" class="action-btn">
                    <el-icon><MapLocation /></el-icon>导航
                  </el-button>
                </div>
              </div>
            </template>
            <el-descriptions :column="2" border class="branch-desc">
              <el-descriptions-item label="地址">{{ currentBranch.branchAddress }}</el-descriptions-item>
              <el-descriptions-item label="电话">{{ currentBranch.branchPhone }}</el-descriptions-item>
              <el-descriptions-item label="营业时间">
                {{ currentBranch.branchStart }} - {{ currentBranch.branchEnd }}
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="currentBranch.branchStatus === '营业中' ? 'success' : 'danger'" effect="dark">
                  {{ currentBranch.branchStatus }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDate(currentBranch.createdAt) }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ formatDate(currentBranch.updatedAt) }}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 负责人管理 -->
          <el-card v-if="hasStores && currentTab === 'manager'" class="content-card" v-loading="loading">
            <template #header>
              <div class="card-header">
                <h3 class="card-title">负责人管理 - {{ currentBranch.branchName }}</h3>
                <div class="card-actions">
                  <el-button 
                    type="primary" 
                    @click="showSetBossDialog"
                    class="action-btn"
                  >
                    <el-icon><User /></el-icon>
                    {{ currentBranch.branchBoss ? '更换负责人' : '设置负责人' }}
                  </el-button>
                </div>
              </div>
            </template>
            
            <el-alert 
              v-if="!currentBranch.branchBoss" 
              title="该分店尚未设置负责人" 
              type="info" 
              show-icon 
              class="mb-16"
            />
            
            <div v-else>
              <el-descriptions :column="2" border v-if="currentBoss" class="boss-desc">
                <el-descriptions-item label="负责人ID">{{ currentBoss.accountId }}</el-descriptions-item>
                <el-descriptions-item label="姓名">{{ currentBoss.accountName }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ currentBoss.accountGender }}</el-descriptions-item>
                <el-descriptions-item label="电话">{{ currentBoss.accountPhone }}</el-descriptions-item>
                <el-descriptions-item label="薪资">{{ currentBoss.salary }}</el-descriptions-item>
              </el-descriptions>
              
              <div class="boss-actions" v-if="currentBoss">
                <el-button type="primary" @click="showEditBossDialog" class="edit-btn">
                  <el-icon><Edit /></el-icon>编辑负责人信息
                </el-button>
              </div>
            </div>
          </el-card>
      
          <!-- 营业情况 -->
          <el-card v-if="hasStores && currentTab === 'sales'" class="content-card" v-loading="loading">
            <template #header>
              <h3 class="card-title">营业情况 - {{ currentBranch.branchName }}</h3>
            </template>
            <el-table :data="salesData" border style="width: 100%" class="sales-table">
              <el-table-column prop="date" label="日期" align="center" />
              <el-table-column prop="orderCount" label="订单数" align="center" />
              <el-table-column prop="totalAmount" label="营业额(元)" align="center">
                <template #default="{ row }">
                  <span class="sales-amount">¥{{ row.totalAmount }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增分店弹窗 -->
    <el-dialog v-model="addBranchDialogVisible" title="新增分店" width="600px" class="branch-dialog">
      <el-form :model="newBranch" label-width="120px" ref="addBranchForm" class="branch-form">
        <el-form-item label="分店名称" prop="branchName" required>
          <el-input v-model="newBranch.branchName" placeholder="请输入分店名称" />
        </el-form-item>
        <el-form-item label="省份" prop="province" required>
          <el-select v-model="newBranch.province" placeholder="请选择省份" style="width: 100%">
            <el-option 
              v-for="province in provinces" 
              :key="province.name" 
              :label="province.name" 
              :value="province.name" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="branchAddress" required>
          <el-input v-model="newBranch.branchAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="branchPhone" required>
          <el-input v-model="newBranch.branchPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="开始营业" prop="branchStart" required>
          <el-time-picker 
            v-model="newBranch.branchStart" 
            placeholder="选择时间" 
            format="HH:mm" 
            value-format="HH:mm" 
          />
        </el-form-item>
        <el-form-item label="结束营业" prop="branchEnd" required>
          <el-time-picker 
            v-model="newBranch.branchEnd" 
            placeholder="选择时间" 
            format="HH:mm" 
            value-format="HH:mm" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addBranchDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="addBranch" class="confirm-btn">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑分店弹窗 -->
    <el-dialog v-model="editBranchDialogVisible" title="编辑分店信息" width="600px" class="branch-dialog">
      <el-form :model="editingBranch" label-width="120px" ref="editBranchForm" class="branch-form">
        <el-form-item label="分店名称" prop="branchName" required>
          <el-input v-model="editingBranch.branchName" placeholder="请输入分店名称" />
        </el-form-item>
        <el-form-item label="详细地址" prop="branchAddress" required>
          <el-input v-model="editingBranch.branchAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="branchPhone" required>
          <el-input v-model="editingBranch.branchPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="开始营业" prop="branchStart" required>
          <el-time-picker 
            v-model="editingBranch.branchStart" 
            placeholder="选择时间" 
            format="HH:mm" 
            value-format="HH:mm" 
          />
        </el-form-item>
        <el-form-item label="结束营业" prop="branchEnd" required>
          <el-time-picker 
            v-model="editingBranch.branchEnd" 
            placeholder="选择时间" 
            format="HH:mm" 
            value-format="HH:mm" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="branchStatus" required>
          <el-select v-model="editingBranch.branchStatus" placeholder="请选择状态" style="width: 100%">
            <el-option label="营业中" value="营业中" />
            <el-option label="装修中" value="装修中" />
            <el-option label="暂停营业" value="暂停营业" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editBranchDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="updateBranch" class="confirm-btn">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置负责人弹窗 -->
    <el-dialog v-model="setBossDialogVisible" title="设置负责人" width="500px" class="boss-dialog">
      <el-form :model="bossRequest" label-width="120px" ref="setBossForm" class="boss-form">
        <el-form-item label="负责人ID" prop="bossId" required>
          <el-input 
            v-model.number="bossRequest.bossId" 
            placeholder="请输入负责人账号ID" 
            type="number" 
          />
        </el-form-item>
        <el-alert 
          title="注意：设置负责人后，该账号将拥有分店管理权限" 
          type="warning" 
          show-icon 
          class="mb-16 alert-warning"
        />
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setBossDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="setBranchBoss" class="confirm-btn">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑负责人信息弹窗 -->
    <el-dialog v-model="editBossDialogVisible" title="编辑负责人信息" width="500px" class="boss-dialog">
      <el-form :model="editingBoss" label-width="120px" ref="editBossForm" class="boss-form">
        <el-form-item label="姓名" prop="name" required>
          <el-input v-model="editingBoss.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender" required>
          <el-select v-model="editingBoss.gender" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" required>
          <el-input v-model="editingBoss.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="薪资" prop="salary" required>
          <el-input-number 
            v-model="editingBoss.salary" 
            :precision="2" 
            :step="100" 
            :min="0" 
            controls-position="right" 
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editBossDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="updateBossInfo" class="confirm-btn">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  OfficeBuilding,
  Plus,
  Location,
  Edit,
  MapLocation,
  InfoFilled,
  UserFilled,
  PieChart,
  User,
  Warning
} from '@element-plus/icons-vue';

// 省份列表（静态数据）
const provinces = ref([
  { name: '北京', stores: [], loaded: false },
  { name: '上海', stores: [], loaded: false },
  { name: '广东', stores: [], loaded: false },
  { name: '江苏', stores: [], loaded: false },
  { name: '浙江', stores: [], loaded: false },
  { name: '四川', stores: [], loaded: false },
  { name: '湖北', stores: [], loaded: false },
  { name: '湖南', stores: [], loaded: false },
  { name: '福建', stores: [], loaded: false },
  { name: '山东', stores: [], loaded: false },
  { name: '辽宁', stores: [], loaded: false },
  { name: '吉林', stores: [], loaded: false },
  { name: '黑龙江', stores: [], loaded: false },
  { name: '河北', stores: [], loaded: false },
  { name: '山西', stores: [], loaded: false },
  { name: '河南', stores: [], loaded: false },
  { name: '安徽', stores: [], loaded: false },
  { name: '江西', stores: [], loaded: false },
  { name: '重庆', stores: [], loaded: false },
  { name: '云南', stores: [], loaded: false },
  { name: '贵州', stores: [], loaded: false },
  { name: '陕西', stores: [], loaded: false },
  { name: '甘肃', stores: [], loaded: false },
  { name: '青海', stores: [], loaded: false },
  { name: '西藏', stores: [], loaded: false },
  { name: '内蒙古', stores: [], loaded: false },
  { name: '广西', stores: [], loaded: false },
  { name: '宁夏', stores: [], loaded: false },
  { name: '新疆', stores: [], loaded: false },
  { name: '香港', stores: [], loaded: false },
  { name: '澳门', stores: [], loaded: false },
  { name: '台湾', stores: [], loaded: false }
]);

// 当前选中的省份索引、分店索引、功能页
const currentProvinceIndex = ref(0);
const currentStoreIndex = ref(0);
const currentTab = ref('info');

// 当前选中的分店数据
const currentBranch = ref({});
// 当前分店的负责人信息
const currentBoss = ref(null);
// 营业数据
const salesData = ref([]);

// 弹窗控制
const addBranchDialogVisible = ref(false);
const editBranchDialogVisible = ref(false);
const setBossDialogVisible = ref(false);
const editBossDialogVisible = ref(false);

// 表单数据
const newBranch = ref({
  branchName: '',
  province: '',
  branchAddress: '',
  branchPhone: '',
  branchStart: '09:00',
  branchEnd: '22:00'
});

const editingBranch = ref({});
const bossRequest = ref({ bossId: null });
const editingBoss = ref({
  name: '',
  gender: '',
  phone: '',
  salary: 0
});

// 新增：管理当前激活菜单项
const activeIndex = ref('');
// 新增：加载状态
const loading = ref(true);
// 新增：当前位置信息
const currentPosition = ref(null);

// 计算属性：是否有分店数据
const hasStores = computed(() => {
  return provinces.value.some(p => p.stores.length > 0)
});

// 格式化时间显示
const formatTime = (time) => {
  if (!time) return '--:--';
  return time.length === 5 ? time : `${time}:00`;
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  // 处理LocalDateTime格式 (yyyy-MM-ddTHH:mm:ss)
  if (dateStr.includes('T')) {
    const [datePart] = dateStr.split('T');
    return datePart;
  }
  // 处理旧格式
  return dateStr;
};

// 导航菜单点击处理
const handleMenuSelect = (index) => {
  const parts = index.split('-');
  const provinceIndexStr = parts[1];
  const storeIndexStr = parts[2];
  const tabIndex = parts[3];

  if (provinceIndexStr && !isNaN(provinceIndexStr)) {
    const provinceIndex = parseInt(provinceIndexStr) - 1;

    // 确保省份索引有效
    if (provinceIndex >= 0 && provinceIndex < provinces.value.length) {
      const province = provinces.value[provinceIndex];
      
      // 如果有分店索引且有效
      if (storeIndexStr && !isNaN(storeIndexStr)) {
        const storeIndex = parseInt(storeIndexStr) - 1;
        
        if (storeIndex >= 0 && storeIndex < province.stores.length) {
          currentStoreIndex.value = storeIndex;
          currentBranch.value = province.stores[storeIndex];
          currentProvinceIndex.value = provinceIndex;
          
          // 加载负责人信息
          if (currentBranch.value.branchId) {
            loadBossInfo(currentBranch.value.branchId);
          }
        }
      }

      // 更新当前标签页
      if (tabIndex) {
        const tabsMap = {
          '1': 'info',
          '2': 'manager',
          '5': 'sales'
        };
        currentTab.value = tabsMap[tabIndex] || 'info';
        
        // 如果需要营业数据则加载
        if (currentTab.value === 'sales' && currentBranch.value.branchId) {
          loadSalesData(currentBranch.value.branchId);
        }
      }
    }
  }
};

// 加载所有省份的分店数据
const loadAllStores = async () => {
  loading.value = true;
  try {
    // 并行加载所有省份数据
    const promises = provinces.value.map((province, index) => 
      loadProvinceStores(province.name, index)
    );
    
    await Promise.all(promises);
    
    // 查找第一个有分店的省份
    const firstProvinceWithStores = provinces.value.find(p => p.stores.length > 0);
    if (firstProvinceWithStores) {
      const provinceIndex = provinces.value.indexOf(firstProvinceWithStores);
      const storeIndex = 0;
      
      // 设置当前选中的分店
      currentProvinceIndex.value = provinceIndex;
      currentStoreIndex.value = storeIndex;
      currentBranch.value = firstProvinceWithStores.stores[storeIndex];
      
      // 设置激活菜单项
      activeIndex.value = `1-${provinceIndex + 1}-${storeIndex + 1}-1`;
      
      // 加载相关数据
      if (currentBranch.value.branchId) {
        loadBossInfo(currentBranch.value.branchId);
        loadSalesData(currentBranch.value.branchId);
      }
    }
    
    ElMessage.success('分店数据加载完成');
  } catch (error) {
    console.error('加载分店数据失败:', error);
    ElMessage.error('分店数据加载失败');
  } finally {
    loading.value = false;
  }
};

// 加载省份分店数据
const loadProvinceStores = async (province, provinceIndex) => {
  const provinceData = provinces.value[provinceIndex];
  
  // 如果已经加载过，不再重复加载
  if (provinceData.loaded) return;
  
  try {
    const response = await axios.get(`http://localhost:8080/admin/branch/province/${province}`);
    provinceData.stores = response.data;
    provinceData.loaded = true;
  } catch (error) {
    console.error(`加载${province}分店数据失败:`, error);
    // 保留错误提示，但继续执行其他省份加载
  }
};

// 加载负责人信息 (修复后的方法)
const loadBossInfo = async (branchId) => {
  try {
    const response = await axios.get(`http://localhost:8080/admin/branch/boss/${branchId}`);
    currentBoss.value = response.data;
    ElMessage.success('负责人信息加载成功');
  } catch (error) {
    console.error('加载负责人信息失败:', error);
    
    // 处理404错误（未找到负责人）
    if (error.response && error.response.status === 404) {
      currentBoss.value = null;
      ElMessage.warning('该分店尚未设置负责人');
    } else {
      ElMessage.error('加载负责人信息失败');
    }
  }
};

// 加载营业数据
const loadSalesData = async (branchId) => {
  try {
    const response = await axios.get(`http://localhost:8080/admin/branch/${branchId}/dailyStats`);
    // 将数据转换为数组形式
    salesData.value = Object.entries(response.data).map(([date, stats]) => ({
      date: date.substring(0, 10), // 只取日期部分
      orderCount: stats.orderCount,
      totalAmount: stats.totalAmount
    }));
  } catch (error) {
    console.error('加载营业数据失败:', error);
    ElMessage.error('加载营业数据失败');
  }
};

// 显示新增分店弹窗
const showAddBranchDialog = () => {
  newBranch.value = {
    branchName: '',
    province: '',
    branchAddress: '',
    branchPhone: '',
    branchStart: '09:00',
    branchEnd: '22:00'
  };
  addBranchDialogVisible.value = true;
};

// 新增分店
const addBranch = async () => {
  try {
    // 设置默认值
    const branchToAdd = {
      ...newBranch.value,
      branchStatus: '营业中',
      branchBoss: null,
      isDeleted: 0
    };
    
    const response = await axios.post('http://localhost:8080/admin/branch/add', branchToAdd);
    
    if (response.data) {
      ElMessage.success('分店添加成功');
      addBranchDialogVisible.value = false;
      
      // 刷新省份数据
      const provinceIndex = provinces.value.findIndex(p => p.name === newBranch.value.province);
      if (provinceIndex !== -1) {
        provinces.value[provinceIndex].loaded = false;
        loadProvinceStores(newBranch.value.province, provinceIndex);
      }
      
      // 重新加载所有数据
      loadAllStores();
    } else {
      ElMessage.error('分店添加失败');
    }
  } catch (error) {
    console.error('添加分店失败:', error);
    ElMessage.error('添加分店失败: ' + error.message);
  }
};

// 显示编辑分店弹窗
const showEditBranchDialog = () => {
  editingBranch.value = { ...currentBranch.value };
  editBranchDialogVisible.value = true;
};

// 更新分店信息
const updateBranch = async () => {
  try {
    const response = await axios.put(
      `http://localhost:8080/admin/branch/${editingBranch.value.branchId}`, 
      editingBranch.value
    );
    
    if (response.data) {
      ElMessage.success('分店信息更新成功');
      editBranchDialogVisible.value = false;
      
      // 更新当前显示的分店信息
      Object.assign(currentBranch.value, editingBranch.value);
      
      // 更新省份列表中的分店信息
      const storeIndex = provinces.value[currentProvinceIndex.value].stores
        .findIndex(s => s.branchId === editingBranch.value.branchId);
      
      if (storeIndex !== -1) {
        Object.assign(
          provinces.value[currentProvinceIndex.value].stores[storeIndex], 
          editingBranch.value
        );
      }
    } else {
      ElMessage.error('分店信息更新失败');
    }
  } catch (error) {
    console.error('更新分店失败:', error);
    ElMessage.error('更新分店失败: ' + error.message);
  }
};

// 显示设置负责人弹窗
const showSetBossDialog = () => {
  bossRequest.value = { bossId: null };
  setBossDialogVisible.value = true;
};

// 设置分店负责人 (修复后的方法)
const setBranchBoss = async () => {
  try {
    const response = await axios.put(
      `http://localhost:8080/admin/branch/${currentBranch.value.branchId}/boss`,
      bossRequest.value
    );
    
    if (response.data) {
      ElMessage.success('负责人设置成功');
      setBossDialogVisible.value = false;
      
      // 更新当前分店信息
      currentBranch.value.branchBoss = bossRequest.value.bossId;
      
      // 重新加载负责人信息
      loadBossInfo(currentBranch.value.branchId);
      
      // 更新省份列表中的分店信息
      const storeIndex = provinces.value[currentProvinceIndex.value].stores
        .findIndex(s => s.branchId === currentBranch.value.branchId);
      
      if (storeIndex !== -1) {
        provinces.value[currentProvinceIndex.value].stores[storeIndex].branchBoss = bossRequest.value.bossId;
      }
    } else {
      ElMessage.error('负责人设置失败');
    }
  } catch (error) {
    console.error('设置负责人失败:', error);
    
    // 处理特定错误情况
    if (error.response) {
      if (error.response.status === 400) {
        ElMessage.error('该分店已有负责人');
      } else if (error.response.status === 404) {
        ElMessage.error('指定的负责人账号不存在');
      } else {
        ElMessage.error('设置负责人失败: ' + error.response.data);
      }
    } else {
      ElMessage.error('设置负责人失败: ' + error.message);
    }
  }
};

// 显示编辑负责人弹窗
const showEditBossDialog = () => {
  if (currentBoss.value) {
    editingBoss.value = {
      name: currentBoss.value.accountName,
      gender: currentBoss.value.accountGender,
      phone: currentBoss.value.accountPhone,
      salary: currentBoss.value.salary
    };
    editBossDialogVisible.value = true;
  }
};

// 更新负责人信息 (修复后的方法)
const updateBossInfo = async () => {
  try {
    // 构建后端需要的请求格式
    const bossUpdateData = {
      name: editingBoss.value.name,
      gender: editingBoss.value.gender,
      phone: editingBoss.value.phone,
      salary: editingBoss.value.salary
    };
    
    const response = await axios.put(
      `http://localhost:8080/admin/branch/${currentBranch.value.branchId}/boss-info`,
      bossUpdateData
    );
    
    if (response.data) {
      ElMessage.success('负责人信息更新成功');
      editBossDialogVisible.value = false;
      
      // 更新当前负责人信息
      Object.assign(currentBoss.value, {
        accountName: editingBoss.value.name,
        accountGender: editingBoss.value.gender,
        accountPhone: editingBoss.value.phone,
        salary: editingBoss.value.salary
      });
    } else {
      ElMessage.error('负责人信息更新失败');
    }
  } catch (error) {
    console.error('更新负责人失败:', error);
    
    // 处理特定错误情况
    if (error.response) {
      if (error.response.status === 404) {
        ElMessage.error('该分店没有负责人或负责人账号不存在');
      } else {
        ElMessage.error('更新负责人失败: ' + error.response.data);
      }
    } else {
      ElMessage.error('更新负责人失败: ' + error.message);
    }
  }
};

// 新增：获取当前位置
const getCurrentLocation = () => {
  return new Promise((resolve, reject) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        position => resolve(position.coords),
        error => reject(error),
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 0
        }
      );
    } else {
      reject(new Error('浏览器不支持地理位置服务'));
    }
  });
};

// 新增：导航到分店
const navigateToBranch = async (branch) => {
  // 如果没有分店的经纬度，则提示
  if (!branch.latitude || !branch.longitude) {
    ElMessage.error('该分店未设置位置信息');
    return;
  }

  try {
    // 获取当前位置
    const coords = await getCurrentLocation();
    const fromLng = coords.longitude;
    const fromLat = coords.latitude;
    const toLng = branch.longitude;
    const toLat = branch.latitude;

    // 构造高德地图导航URL
    const fromName = '我的位置';
    const toName = branch.branchAddress || '分店位置';
    const url = `https://uri.amap.com/navigation?from=${fromLng},${fromLat},${encodeURIComponent(fromName)}&to=${toLng},${toLat},${encodeURIComponent(toName)}&mode=car&src=mypage&coordinate=gaode`;

    window.open(url, '_blank');
  } catch (error) {
    console.error('获取当前位置失败:', error);
    // 如果获取当前位置失败，则只提供终点（分店位置）
    const toLng = branch.longitude;
    const toLat = branch.latitude;
    const toName = branch.branchAddress || '分店位置';
    const url = `https://uri.amap.com/navigation?to=${toLng},${toLat},${encodeURIComponent(toName)}&mode=car&src=mypage&coordinate=gaode`;
    window.open(url, '_blank');
  }
};

// 初始化加载所有省份的数据
onMounted(() => {
  loadAllStores();
});
</script>

<style scoped>
.branch-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.main-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.main-card :deep(.el-card__body) {
  padding: 0;
}

.full-height {
  height: calc(100vh - 100px);
}

.nav-container {
  height: 600px;
  display: flex;
  flex-direction: column;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.add-btn {
  width: 100%;
  margin-bottom: 16px;
  border-radius: 20px;
  padding: 10px 20px;
  font-weight: 600;
  background: linear-gradient(45deg, #409eff, #64b5f6);
  border: none;
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.25);
  transition: all 0.3s;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.35);
}

.vertical-menu {
  flex: 1;
  overflow-y: auto;
  border: none;
  border-radius: 8px;
  background-color: #fff;
}

.vertical-menu :deep(.el-sub-menu__title),
.vertical-menu :deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  color: #5a5e66;
  transition: all 0.2s;
  border-radius: 8px;
  margin: 4px 0;
}

.vertical-menu :deep(.el-sub-menu__title):hover,
.vertical-menu :deep(.el-menu-item):hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.vertical-menu :deep(.el-menu-item.is-active) {
  background: linear-gradient(90deg, #ecf5ff, #fff);
  color: #409eff;
  font-weight: 600;
  border-left: 4px solid #409eff;
}

.menu-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #409eff;
}

.menu-title .el-icon {
  margin-right: 10px;
  font-size: 18px;
}

.store-count {
  margin-left: 6px;
  font-size: 12px;
  color: #909399;
}

.no-stores {
  color: #909399;
  font-size: 13px;
}

.empty-state {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
}

.empty-content {
  padding: 40px;
  background-color: #f8fafc;
  border-radius: 12px;
}

.empty-btn {
  border-radius: 20px;
  padding: 10px 24px;
  font-weight: 500;
}

.content-card {
  margin-top: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: none;
}

.content-card :deep(.el-card__header) {
  background: linear-gradient(120deg, #f0f7ff, #e6f7ff);
  border-radius: 8px 8px 0 0;
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  border-radius: 20px;
  padding: 8px 16px;
}

.branch-desc :deep(.el-descriptions__header) {
  margin-bottom: 16px;
}

.branch-desc :deep(.el-descriptions__label) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.boss-desc :deep(.el-descriptions__label) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.boss-actions {
  margin-top: 20px;
  text-align: right;
}

.edit-btn {
  border-radius: 20px;
  padding: 8px 20px;
}

.sales-table :deep(th) {
  background-color: #f5f7fa !important;
  font-weight: 600;
  color: #409eff;
}

.sales-table :deep(tr:hover) {
  background-color: #f0f7ff !important;
}

.sales-amount {
  font-weight: 600;
  color: #ff6b6b;
}

.mb-16 {
  margin-bottom: 16px;
}

.mt-20 {
  margin-top: 20px;
}

.branch-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.branch-form {
  padding: 20px 30px 0 10px;
}

.boss-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.boss-form {
  padding: 20px 30px 0 10px;
}

.alert-warning {
  border-radius: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px 20px;
}

.cancel-btn {
  border-radius: 20px;
  padding: 8px 20px;
}

.confirm-btn {
  border-radius: 20px;
  padding: 8px 20px;
  background: linear-gradient(45deg, #409eff, #64b5f6);
  border: none;
  transition: all 0.3s;
}

.confirm-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.3);
}
</style>