<template>
  <div class="slaughterhouse-container">
    <div class="page-header">
      <h1>屠宰场管理</h1>
    </div>
    
    <div class="content-wrapper">
      <!-- 工具栏 -->
      <div class="toolbar">
        <a-button type="primary" @click="handleAdd">新增屠宰场</a-button>
        <a-input-search 
          placeholder="搜索屠宰场名称" 
          style="width: 300px; margin-left: 16px;"
          @search="handleSearch"
          v-model:value="searchKeyword"
        />
      </div>
      
      <!-- 数据表格 -->
      <a-table 
        :columns="columns" 
        :data-source="slaughterhouses" 
        row-key="id"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #action="{ record }">
          <a-space>
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              title="确定要删除该屠宰场吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
            <a-button type="link" @click="handleDetail(record)">详情</a-button>
            <a-button type="link" @click="handleToggleStatus(record)">{{ record.status === '正常' ? '暂停' : '启用' }}</a-button>
          </a-space>
        </template>
        <template #status="{ text }">
          <a-tag :color="getStatusColor(text)">
            {{ getStatusText(text) }}
          </a-tag>
        </template>
      </a-table>
    </div>
    
    <!-- 新增/编辑表单 -->
    <a-modal
      v-model:open="isModalOpen"
      :title="formData.id ? '编辑屠宰场' : '新增屠宰场'"
      @ok="handleOk"
      @cancel="handleCancel"
      width="600px"
      :confirm-loading="modalLoading"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        class="slaughterhouse-form"
      >
        <a-form-item label="屠宰场名称" name="name">
          <a-input 
            v-model:value="formData.name" 
            placeholder="请输入屠宰场名称"
          />
        </a-form-item>
        
        <a-form-item label="许可证号" name="licenseNumber">
          <a-input 
            v-model:value="formData.licenseNumber" 
            placeholder="请输入许可证号"
          />
        </a-form-item>
        
        <a-form-item label="地址" name="address">
          <a-textarea 
            v-model:value="formData.address" 
            placeholder="请输入详细地址"
            :rows="3"
          />
        </a-form-item>
        
        <a-form-item label="联系人" name="contactPerson">
          <a-input 
            v-model:value="formData.contactPerson" 
            placeholder="请输入联系人姓名"
          />
        </a-form-item>
        
        <a-form-item label="联系电话" name="contactPhone">
          <a-input 
            v-model:value="formData.contactPhone" 
            placeholder="请输入联系电话"
          />
        </a-form-item>
        
        <a-form-item label="状态" name="status">
          <a-select 
            v-model:value="formData.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <a-select-option value="正常">正常</a-select-option>
            <a-select-option value="暂停营业">暂停营业</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="isDetailModalOpen"
      title="屠宰场详情"
      @cancel="handleDetailCancel"
    >
      <div class="detail-container">
        <div class="detail-row">
          <span class="detail-label">屠宰场名称：</span>
          <span class="detail-value">{{ detailData.name }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">地址：</span>
          <span class="detail-value">{{ detailData.address }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">联系人：</span>
          <span class="detail-value">{{ detailData.contactPerson }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">联系电话：</span>
          <span class="detail-value">{{ detailData.contactPhone }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">许可证号：</span>
          <span class="detail-value">{{ detailData.licenseNumber }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">状态：</span>
          <span class="detail-value"><a-tag :color="getStatusColor(detailData.status)">
            {{ getStatusText(detailData.status) }}
          </a-tag></span>
        </div>
        <div class="detail-row">
          <span class="detail-label">创建时间：</span>
          <span class="detail-value">{{ detailData.createTime }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">更新时间：</span>
          <span class="detail-value">{{ detailData.updateTime }}</span>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import api from '@/utils/api'

export default {
  setup() {
    // 数据列表
    const slaughterhouses = ref([])
    
    // 加载状态
    const loading = ref(false)
    
    // 搜索关键词
    const searchKeyword = ref('')
    
    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total) => `共 ${total} 条记录`
    })
    
    // 模态框状态
    const isModalOpen = ref(false)
    const isDetailModalOpen = ref(false)
    const modalLoading = ref(false)
    
    // 表单引用
    const formRef = ref(null)
    
    // 表单数据
    const formData = reactive({
      id: '',
      name: '',
      address: '',
      contactPerson: '',
      contactPhone: '',
      licenseNumber: '',
      status: '正常'
    })
    
    // 详情数据
    const detailData = reactive({})
    
    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入屠宰场名称', trigger: 'blur' }
      ],
      address: [
        { required: true, message: '请输入地址', trigger: 'blur' }
      ],
      contactPerson: [
        { required: true, message: '请输入联系人', trigger: 'blur' }
      ],
      contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' }
      ],
      licenseNumber: [
        { required: true, message: '请输入许可证号', trigger: 'blur' }
      ]
    }
    
    // 表格列配置
    const columns = [
      {
        title: '屠宰场名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '地址',
        dataIndex: 'address',
        key: 'address'
      },
      {
        title: '联系人',
        dataIndex: 'contactPerson',
        key: 'contactPerson'
      },
      {
        title: '联系电话',
        dataIndex: 'contactPhone',
        key: 'contactPhone'
      },
      {
        title: '许可证号',
        dataIndex: 'licenseNumber',
        key: 'licenseNumber'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        slots: { customRender: 'status' }
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime'
      },
      {
        title: '操作',
        key: 'action',
        slots: { customRender: 'action' }
      }
    ]
    
    // 获取屠宰场列表
    const fetchSlaughterhouses = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          keyword: searchKeyword.value
        }
        const response = await api.slaughter.getList(params)
        if (response && response.data) {
          slaughterhouses.value = response.data.list || []
          pagination.total = response.data.total || 0
        } else {
          slaughterhouses.value = []
          pagination.total = 0
        }
      } catch (error) {
        message.error('获取屠宰场列表失败')
        console.error('获取屠宰场列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 处理搜索
    const handleSearch = async () => {
      pagination.current = 1
      await fetchSlaughterhouses()
    }
    
    // 处理表格变化
    const handleTableChange = async (paginationConfig) => {
      Object.assign(pagination, paginationConfig)
      await fetchSlaughterhouses()
    }
    
    // 处理新增
    const handleAdd = () => {
      // 重置表单数据
      formData.id = null
      formData.name = ''
      formData.address = ''
      formData.contactPerson = ''
      formData.contactPhone = ''
      formData.licenseNumber = ''
      formData.status = '正常'
      
      // 重置表单验证状态
      if (formRef.value) {
        formRef.value.resetFields()
      }
      
      // 打开模态框
      isModalOpen.value = true
    }
    
    // 处理编辑
    const handleEdit = async (record) => {
      try {
        const response = await api.slaughter.getDetail(record.id)
        if (response && response.data) {
          // 确保状态字段正确映射
          const editData = {
            ...response.data,
            status: response.data.status === 'active' ? '正常' : response.data.status === 'inactive' ? '暂停营业' : response.data.status
          }
          Object.assign(formData, editData)
          isModalOpen.value = true
        }
      } catch (error) {
        message.error('获取屠宰场详情失败')
        console.error('获取屠宰场详情失败:', error)
      }
    }
    
    // 处理删除
    const handleDelete = async (id) => {
      try {
        const response = await api.slaughter.delete(id)
        if (response && response.code === 200) {
          message.success('删除成功')
          await fetchSlaughterhouses()
        }
      } catch (error) {
        message.error('删除失败')
        console.error('删除失败:', error)
      }
    }
    
    // 处理查看详情
    const handleDetail = async (record) => {
      try {
        const response = await api.slaughter.getDetail(record.id)
        if (response && response.data) {
          Object.assign(detailData, response.data)
          isDetailModalOpen.value = true
        }
      } catch (error) {
        message.error('获取屠宰场详情失败')
        console.error('获取屠宰场详情失败:', error)
      }
    }
    
    // 获取状态对应的颜色
    const getStatusColor = (status) => {
      const colorMap = {
        'active': 'green',
        'inactive': 'red',
        '正常': 'green',
        '暂停营业': 'red'
      }
      return colorMap[status] || 'default'
    }
    
    // 获取状态对应的中文文本
    const getStatusText = (status) => {
      const textMap = {
        'active': '正常',
        'inactive': '暂停营业',
        '正常': '正常',
        '暂停营业': '暂停营业'
      }
      return textMap[status] || status
    }
    
    // 处理切换状态
    const handleToggleStatus = async (record) => {
      try {
        const response = await api.slaughter.toggleStatus(record.id)
        if (response && response.code === 200) {
          message.success('状态切换成功')
          await fetchSlaughterhouses()
        }
      } catch (error) {
        message.error('状态切换失败')
        console.error('状态切换失败:', error)
      }
    }
    
    // 表单提交
    const handleOk = async () => {
      if (!formRef.value) return
      try {
        await formRef.value.validate()
        modalLoading.value = true
        
        // 准备提交数据，确保状态字段正确
        const submitData = {
          name: formData.name,
          address: formData.address,
          contactPerson: formData.contactPerson,
          contactPhone: formData.contactPhone,
          licenseNumber: formData.licenseNumber,
          status: formData.status === '正常' ? 'active' : formData.status === '暂停营业' ? 'inactive' : formData.status
        }
        
        let response
        if (formData.id) {
          // 更新
          response = await api.slaughter.update(formData.id, submitData)
        } else {
          // 新增
          response = await api.slaughter.create(submitData)
        }
        
        if (response && (response.code === 200 || response.code === 201)) {
          message.success(formData.id ? '更新成功' : '新增成功')
          isModalOpen.value = false
          await fetchSlaughterhouses()
        } else {
          message.error(response?.message || (formData.id ? '更新失败' : '新增失败'))
        }
      } catch (error) {
        if (error && error.errors && error.errors.length > 0) {
          message.error(error.errors[0].message)
        } else if (error && error.message) {
          message.error(error.message)
        } else {
          message.error(formData.id ? '更新失败' : '新增失败')
        }
        console.error(formData.id ? '更新失败:' : '新增失败:', error)
      } finally {
        modalLoading.value = false
      }
    }
    
    // 取消表单
    const handleCancel = () => {
      isModalOpen.value = false
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    // 取消详情
    const handleDetailCancel = () => {
      isDetailModalOpen.value = false
    }
    
    // 组件挂载时获取数据
    onMounted(async () => {
      await fetchSlaughterhouses()
    })
    
    return {
      slaughterhouses,
      loading,
      searchKeyword,
      pagination,
      isModalOpen,
      isDetailModalOpen,
      modalLoading,
      formRef,
      formData,
      detailData,
      formRules,
      columns,
      getStatusColor,
      getStatusText,
      handleSearch,
      handleTableChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleDetail,
      handleToggleStatus,
      handleOk,
      handleCancel,
      handleDetailCancel
    }
  }
}
</script>

<style scoped>
.slaughterhouse-container {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.toolbar {
  margin-bottom: 16px;
}

.content-wrapper {
  background: #fff;
  padding: 24px;
  border-radius: 2px;
}

/* 表单样式 */
.slaughterhouse-form {
  padding: 16px 0;
}

.slaughterhouse-form .ant-form-item {
  margin-bottom: 16px;
}

.slaughterhouse-form .ant-form-item-label > label {
  font-weight: 500;
  color: #262626;
}

.slaughterhouse-form .ant-input,
.slaughterhouse-form .ant-select,
.slaughterhouse-form .ant-textarea {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s;
}

.slaughterhouse-form .ant-input:hover,
.slaughterhouse-form .ant-select:hover,
.slaughterhouse-form .ant-textarea:hover {
  border-color: #40a9ff;
}

.slaughterhouse-form .ant-input:focus,
.slaughterhouse-form .ant-select:focus,
.slaughterhouse-form .ant-textarea:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.slaughterhouse-form .ant-select .ant-select-selector {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}

.slaughterhouse-form .ant-select .ant-select-selector:hover {
  border-color: #40a9ff;
}

.slaughterhouse-form .ant-select.ant-select-focused .ant-select-selector {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 详情弹窗样式 */
.detail-container {
  padding: 16px 0;
  max-height: 400px;
  overflow-y: auto;
}

.detail-row {
  margin-bottom: 16px;
  line-height: 1.8;
  display: flex;
  align-items: center;
}

.detail-label {
  display: inline-block;
  width: 100px;
  color: rgba(0, 0, 0, 0.65);
  font-weight: 500;
  flex-shrink: 0;
}

.detail-value {
  display: inline-block;
  color: rgba(0, 0, 0, 0.85);
  flex: 1;
}
</style>