<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { storeApi } from '@/api/system.js'

// ─── State ────────────────────────────────────────────────────────────────────

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增门店')
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const searchForm = reactive({ keyword: '', status: '' })
const pagination = reactive({ page: 1, page_size: 20 })

// ─── Form ─────────────────────────────────────────────────────────────────────

const form = reactive({
  id: null,
  name: '',
  code: '',
  region: '',
  address: '',
  phone: '',
  contact: '',
  capacity: 1,
  description: '',
  status: 1
})

const formRules = {
  name: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  code: [
    { required: true, message: '请输入门店编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9_]+$/, message: '编码只允许大写字母、数字、下划线', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^[\d-()（）\s]+$/, message: '请输入正确的联系电话', trigger: 'blur' }
  ]
}

// ─── Methods ──────────────────────────────────────────────────────────────────

async function fetchList() {
  loading.value = true
  try {
    const res = await storeApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch {
    //
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pagination.page = 1
  fetchList()
}

function handleReset() {
  Object.assign(searchForm, { keyword: '', status: '' })
  handleSearch()
}

function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新增门店'
  Object.assign(form, {
    id: null, name: '', code: '', region: '', address: '',
    phone: '', contact: '', capacity: 1, description: '', status: 1
  })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = `编辑门店 - ${row.name}`
  const res = await storeApi.getDetail(row.id)
  const store = res.data
  Object.assign(form, {
    id: store.id,
    name: store.name,
    code: store.code,
    region: store.region || '',
    address: store.address || '',
    phone: store.phone || '',
    contact: store.contact || '',
    capacity: store.capacity || '',
    description: store.description || '',
    status: store.status
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
  } catch {
    return
  }
  submitLoading.value = true
  try {
    // 只发送后端接受的字段，过滤 id / region
    const { id, region, ...payload } = form
    if (isEdit.value) {
      await storeApi.update(id, payload)
      ElMessage.success('门店信息更新成功')
    } else {
      await storeApi.create(payload)
      ElMessage.success('门店创建成功')
    }
    dialogVisible.value = false
    fetchList()
  } catch {
    //
  } finally {
    submitLoading.value = false
  }
}

async function handleDelete(row) {
  await ElMessageBox.confirm(
    `确定删除门店「${row.name}」吗？删除后该门店下的数据将不可访问。`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  )
  await storeApi.delete(row.id)
  ElMessage.success('删除成功')
  fetchList()
}

async function handleStatusToggle(row) {
  const newStatus = row.status === 1 ? 0 : 1
  const label = newStatus === 1 ? '启用' : '停用'
  try {
    await storeApi.update(row.id, { ...row, status: newStatus })
    row.status = newStatus
    ElMessage.success(`门店已${label}`)
  } catch {
    //
  }
}

function handlePageChange(val) {
  pagination.page = val
  fetchList()
}

function handleSizeChange(val) {
  pagination.page_size = val
  pagination.page = 1
  fetchList()
}

onMounted(fetchList)
</script>

<template>
  <div class="p-6 space-y-4">
    <!-- Search -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input
        v-model="searchForm.keyword"
        placeholder="搜索门店名称/编码/地址"
        style="width: 260px"
        clearable
        @keydown.enter="handleSearch"
      >
        <template #prefix><el-icon><Search /></el-icon></template>
      </el-input>
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width: 120px">
        <el-option label="启用" :value="1" />
        <el-option label="停用" :value="0" />
      </el-select>
      <el-button type="primary" :icon="'Search'" @click="handleSearch">查询</el-button>
      <el-button :icon="'Refresh'" @click="handleReset">重置</el-button>
    </div>

    <!-- Table -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3"></div>
        <el-button type="primary" :icon="'Plus'" @click="handleAdd">新增门店</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width: 100%">
          <el-table-column prop="name" label="门店名称" min-width="160" />
          <el-table-column prop="code" label="门店编码" width="120" />
          <el-table-column label="所在地区" min-width="130">
            <template #default="{ row }">{{ row.region?.name || '' }}</template>
          </el-table-column>
          <el-table-column prop="address" label="详细地址" min-width="200" show-overflow-tooltip />
          <el-table-column prop="phone" label="联系电话" width="140" />
          <el-table-column prop="contact" label="联系人" width="100" />
          <el-table-column prop="capacity" label="床位数" width="80" align="center" />
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                {{ row.status === 1 ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button
                size="small"
                :type="row.status === 1 ? 'warning' : 'success'"
                text
                @click="handleStatusToggle(row)"
              >
                {{ row.status === 1 ? '停用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- Add/Edit Dialog -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="门店名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入门店名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店编码" prop="code">
              <el-input v-model="form.code" placeholder="如: HQ001" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在地区" prop="region">
              <el-input v-model="form.region" placeholder="如: 北京市朝阳区" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="负责人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="床位数量" prop="capacity">
              <el-input-number v-model="form.capacity" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="3"
                placeholder="门店备注信息（选填）"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '保存修改' : '确认创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- Add/Edit Dialog -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="门店名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入门店名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店编码" prop="code">
              <el-input v-model="form.code" placeholder="如: HQ001" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在地区" prop="region">
              <el-input v-model="form.region" placeholder="如: 北京市朝阳区" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="负责人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="床位数量" prop="capacity">
              <el-input-number v-model="form.capacity" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="3"
                placeholder="门店备注信息（选填）"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '保存修改' : '确认创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
