<template>
  <div class="store-info-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>店铺信息管理</h1>
      <div class="header-actions">
        <el-button @click="refreshData" :icon="Refresh">刷新</el-button>
      </div>
    </div>

    <!-- 标签页切换 -->
    <el-tabs v-model="activeTab" class="store-tabs">
      <el-tab-pane label="基础信息" name="basic">
        <el-card class="info-card" v-loading="loading.basic">
          <el-form
            ref="basicFormRef"
            :model="formData.basic"
            :rules="rules.basic"
            label-width="120px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="分店名称" prop="branchName">
                  <el-input
                    v-model="formData.basic.branchName"
                    placeholder="请输入分店名称"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="branchPhone">
                  <el-input
                    v-model="formData.basic.branchPhone"
                    placeholder="请输入联系电话"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="店铺地址" prop="branchAddress">
              <el-input
                v-model="formData.basic.branchAddress"
                placeholder="请输入完整地址（省市区街道门牌号）"
                clearable
                @blur="handleAddressBlur"
              >
                <template #append>
                  <el-button @click="parseAddress" :loading="parsing">
                    <el-icon><Location /></el-icon>
                    解析地址
                  </el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input-number
                    v-model="formData.basic.longitude"
                    :precision="6"
                    :min="-180"
                    :max="180"
                    placeholder="经度"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input-number
                    v-model="formData.basic.latitude"
                    :precision="6"
                    :min="-90"
                    :max="90"
                    placeholder="纬度"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 地图组件 -->
            <el-form-item label="地图定位">
              <Map
                ref="mapRef"
                :address="formData.basic.branchAddress"
                :longitude="formData.basic.longitude"
                :latitude="formData.basic.latitude"
                @update-location="handleLocationUpdate"
              />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="省份" prop="province">
                  <el-input
                    v-model="formData.basic.province"
                    placeholder="自动解析省份"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人" prop="branchBoss">
                  <el-input
                    v-model="formData.basic.branchBoss"
                    disabled
                    placeholder="店铺负责人"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button type="primary" @click="saveBasicInfo" :loading="saving.basic">
                保存基础信息
              </el-button>
              <el-button @click="resetForm('basic')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="营业信息" name="business">
        <el-card class="info-card" v-loading="loading.business">
          <el-form
            ref="businessFormRef"
            :model="formData.business"
            :rules="rules.business"
            label-width="120px"
          >
            <el-form-item label="营业状态" prop="branchStatus">
              <el-select
                v-model="formData.business.branchStatus"
                placeholder="请选择营业状态"
                style="width: 100%"
              >
                <el-option label="营业中" value="open" />
                <el-option label="休息中" value="closed" />
              </el-select>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="branchStart">
                  <el-time-picker
                    v-model="formData.business.branchStart"
                    placeholder="选择开始时间"
                    format="HH:mm"
                    value-format="HH:mm"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="branchEnd">
                  <el-time-picker
                    v-model="formData.business.branchEnd"
                    placeholder="选择结束时间"
                    format="HH:mm"
                    value-format="HH:mm"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button type="primary" @click="saveBusinessInfo" :loading="saving.business">
                保存营业信息
              </el-button>
              <el-button @click="resetForm('business')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="店铺列表" name="list">
        <el-card class="info-card">
          <!-- 搜索栏 -->
          <div class="search-bar">
            <el-input
              v-model="searchParams.keyword"
              placeholder="搜索分店名称"
              clearable
              style="width: 200px"
              @clear="fetchBranchList"
            />
            <el-select
              v-model="searchParams.branchStatus"
              placeholder="营业状态"
              clearable
              style="width: 150px; margin-left: 10px"
              @change="fetchBranchList"
            >
              <el-option label="营业中" value="open" />
              <el-option label="休息中" value="closed" />
            </el-select>
            <el-button type="primary" @click="fetchBranchList" style="margin-left: 10px">
              搜索
            </el-button>
          </div>

          <!-- 表格 -->
          <el-table
            :data="branchList"
            v-loading="loading.list"
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column prop="branchName" label="分店名称" min-width="150" />
            <el-table-column prop="branchAddress" label="地址" min-width="200" />
            <el-table-column prop="branchPhone" label="联系电话" width="120" />
            <el-table-column prop="branchStatus" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.branchStatus === 'open' ? 'success' : 'info'">
                  {{ row.branchStatus === 'open' ? '营业中' : '休息中' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="营业时间" width="150">
              <template #default="{ row }">
                {{ row.branchStart }} - {{ row.branchEnd }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="editBranch(row)">编辑</el-button>
                <el-button type="danger" size="small" @click="deleteBranch(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 20px; justify-content: center"
            @size-change="fetchBranchList"
            @current-change="fetchBranchList"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Refresh, Location } from '@element-plus/icons-vue'
import axios from 'axios'
import Map from '@/components/Map.vue'

// 获取本地存储的用户信息
interface UserInfo {
  accountId: number
  accountName: string
  accountType: string
}

// 获取用户信息的工具函数
const getUserInfo = (): UserInfo | null => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      return JSON.parse(userInfoStr)
    } catch (e) {
      console.error('解析用户信息失败:', e)
    }
  }
  return null
}

