<template>
  <div class="store-info">
    <el-card class="header-card">
      <el-row :gutter="24">
        <el-col :span="18">
          <div class="card-header">
            <span class="header-title">分店信息管理</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="function-selector">
            <el-radio-group v-model="activeTab" size="large">
              <el-radio-button :value="1">基础信息</el-radio-button>
              <el-radio-button :value="2">营业状况</el-radio-button>
            </el-radio-group>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 基础信息表单 -->
    <el-card v-if="activeTab === 1" class="form-card" v-loading="loading">
      <template #header>
        <span class="card-title">基础信息设置</span>
      </template>

      <el-form
        ref="basicFormRef"
        :model="basicForm"
        :rules="basicRules"
        label-width="120px"
        class="basic-form"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="分店名称" prop="branchName">
              <el-input v-model="basicForm.branchName" placeholder="请输入分店名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分店电话" prop="branchPhone">
              <el-input
                v-model="basicForm.branchPhone"
                placeholder="请输入分店联系电话"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="分店地址" prop="branchAddress">
              <div class="address-selector">
                <el-select
                  v-model="addressForm.province"
                  placeholder="请选择省份"
                  @change="onProvinceChange"
                  style="width: 150px; margin-right: 12px"
                >
                  <el-option
                    v-for="province in provinces"
                    :key="province.adcode"
                    :label="province.name"
                    :value="province.adcode"
                  />
                </el-select>
                <el-select
                  v-model="addressForm.city"
                  placeholder="请选择城市"
                  @change="onCityChange"
                  style="width: 150px; margin-right: 12px"
                >
                  <el-option
                    v-for="city in cities"
                    :key="city.adcode"
                    :label="city.name"
                    :value="city.adcode"
                  />
                </el-select>
                <el-select
                  v-model="addressForm.district"
                  placeholder="请选择区域"
                  @change="onDistrictChange"
                  style="width: 150px; margin-right: 12px"
                >
                  <el-option
                    v-for="district in districts"
                    :key="district.adcode"
                    :label="district.name"
                    :value="district.adcode"
                  />
                </el-select>
              </div>
              <el-input
                v-model="basicForm.branchAddress"
                placeholder="请输入详细地址"
                style="margin-top: 12px"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 地图组件 -->
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="位置地图">
              <Map
                :province="getProvinceName(addressForm.province)"
                :city="getCityName(addressForm.city)"
                :district="getDistrictName(addressForm.district)"
                :address="basicForm.branchAddress"
                @update-address="onMapAddressUpdate"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="分店负责人" prop="branchBoss">
              <el-input
                v-model="basicForm.branchBoss"
                disabled
                placeholder="请输入分店负责人"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item class="form-actions">
          <el-button type="primary" @click="saveBasicInfo" :loading="saving">
            <el-icon><Check /></el-icon>
            保存信息
          </el-button>
          <el-button @click="resetBasicForm">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 营业状况表单 -->
    <el-card v-if="activeTab === 2" class="form-card" v-loading="loading">
      <template #header>
        <span class="card-title">营业状况设置</span>
      </template>

      <el-form
        ref="businessFormRef"
        :model="businessForm"
        :rules="businessRules"
        label-width="120px"
        class="business-form"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="营业状态" prop="branchStatus">
              <el-radio-group v-model="businessForm.branchStatus">
                <el-radio value="营业中">
                  <el-tag type="success">营业中</el-tag>
                </el-radio>
                <el-radio value="暂停营业">
                  <el-tag type="warning">暂停营业</el-tag>
                </el-radio>
                <el-radio value="停业整顿">
                  <el-tag type="danger">停业整顿</el-tag>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="营业时间" prop="businessHours">
              <div class="time-range">
                <el-time-picker
                  v-model="businessForm.branchStart"
                  placeholder="营业开始时间"
                  format="HH:mm"
                  value-format="HH:mm"
                  style="width: 150px"
                />
                <span class="time-separator">至</span>
                <el-time-picker
                  v-model="businessForm.branchEnd"
                  placeholder="营业结束时间"
                  format="HH:mm"
                  value-format="HH:mm"
                  style="width: 150px"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item class="form-actions">
          <el-button type="primary" @click="saveBusinessInfo" :loading="saving">
            <el-icon><Check /></el-icon>
            保存设置
          </el-button>
          <el-button @click="resetBusinessForm">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

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

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const recordLoading = ref(false)
const activeTab = ref(1)
const recordDialogVisible = ref(false)
const user = reactive({
  account_id: 'ACC001',
  account_name: '张三',
  account_password: 'password123',
  account_phone: '13800138000',
  account_type: '员工',
  account_img: '/images/user001.jpg',
  account_gender: '男',
  account_tag: 'VIP',
  salary: 5000.0,
  is_deleted: 0,
})

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

