<template>
  <div class="harmless-place-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="harmlessPlaces" 
        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-space>
        </template>
        <template #status="{ text }">
          <a-tag :color="getStatusColor(text)">
            {{ text }}
          </a-tag>
        </template>
      </a-table>
    </div>
    
    <!-- 新增/编辑表单 -->
    <a-modal
      v-model:open="isModalOpen"
      :title="editingId ? '编辑无害化场所' : '新增无害化场所'"
      @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="harmless-place-form"
      >
        <a-form-item label="场所名称" name="name">
          <a-input 
            v-model:value="formData.name" 
            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="licenseNumber">
          <a-input 
            v-model:value="formData.licenseNumber" 
            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-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">{{ detailData.status }}</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, nextTick } from 'vue'
import api from '@/utils/api'
import { message } from 'ant-design-vue'

export default {
  setup() {
    // 响应式数据
    const harmlessPlaces = ref([])
    const loading = ref(false)
    const searchKeyword = ref('')
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })
    
    // 模态框状态
    const isModalOpen = ref(false)
    const isDetailModalOpen = ref(false)
    const editingId = ref('')
    const modalLoading = ref(false)
    
    // 表单引用和数据
    const formRef = ref()
    const formData = reactive({
      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' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }
    
    // 表格列配置
    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 getStatusColor = (status) => {
      const colorMap = {
        '正常': 'green',
        '维护中': 'orange',
        '停用': 'red'
      }
      return colorMap[status] || 'default'
    }
    
    // 获取无害化场所列表
    const fetchHarmlessPlaces = async () => {
      try {
        loading.value = true
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          keyword: searchKeyword.value
        }
        const res = await api.harmlessPlace.getList(params)
        if (res.code === 200) {
          harmlessPlaces.value = res.data.list || []
          pagination.total = res.data.total || 0
        } else {
          message.error(res.message || '获取无害化场所列表失败')
        }
      } catch (error) {
        console.error('获取无害化场所列表失败:', error)
        message.error('获取无害化场所列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 处理搜索
    const handleSearch = async (value) => {
      searchKeyword.value = value || ''
      pagination.current = 1
      await fetchHarmlessPlaces()
    }
    
    // 处理表格分页变化
    const handleTableChange = async (pagination) => {
      Object.assign(pagination, pagination)
      await fetchHarmlessPlaces()
    }
    
    // 重置表单
    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
      Object.assign(formData, {
        name: '',
        address: '',
        contactPerson: '',
        contactPhone: '',
        licenseNumber: '',
        status: '正常'
      })
      editingId.value = ''
    }
    
    // 处理新增
    const handleAdd = () => {
      resetForm()
      isModalOpen.value = true
    }
    
    // 处理编辑
    const handleEdit = async (record) => {
      try {
        // 重置表单
        resetForm()
        editingId.value = record.id
        
        // 从API获取详细数据
        const response = await api.harmlessPlace.getDetail(record.id)
        if (response && response.code === 200) {
          // 填充表单数据
          Object.assign(formData, {
            name: response.data.name,
            address: response.data.address,
            contactPerson: response.data.contactPerson,
            contactPhone: response.data.contactPhone,
            licenseNumber: response.data.licenseNumber,
            status: response.data.status
          })
          
          await nextTick()
          isModalOpen.value = true
        } else {
          message.error('获取无害化场所详情失败')
        }
      } catch (error) {
        message.error('获取无害化场所详情失败')
        console.error('获取无害化场所详情失败:', error)
      }
    }
    
    // 处理删除
    const handleDelete = async (id) => {
      try {
        loading.value = true
        const res = await api.harmlessPlace.delete(id)
        if (res.code === 200) {
          message.success('删除成功')
          await fetchHarmlessPlaces()
        } else {
          message.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除无害化场所失败:', error)
        message.error('删除失败')
      } finally {
        loading.value = false
      }
    }
    
    // 处理查看详情
    const handleDetail = async (record) => {
      try {
        const res = await api.harmlessPlace.getDetail(record.id)
        if (res.code === 200) {
          Object.assign(detailData, res.data)
          isDetailModalOpen.value = true
        } else {
          message.error(res.message || '获取详情失败')
        }
      } catch (error) {
        console.error('获取无害化场所详情失败:', error)
        message.error('获取详情失败')
      }
    }
    
    // 表单提交
    const handleOk = async () => {
      try {
        if (!formRef.value) return
        
        await formRef.value.validate()
        modalLoading.value = true
        
        let res
        
        if (editingId.value) {
          // 更新
          res = await api.harmlessPlace.update(editingId.value, formData)
        } else {
          // 新增
          res = await api.harmlessPlace.create(formData)
        }
        
        if (res.code === 200) {
          message.success(editingId.value ? '更新成功' : '创建成功')
          isModalOpen.value = false
          await fetchHarmlessPlaces()
        } else {
          message.error(res.message || (editingId.value ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        console.error(editingId.value ? '更新无害化场所失败' : '创建无害化场所失败', error)
        message.error(editingId.value ? '更新失败' : '创建失败')
      } finally {
        modalLoading.value = false
      }
    }
    
    // 处理取消
    const handleCancel = () => {
      isModalOpen.value = false
      resetForm()
    }
    
    // 处理详情弹窗取消
    const handleDetailCancel = () => {
      isDetailModalOpen.value = false
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchHarmlessPlaces()
    })
    
    return {
      harmlessPlaces,
      loading,
      searchKeyword,
      pagination,
      isModalOpen,
      isDetailModalOpen,
      modalLoading,
      editingId,
      formRef,
      formData,
      detailData,
      formRules,
      columns,
      getStatusColor,
      handleSearch,
      handleTableChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleDetail,
      handleOk,
      handleCancel,
      handleDetailCancel
    }
  }
}
</script>

<style scoped>
.harmless-place-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;
}

.detail-container {
  padding: 16px 0;
}

.detail-row {
  margin-bottom: 16px;
  line-height: 1.8;
}

.detail-label {
  display: inline-block;
  width: 100px;
  color: rgba(0, 0, 0, 0.45);
}

.detail-value {
  display: inline-block;
  color: rgba(0, 0, 0, 0.85);
}

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

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

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

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

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

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

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

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

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