<template>
  <div class="factories">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>工厂库</span>
          <el-button type="primary" @click="handleAdd" v-if="isAdmin">新增工厂</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="工厂名称">
          <el-input v-model="searchForm.name" placeholder="请输入工厂名称" clearable />
        </el-form-item>

        <el-form-item label="省份">
          <el-input v-model="searchForm.province" placeholder="请输入省份" clearable />
        </el-form-item>

        <el-form-item label="城市">
          <el-input v-model="searchForm.city" placeholder="请输入城市" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工厂表格 -->
      <el-table :data="tableData" stripe v-loading="loading">
        <el-table-column prop="factory_name" label="工厂全称" />
        <el-table-column prop="factory_short_name" label="工厂简称" />
        <el-table-column prop="dealer_name" label="经销商名称" />
        <el-table-column prop="province" label="省份" />
        <el-table-column prop="city" label="城市" />
        <el-table-column prop="material_count" label="材料数量" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(row)" v-if="canEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)" v-if="canDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 工厂表单对话框 -->
    <FactoryForm
      v-if="showForm"
      :visible="showForm"
      :factory="currentFactory"
      @close="showForm = false"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getFactoryList, deleteFactory } from '@/api/factory'
import { ElMessage, ElMessageBox } from 'element-plus'
import FactoryForm from '@/components/FactoryForm.vue'

const router = useRouter()
const userStore = useUserStore()

const isAdmin = computed(() => userStore.isAdmin)

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  province: '',
  city: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 表单对话框
const showForm = ref(false)
const currentFactory = ref(null)

// 判断是否可以编辑
const canEdit = (row) => {
  if (isAdmin.value) return true
  return userStore.factoryId === row.id
}

// 判断是否可以删除
const canDelete = (row) => {
  if (isAdmin.value) return true
  return userStore.factoryId === row.id
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.size,
      ...searchForm
    }
    const data = await getFactoryList(params)
    tableData.value = data.results || data
    pagination.total = data.count || data.length
  } catch (error) {
    console.error('加载数据失败：', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    province: '',
    city: ''
  })
  pagination.page = 1
  loadData()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 新增
const handleAdd = () => {
  currentFactory.value = null
  showForm.value = true
}

// 查看
const handleView = (row) => {
  router.push(`/factories/${row.id}`)
}

// 编辑
const handleEdit = (row) => {
  currentFactory.value = { ...row }
  showForm.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该工厂吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteFactory(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 表单成功回调
const handleFormSuccess = () => {
  showForm.value = false
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.factories {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