// 基础信息表单
const basicForm = reactive({
  branchId: 0,
  branchName: '',
  branchAddress: '',
  branchPhone: '',
  branchBoss: user.account_name,
})

// 营业信息表单
const businessForm = reactive({
  branchId: 0,
  branchStatus: '营业中',
  branchStart: '09:00',
  branchEnd: '22:00',
})

// 地址选择表单
const addressForm = reactive({
  province: '',
  city: '',
  district: '',
})

// 地址选项数据
interface DistrictItem {
  adcode: string
  name: string
}

interface BossItem {
  id: string
  name: string
  phone: string
}

const provinces = ref<DistrictItem[]>([])
const cities = ref<DistrictItem[]>([])
const districts = ref<DistrictItem[]>([])
const bossOptions = ref<BossItem[]>([])

// 修改记录
const modifyRecords = ref([])

// API 基础URL
const API_BASE_URL = 'http://localhost:8080/api'

async function fetchDistricts(keywords: string) {
  try {
    const response = await axios.get(`${API_BASE_URL}/district`, { params: { keywords } })
    return response.data[0]?.districts || []
  } catch (error) {
    ElMessage.error(`获取行政区划失败 (keywords: ${error}):`)
    return [] // 出错时返回空数组
  }
}

const onProvinceChange = async () => {
  cities.value = await fetchDistricts(addressForm.province)
}
const onCityChange = async () => {
  districts.value = await fetchDistricts(addressForm.city)
}
const onDistrictChange = async () => {
  // 区域变化处理
  console.log('区域已变更:', addressForm.district)
}

// 获取省份名称
const getProvinceName = (adcode: string) => {
  const province = provinces.value.find((p) => p.adcode === adcode)
  return province?.name || ''
}

// 获取城市名称
const getCityName = (adcode: string) => {
  const city = cities.value.find((c) => c.adcode === adcode)
  return city?.name || ''
}

// 获取区域名称
const getDistrictName = (adcode: string) => {
  const district = districts.value.find((d) => d.adcode === adcode)
  return district?.name || ''
}

// 地图地址更新回调
const onMapAddressUpdate = (address: string) => {
  basicForm.branchAddress = address
  ElMessage.success('地址已更新')
}

