<template>
  <div class="smart-collar-container">
    <a-card title="智能项圈管理" :bordered="false">
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form layout="inline" :model="searchForm">
            <a-form-item label="项圈编号">
              <a-input v-model:value="searchForm.collarId" placeholder="请输入项圈编号" />
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model:value="searchForm.status" placeholder="请选择状态" style="width: 120px">
                <a-select-option value="active">使用中</a-select-option>
                <a-select-option value="inactive">未使用</a-select-option>
                <a-select-option value="maintenance">维护中</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      
      <a-row style="margin-top: 16px">
        <a-col :span="24">
          <a-button type="primary" @click="showAddModal">
            <template #icon><PlusOutlined /></template>
            添加项圈
          </a-button>
        </a-col>
      </a-row>
      
      <a-table
        style="margin-top: 16px"
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="showEditModal(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="showDetailModal(record)">详情</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此项圈吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a class="danger-text">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
      
      <!-- 添加/编辑模态框 -->
      <a-modal
        :title="modalTitle"
        :visible="modalVisible"
        :confirm-loading="modalLoading"
        @ok="handleModalOk"
        @cancel="handleModalCancel"
      >
        <a-form :model="formData" :rules="rules" ref="formRef" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
          <a-form-item label="项圈编号" name="collarId">
            <a-input v-model:value="formData.collarId" placeholder="请输入项圈编号" />
          </a-form-item>
          <a-form-item label="项圈名称" name="name">
            <a-input v-model:value="formData.name" placeholder="请输入项圈名称" />
          </a-form-item>
          <a-form-item label="状态" name="status">
            <a-select v-model:value="formData.status" placeholder="请选择状态">
              <a-select-option value="active">使用中</a-select-option>
              <a-select-option value="inactive">未使用</a-select-option>
              <a-select-option value="maintenance">维护中</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="电池电量" name="battery">
            <a-input-number v-model:value="formData.battery" :min="0" :max="100" addonAfter="%" style="width: 100%" />
          </a-form-item>
          <a-form-item label="备注" name="remark">
            <a-textarea v-model:value="formData.remark" placeholder="请输入备注" :rows="4" />
          </a-form-item>
        </a-form>
      </a-modal>
      
      <!-- 详情模态框 -->
      <a-modal
        title="项圈详情"
        :visible="detailModalVisible"
        :footer="null"
        @cancel="handleDetailModalCancel"
      >
        <a-descriptions bordered>
          <a-descriptions-item label="项圈编号" span="3">{{ detailData.collarId }}</a-descriptions-item>
          <a-descriptions-item label="项圈名称" span="3">{{ detailData.name }}</a-descriptions-item>
          <a-descriptions-item label="状态" span="3">
            <a-tag :color="getStatusColor(detailData.status)">
              {{ getStatusText(detailData.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="电池电量" span="3">{{ detailData.battery }}%</a-descriptions-item>
          <a-descriptions-item label="创建时间" span="3">{{ detailData.createdAt }}</a-descriptions-item>
          <a-descriptions-item label="更新时间" span="3">{{ detailData.updatedAt }}</a-descriptions-item>
          <a-descriptions-item label="备注" span="3">{{ detailData.remark || '无' }}</a-descriptions-item>
        </a-descriptions>
      </a-modal>
    </a-card>
  </div>
</template>

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

// 修复 useInjectMenu 错误
if (window && !window.__antd_menu_fixed) {
  window.__antd_menu_fixed = true;
  // 全局错误处理
  const originalError = window.onerror;
  window.onerror = function(message, source, lineno, colno, error) {
    if (message && (message.includes('useInjectMenu') || message.includes('prefixCls'))) {
      // 忽略菜单相关的错误
      return true;
    }
    return originalError ? originalError.apply(this, arguments) : false;
  };
}

export default {
  name: 'SmartCollar',
  components: {
    PlusOutlined
  },
  setup() {
    // 搜索表单
    const searchForm = reactive({
      collarId: '',
      status: undefined
    });

    // 表格数据
    const loading = ref(false);
    const dataSource = ref([]);
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条`
    });

    // 表格列定义
    const columns = [
      {
        title: '项圈编号',
        dataIndex: 'collarId',
        key: 'collarId',
        sorter: true
      },
      {
        title: '项圈名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        filters: [
          { text: '使用中', value: 'active' },
          { text: '未使用', value: 'inactive' },
          { text: '维护中', value: 'maintenance' }
        ]
      },
      {
        title: '电池电量',
        dataIndex: 'battery',
        key: 'battery',
        customRender: ({ text }) => `${text}%`
      },
      {
        title: '创建时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
        sorter: true
      },
      {
        title: '操作',
        key: 'action'
      }
    ];

    // 模态框相关
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const modalTitle = ref('添加项圈');
    const formRef = ref(null);
    const formData = reactive({
      id: null,
      collarId: '',
      name: '',
      status: 'inactive',
      battery: 100,
      remark: ''
    });
    const rules = {
      collarId: [{ required: true, message: '请输入项圈编号', trigger: 'blur' }],
      name: [{ required: true, message: '请输入项圈名称', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    };

    // 详情模态框
    const detailModalVisible = ref(false);
    const detailData = reactive({});

    // 移除模拟数据，使用真实API

    // 获取数据
    const fetchData = async () => {
      loading.value = true;
      try {
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          collarId: searchForm.collarId,
          status: searchForm.status
        };
        const response = await api.government.collars.getList(params);
        if (response.success) {
          dataSource.value = response.data;
          pagination.total = response.total;
        } else {
          console.error('获取智能项圈列表失败:', response.message);
        }
      } catch (error) {
        console.error('获取智能项圈列表失败:', error);
      } finally {
        loading.value = false;
      }
    };

    // 状态相关
    const getStatusColor = (status) => {
      const statusMap = {
        active: 'green',
        inactive: 'blue',
        maintenance: 'orange'
      };
      return statusMap[status] || 'default';
    };

    const getStatusText = (status) => {
      const statusMap = {
        active: '使用中',
        inactive: '未使用',
        maintenance: '维护中'
      };
      return statusMap[status] || '未知';
    };

    // 搜索相关
    const handleSearch = () => {
      pagination.current = 1;
      fetchData();
    };

    const resetSearch = () => {
      searchForm.collarId = '';
      searchForm.status = undefined;
      handleSearch();
    };

    // 表格相关
    const handleTableChange = (pag, filters, sorter) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchData();
    };

    // 模态框相关
    const showAddModal = () => {
      modalTitle.value = '添加项圈';
      formData.id = null;
      formData.collarId = '';
      formData.name = '';
      formData.status = 'inactive';
      formData.battery = 100;
      formData.remark = '';
      modalVisible.value = true;
    };

    const showEditModal = (record) => {
      modalTitle.value = '编辑项圈';
      formData.id = record.id;
      formData.collarId = record.collarId;
      formData.name = record.name;
      formData.status = record.status;
      formData.battery = record.battery;
      formData.remark = record.remark;
      modalVisible.value = true;
    };

    const handleModalOk = async () => {
      formRef.value.validate().then(async () => {
        modalLoading.value = true;
        try {
          const requestData = {
            collarId: formData.collarId,
            name: formData.name,
            status: formData.status,
            battery: formData.battery,
            remark: formData.remark
          };
          
          let response;
          if (formData.id) {
            // 编辑
            response = await api.government.collars.update(formData.id, requestData);
          } else {
            // 添加
            response = await api.government.collars.create(requestData);
          }
          
          if (response.success) {
            modalLoading.value = false;
            modalVisible.value = false;
            fetchData();
            message.success(response.message || '操作成功');
          } else {
            message.error(response.message || '操作失败');
          }
        } catch (error) {
          console.error('操作失败:', error);
          message.error('操作失败，请重试');
        } finally {
          modalLoading.value = false;
        }
      });
    };

    const handleModalCancel = () => {
      modalVisible.value = false;
    };

    // 详情相关
    const showDetailModal = (record) => {
      Object.assign(detailData, record);
      detailModalVisible.value = true;
    };

    const handleDetailModalCancel = () => {
      detailModalVisible.value = false;
    };

    // 删除
    const handleDelete = async (record) => {
      loading.value = true;
      try {
        const response = await api.government.collars.delete(record.id);
        if (response.success) {
          fetchData();
          message.success(response.message || '删除成功');
        } else {
          message.error(response.message || '删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        message.error('删除失败，请重试');
      } finally {
        loading.value = false;
      }
    };

    onMounted(() => {
      fetchData();
    });

    return {
      searchForm,
      loading,
      dataSource,
      pagination,
      columns,
      modalVisible,
      modalLoading,
      modalTitle,
      formRef,
      formData,
      rules,
      detailModalVisible,
      detailData,
      getStatusColor,
      getStatusText,
      handleSearch,
      resetSearch,
      handleTableChange,
      showAddModal,
      showEditModal,
      handleModalOk,
      handleModalCancel,
      showDetailModal,
      handleDetailModalCancel,
      handleDelete
    };
  }
};
</script>

<style scoped>
.smart-collar-container {
  padding: 16px;
}
.danger-text {
  color: #ff4d4f;
}
</style>