// 获取accountId
const getAccountId = (): number | null => {
  const userInfo = getUserInfo()
  return userInfo ? userInfo.accountId : null
}

// 类型定义
interface Branch {
  branchId?: number
  branchName: string
  branchAddress: string
  branchPhone?: string
  branchStart?: string
  branchEnd?: string
  branchStatus: string
  branchBoss?: number
  province?: string
  latitude?: number
  longitude?: number
}

interface PaginationParams {
  current: number
  size: number
  total: number
}

// 响应式数据
const baseURL = 'http://localhost:8080'
const accountId = ref<number | null>(getAccountId())
const activeTab = ref('basic')
const currentBranchId = ref<number | null>(null)
const parsing = ref(false)
const mapRef = ref<any>(null)

// 表单引用
const basicFormRef = ref<FormInstance>()
const businessFormRef = ref<FormInstance>()

// 加载状态
const loading = reactive({
  basic: false,
  business: false,
  list: false,
})

// 保存状态
const saving = reactive({
  basic: false,
  business: false,
})

// 表单数据
const formData = reactive({
  basic: {
    branchName: '',
    branchAddress: '',
    branchPhone: '',
    branchBoss: accountId.value,
    province: '',
    latitude: null as number | null,
    longitude: null as number | null,
  },
  business: {
    branchStatus: 'open',
    branchStart: '09:00',
    branchEnd: '22:00',
  },
})

// 搜索参数
const searchParams = reactive({
  keyword: '',
  branchStatus: '',
})

// 分页参数
const pagination = reactive<PaginationParams>({
  current: 1,
  size: 10,
  total: 0,
})

// 分店列表
const branchList = ref<Branch[]>([])

// 表单验证规则
const rules = {
  basic: {
    branchName: [
      { required: true, message: '请输入分店名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    ],
    branchAddress: [
      { required: true, message: '请输入分店地址', trigger: 'blur' },
      { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' },
    ],
    branchPhone: [
      { pattern: /^1[3-9]\d{9}$|^\d{3,4}-\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' },
    ],
  },
  business: {
    branchStatus: [{ required: true, message: '请选择营业状态', trigger: 'change' }],
    branchStart: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    branchEnd: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  },
}

// 处理地址输入框失焦事件
const handleAddressBlur = () => {
  if (formData.basic.branchAddress) {
    parseAddress()
  }
}

// 解析地址
const parseAddress = async () => {
  if (!formData.basic.branchAddress) {
    ElMessage.warning('请输入地址')
    return
  }

  parsing.value = true
  
  // 通知地图组件解析地址
  await nextTick()
  if (mapRef.value) {
    mapRef.value.geocodeAddress(formData.basic.branchAddress)
  }
  
  // 从地址中提取省份
  const provinceMatch = formData.basic.branchAddress.match(/^(.+?(?:省|市|自治区|特别行政区))/)
  if (provinceMatch) {
    formData.basic.province = provinceMatch[1].replace(/省|市|自治区|特别行政区/, '')
  }
  
  parsing.value = false
}

// 处理地图位置更新
const handleLocationUpdate = (data: { 
  address: string, 
  longitude: number, 
  latitude: number,
  province?: string 
}) => {
  formData.basic.branchAddress = data.address
  formData.basic.longitude = data.longitude
  formData.basic.latitude = data.latitude
  
  if (data.province) {
    formData.basic.province = data.province.replace(/省|市|自治区|特别行政区/, '')
  }
  
  ElMessage.success('地址已更新')
}

// 获取当前用户的分店信息
const fetchMyBranch = async () => {
  if (!accountId.value) {
    ElMessage.warning('未获取到用户信息')
    return
  }

  try {
    loading.basic = true
    loading.business = true
    
    const response = await axios.get(`${baseURL}/branch/branch/by-boss/${accountId.value}`)
    
    if (response.data.code === 200 && response.data.data && response.data.data.length > 0) {
      const branch = response.data.data[0]
      currentBranchId.value = branch.branchId
      
      // 填充基础信息
      formData.basic.branchName = branch.branchName || ''
      formData.basic.branchAddress = branch.branchAddress || ''
      formData.basic.branchPhone = branch.branchPhone || ''
      formData.basic.province = branch.province || ''
      formData.basic.latitude = branch.latitude || null
      formData.basic.longitude = branch.longitude || null
      
      // 填充营业信息
      formData.business.branchStatus = branch.branchStatus || 'open'
      formData.business.branchStart = branch.branchStart || '09:00'
      formData.business.branchEnd = branch.branchEnd || '22:00'
    }
  } catch (error) {
    console.error('获取分店信息失败:', error)
    ElMessage.error('获取分店信息失败')
  } finally {
    loading.basic = false
    loading.business = false
  }
}

// 保存基础信息
const saveBasicInfo = async () => {
  if (!basicFormRef.value) return
  
  await basicFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      saving.basic = true
      
      const data: Branch = {
        ...formData.basic,
        branchBoss: accountId.value!,
        branchStatus: formData.business.branchStatus,
      }
      
      if (currentBranchId.value) {
        data.branchId = currentBranchId.value
      }
      
      const response = await axios.post(`${baseURL}/branch/branch/basic-info`, data)
      
      if (response.data.code === 200) {
        ElMessage.success('保存成功')
        if (response.data.data && response.data.data.branchId) {
          currentBranchId.value = response.data.data.branchId
        }
        fetchMyBranch()
      } else {
        ElMessage.error(response.data.message || '保存失败')
      }
    } catch (error) {
      console.error('保存基础信息失败:', error)
      ElMessage.error('保存失败')
    } finally {
      saving.basic = false
    }
  })
}

// 保存营业信息
const saveBusinessInfo = async () => {
  if (!businessFormRef.value) return
  
  await businessFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    if (!currentBranchId.value) {
      ElMessage.warning('请先保存基础信息')
      activeTab.value = 'basic'
      return
    }
    
    try {
      saving.business = true
      
      const response = await axios.put(
        `${baseURL}/branch/branch/${currentBranchId.value}/business-info`,
        formData.business
      )
      
      if (response.data.code === 200) {
        ElMessage.success('更新成功')
        fetchMyBranch()
      } else {
        ElMessage.error(response.data.message || '更新失败')
      }
    } catch (error) {
      console.error('更新营业信息失败:', error)
      ElMessage.error('更新失败')
    } finally {
      saving.business = false
    }
  })
}