// 保存基础信息
const saveBasicInfo = async () => {
  if (!basicFormRef.value) return

  try {
    await basicFormRef.value.validate()
    saving.value = true

    // 构建完整的地址
    const fullAddress =
      getProvinceName(addressForm.province) +
      getCityName(addressForm.city) +
      getDistrictName(addressForm.district) +
      basicForm.branchAddress

    // 创建要发送的数据
    const branchData = {
      ...basicForm,
      branchAddress: fullAddress,
      branchBoss: user.account_id,
    }

    // 发送请求保存数据
    const response = await axios.post(`${API_BASE_URL}/branch/basic-info`, branchData)

    if (response.data.code === 200) {
      // 更新ID（如果是新创建的店铺）
      if (response.data.data && response.data.data.branchId) {
        basicForm.branchId = response.data.data.branchId
        businessForm.branchId = response.data.data.branchId
      }
      ElMessage.success(response.data.message || '基础信息保存成功')

      // 重新获取店铺信息
      await getBasicForm()
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error: any) {
    ElMessage.error(`保存失败：${error.response?.data?.message || error.message || '未知错误'}`)
  } finally {
    saving.value = false
  }
}

// 重置基础表单
const resetBasicForm = () => {
  basicFormRef.value?.resetFields()
  Object.assign(addressForm, {
    province: '',
    city: '',
    district: '',
  })
  cities.value = []
  districts.value = []
}

// 保存营业信息
const saveBusinessInfo = async () => {
  if (!businessFormRef.value) return

  try {
    await businessFormRef.value.validate()
    saving.value = true

    // 检查是否有分店ID
    if (!businessForm.branchId) {
      ElMessage.warning('请先保存基础信息')
      activeTab.value = 1 // 切换到基础信息页签
      return
    }

    // 构建营业信息数据
    const businessInfo = {
      branchStatus: businessForm.branchStatus,
      branchStart: businessForm.branchStart,
      branchEnd: businessForm.branchEnd,
    }

    // 发送请求更新营业信息
    const response = await axios.put(
      `${API_BASE_URL}/branch/${businessForm.branchId}/business-info`,
      businessInfo,
    )

    if (response.data.code === 200) {
      ElMessage.success(response.data.message || '营业信息更新成功')
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error: any) {
    ElMessage.error(`更新失败：${error.response?.data?.message || error.message || '未知错误'}`)
  } finally {
    saving.value = false
  }
}

// 重置营业表单
const resetBusinessForm = () => {
  businessFormRef.value?.resetFields()
}

// 表单验证规则
const basicRules = {
  branchName: [
    { required: true, message: '请输入分店名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分店名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  branchPhone: [
    { required: true, message: '请输入分店电话', trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/,
      message: '请输入正确的电话号码',
      trigger: 'blur',
    },
  ],
  branchAddress: [
    { required: true, message: '请输入分店地址', trigger: 'blur' },
    { min: 5, max: 200, message: '地址长度在 5 到 200 个字符', trigger: 'blur' },
  ],
  branchBoss: [{ required: true, message: '请选择分店负责人', trigger: 'change' }],
}

const businessRules = {
  branchStatus: [{ required: true, message: '请选择营业状态', trigger: 'change' }],
  businessHours: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!businessForm.branchStart || !businessForm.branchEnd) {
          callback(new Error('请设置完整的营业时间'))
        } else if (businessForm.branchStart >= businessForm.branchEnd) {
          callback(new Error('营业结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
}

// 获取基础表单数据
const getBasicForm = async () => {
  try {
    loading.value = true

    const response = await axios.get(`${API_BASE_URL}/branch/by-boss/${user.account_id}`, {})

    if (response.data.code === 200 && response.data.data.length > 0) {
      const data = response.data.data[0]

      // 基础信息表单赋值
      basicForm.branchId = data.branchId
      basicForm.branchName = data.branchName
      basicForm.branchAddress = data.branchAddress
      basicForm.branchPhone = data.branchPhone

      // 营业信息表单赋值
      businessForm.branchId = data.branchId
      businessForm.branchStatus = data.branchStatus
      businessForm.branchStart = data.branchStart
      businessForm.branchEnd = data.branchEnd

      // 简单地址解析
      const address = data.branchAddress // "广东省深圳市福田区中山路123号"
      const match = address.match(/^(.+?省)(.+?市)(.+?区)(.*)$/)
      if (match) {
        const [, provinceName, cityName, districtName, detailAddr] = match

        // 设置省份
        const province = provinces.value.find((p) => p.name === provinceName)
        if (province) {
          addressForm.province = province.adcode
          await onProvinceChange()

          // 设置城市
          const city = cities.value.find((c) => c.name === cityName)
          if (city) {
            addressForm.city = city.adcode
            await onCityChange()

            // 设置区域
            const district = districts.value.find((d) => d.name === districtName)
            if (district) {
              addressForm.district = district.adcode
            }
          }
        }

        // 更新详细地址
        basicForm.branchAddress = detailAddr
      }

      ElMessage.success('门店信息加载成功')
    }
  } catch (error) {
    ElMessage.error('获取门店信息失败')
  } finally {
    loading.value = false
  }
}

const showModifyRecords = () => {
  recordDialogVisible.value = true
}

// 组件挂载时获取数据
onMounted(async () => {
  provinces.value = await fetchDistricts('中国')
  await getBasicForm()
})
</script>

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

.header-card {
  margin-bottom: 5px;
  border-radius: 5px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

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

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.function-selector {
  margin-top: 5px;
  text-align: center;
}

.form-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.basic-form,
.business-form {
  padding: 20px;
}

.address-selector {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.time-range {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time-separator {
  color: var(--el-text-color-secondary);
  font-weight: 500;
}

.form-actions {
  margin-top: 32px;
  text-align: center;
}

.form-actions .el-button {
  min-width: 120px;
  margin: 0 8px;
}

/* 表单项样式优化 */
.el-form-item {
  margin-bottom: 24px;
}

.el-form-item__label {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

/* 选择器样式 */
.el-select .el-select__placeholder {
  color: var(--el-text-color-placeholder);
}

/* 单选按钮组样式 */
.el-radio-group .el-radio {
  margin-right: 20px;
}

.el-radio__label {
  padding-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .store-info {
    padding: 12px;
  }

  .address-selector {
    flex-direction: column;
    align-items: stretch;
  }

  .address-selector .el-select {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 12px;
  }

  .time-range {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .time-range .el-time-picker {
    width: 100% !important;
  }

  .form-actions .el-button {
    width: 100%;
    margin: 8px 0;
  }
}

/* 表格样式优化 */
.el-table {
  border-radius: 6px;
  overflow: hidden;
}

.el-table th {
  background-color: var(--el-fill-color-light);
  font-weight: 600;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 6px;
  font-weight: 500;
}

.el-button--primary {
  background: linear-gradient(135deg, #409eff, #66b3ff);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(135deg, #66b3ff, #409eff);
}
</style>