// 获取分店列表
const fetchBranchList = async () => {
  try {
    loading.list = true
    
    const params = {
      current: pagination.current,
      size: pagination.size,
      keyword: searchParams.keyword,
      branchStatus: searchParams.branchStatus,
      branchBoss: accountId.value,
    }
    
    const response = await axios.get(`${baseURL}/branch/branch/page`, { params })
    
    if (response.data.code === 200) {
      branchList.value = response.data.data.records || []
      pagination.total = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取列表失败')
    }
  } catch (error) {
    console.error('获取分店列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.list = false
  }
}

// 编辑分店
const editBranch = (branch: Branch) => {
  currentBranchId.value = branch.branchId!
  
  // 切换到基础信息标签页
  activeTab.value = 'basic'
  
  // 填充表单数据
  formData.basic.branchName = branch.branchName
  formData.basic.branchAddress = branch.branchAddress
  formData.basic.branchPhone = branch.branchPhone || ''
  formData.basic.province = branch.province || ''
  formData.basic.latitude = branch.latitude || null
  formData.basic.longitude = branch.longitude || null
  
  formData.business.branchStatus = branch.branchStatus
  formData.business.branchStart = branch.branchStart || '09:00'
  formData.business.branchEnd = branch.branchEnd || '22:00'
}

// 删除分店
const deleteBranch = async (branch: Branch) => {
  await ElMessageBox.confirm(`确定要删除分店"${branch.branchName}"吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  
  try {
    const response = await axios.delete(`${baseURL}/branch/branch/${branch.branchId}`)
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchBranchList()
      
      // 如果删除的是当前编辑的分店，清空表单
      if (branch.branchId === currentBranchId.value) {
        currentBranchId.value = null
        resetForm('basic')
        resetForm('business')
      }
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除分店失败:', error)
    ElMessage.error('删除失败')
  }
}

// 重置表单
const resetForm = (type: 'basic' | 'business') => {
  if (type === 'basic') {
    basicFormRef.value?.resetFields()
    formData.basic.branchBoss = accountId.value
    formData.basic.province = ''
    formData.basic.latitude = null
    formData.basic.longitude = null
  } else {
    businessFormRef.value?.resetFields()
  }
}

// 刷新数据
const refreshData = () => {
  if (activeTab.value === 'list') {
    fetchBranchList()
  } else {
    fetchMyBranch()
  }
}

// 监听标签页切换
watch(activeTab, (newVal) => {
  if (newVal === 'list') {
    fetchBranchList()
  }
})

// 页面挂载时执行
onMounted(() => {
  if (!accountId.value) {
    ElMessage.error('未获取到用户信息，请重新登录')
    return
  }
  
  fetchMyBranch()
})
</script>

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

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.store-tabs {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.info-card {
  margin-top: 20px;
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-tag {
  cursor: default;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    margin-top: 10px;
  }

  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-bar > * {
    margin: 5px 0 !important;
    width: 100% !important;
  }
}
</style>
