<template>
  <div class="government-page">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <a-page-header title="政府监管" sub-title="检查记录和质量追溯">
        <template #extra>
          <a-button type="primary" @click="showAddModal('inspection')">
            <AuditOutlined /> 新增检查
          </a-button>
          <a-button @click="showAddModal('trace')">
            <SearchOutlined /> 质量追溯
          </a-button>
        </template>
      </a-page-header>
    </div>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-cards">
      <a-col :span="6">
        <a-card>
          <a-statistic title="总检查次数" :value="stats.totalInspections" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="合规率" :value="stats.complianceRate" suffix="%" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="追溯记录" :value="stats.totalTraces" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="本月检查" :value="stats.monthlyInspections" />
        </a-card>
      </a-col>
    </a-row>

    <!-- 标签页 -->
    <a-tabs v-model:activeKey="activeTab" class="government-tabs">
      <a-tab-pane key="inspections" tab="检查记录">
        <!-- 检查搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="inspectionSearchForm">
            <a-form-item label="牧场名称">
              <a-input v-model:value="inspectionSearchForm.farmName" placeholder="请输入牧场名称" />
            </a-form-item>
            <a-form-item label="检查类型">
              <a-select v-model:value="inspectionSearchForm.inspectionType" placeholder="请选择检查类型" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="safety">安全检查</a-select-option>
                <a-select-option value="health">卫生检查</a-select-option>
                <a-select-option value="environment">环保检查</a-select-option>
                <a-select-option value="quality">质量检查</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="检查结果">
              <a-select v-model:value="inspectionSearchForm.result" placeholder="请选择结果" style="width: 120px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="passed">通过</a-select-option>
                <a-select-option value="failed">不通过</a-select-option>
                <a-select-option value="conditional">有条件通过</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchInspections">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetInspectionSearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 检查列表 -->
        <a-card>
          <a-table 
            :columns="inspectionColumns" 
            :data-source="inspections" 
            :loading="inspectionLoading"
            :pagination="inspectionPagination"
            @change="handleInspectionTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'inspection_type'">
                <a-tag color="blue">
                  {{ getInspectionTypeText(record.inspection_type) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'result'">
                <a-tag :color="getInspectionResultColor(record.result)">
                  {{ getInspectionResultText(record.result) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewInspectionDetail(record)">
                    详情
                  </a-button>
                  <a-button 
                    v-if="record.result === 'failed'" 
                    size="small" 
                    type="primary"
                    @click="createRectification(record)"
                  >
                    整改通知
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="traces" tab="质量追溯">
        <!-- 追溯搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="traceSearchForm">
            <a-form-item label="追溯编号">
              <a-input v-model:value="traceSearchForm.traceId" placeholder="请输入追溯编号" />
            </a-form-item>
            <a-form-item label="牛只耳标">
              <a-input v-model:value="traceSearchForm.earTag" placeholder="请输入牛只耳标" />
            </a-form-item>
            <a-form-item label="追溯类型">
              <a-select v-model:value="traceSearchForm.traceType" placeholder="请选择类型" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="origin">源头追溯</a-select-option>
                <a-select-option value="feed">饵料追溯</a-select-option>
                <a-select-option value="medicine">药物追溯</a-select-option>
                <a-select-option value="transport">运输追溯</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchTraces">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetTraceSearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 追溯列表 -->
        <a-card>
          <a-table 
            :columns="traceColumns" 
            :data-source="traces" 
            :loading="traceLoading"
            :pagination="tracePagination"
            @change="handleTraceTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'trace_type'">
                <a-tag color="green">
                  {{ getTraceTypeText(record.trace_type) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewTraceDetail(record)">
                    详情
                  </a-button>
                  <a-button size="small" @click="viewTraceChain(record)">
                    追溯链
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="policies" tab="政策法规">
        <!-- 政策搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="policySearchForm">
            <a-form-item label="政策标题">
              <a-input v-model:value="policySearchForm.title" placeholder="请输入政策标题" />
            </a-form-item>
            <a-form-item label="政策类型">
              <a-select v-model:value="policySearchForm.policyType" placeholder="请选择类型" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="industry">行业政策</a-select-option>
                <a-select-option value="subsidy">补贴政策</a-select-option>
                <a-select-option value="regulation">监管政策</a-select-option>
                <a-select-option value="environment">环保政策</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchPolicies">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetPolicySearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 政策列表 -->
        <a-card>
          <a-table 
            :columns="policyColumns" 
            :data-source="policies" 
            :loading="policyLoading"
            :pagination="policyPagination"
            @change="handlePolicyTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'policy_type'">
                <a-tag color="purple">
                  {{ getPolicyTypeText(record.policy_type) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewPolicyDetail(record)">
                    查看
                  </a-button>
                  <a-button size="small" @click="downloadPolicy(record)">
                    下载
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { governmentAPI } from '@/services/api.js';
import { 
  AuditOutlined, 
  SearchOutlined 
} from '@ant-design/icons-vue';

export default {
  name: 'Government',
  components: {
    AuditOutlined,
    SearchOutlined
  },
  setup() {
    const activeTab = ref('inspections');
    const inspectionLoading = ref(false);
    const traceLoading = ref(false);
    const policyLoading = ref(false);
    
    // 统计数据
    const stats = reactive({
      totalInspections: 856,
      complianceRate: 92.5,
      totalTraces: 1245,
      monthlyInspections: 128
    });

    // 检查数据
    const inspections = ref([]);
    const inspectionSearchForm = reactive({
      farmName: '',
      inspectionType: '',
      result: ''
    });
    const inspectionPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 追溯数据
    const traces = ref([]);
    const traceSearchForm = reactive({
      traceId: '',
      earTag: '',
      traceType: ''
    });
    const tracePagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 政策数据
    const policies = ref([]);
    const policySearchForm = reactive({
      title: '',
      policyType: ''
    });
    const policyPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 检查表格列
    const inspectionColumns = [
      { title: '检查编号', dataIndex: 'inspection_id', key: 'inspection_id', width: 120 },
      { title: '牧场名称', dataIndex: 'farm_name', key: 'farm_name' },
      { title: '检查类型', dataIndex: 'inspection_type', key: 'inspection_type' },
      { title: '检查人员', dataIndex: 'inspector_name', key: 'inspector_name' },
      { title: '检查结果', dataIndex: 'result', key: 'result' },
      { title: '检查时间', dataIndex: 'inspection_date', key: 'inspection_date' },
      { title: '操作', key: 'action', width: 150 }
    ];

    // 追溯表格列
    const traceColumns = [
      { title: '追溯编号', dataIndex: 'trace_id', key: 'trace_id', width: 150 },
      { title: '牛只耳标', dataIndex: 'ear_tag', key: 'ear_tag' },
      { title: '追溯类型', dataIndex: 'trace_type', key: 'trace_type' },
      { title: '纳入时间', dataIndex: 'record_date', key: 'record_date' },
      { title: '操作员', dataIndex: 'operator_name', key: 'operator_name' },
      { title: '操作', key: 'action', width: 150 }
    ];

    // 政策表格列
    const policyColumns = [
      { title: '政策标题', dataIndex: 'title', key: 'title' },
      { title: '政策类型', dataIndex: 'policy_type', key: 'policy_type' },
      { title: '发布时间', dataIndex: 'publish_date', key: 'publish_date' },
      { title: '生效时间', dataIndex: 'effective_date', key: 'effective_date' },
      { title: '操作', key: 'action', width: 150 }
    ];

    // 加载检查数据
    const loadInspections = async () => {
      inspectionLoading.value = true;
      try {
        const params = {
          page: inspectionPagination.current,
          limit: inspectionPagination.pageSize,
          ...inspectionSearchForm
        };
        const response = await governmentAPI.getInspections(params);
        if (response.success) {
          inspections.value = response.data.inspections || [];
          inspectionPagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取检查列表失败:', error);
        message.error('获取检查列表失败');
      } finally {
        inspectionLoading.value = false;
      }
    };

    // 加载追溯数据
    const loadTraces = async () => {
      traceLoading.value = true;
      try {
        const params = {
          page: tracePagination.current,
          limit: tracePagination.pageSize,
          ...traceSearchForm
        };
        const response = await governmentAPI.getTraces(params);
        if (response.success) {
          traces.value = response.data.traces || [];
          tracePagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取追溯列表失败:', error);
        message.error('获取追溯列表失败');
      } finally {
        traceLoading.value = false;
      }
    };

    // 加载政策数据
    const loadPolicies = async () => {
      policyLoading.value = true;
      try {
        const params = {
          page: policyPagination.current,
          limit: policyPagination.pageSize,
          ...policySearchForm
        };
        const response = await governmentAPI.getPolicies(params);
        if (response.success) {
          policies.value = response.data.policies || [];
          policyPagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取政策列表失败:', error);
        message.error('获取政策列表失败');
      } finally {
        policyLoading.value = false;
      }
    };

    // 检查类型文本
    const getInspectionTypeText = (type) => {
      const texts = {
        'safety': '安全检查',
        'health': '卫生检查',
        'environment': '环保检查',
        'quality': '质量检查'
      };
      return texts[type] || type;
    };

    // 检查结果颜色
    const getInspectionResultColor = (result) => {
      const colors = {
        'passed': 'green',
        'failed': 'red',
        'conditional': 'orange'
      };
      return colors[result] || 'default';
    };

    // 检查结果文本
    const getInspectionResultText = (result) => {
      const texts = {
        'passed': '通过',
        'failed': '不通过',
        'conditional': '有条件通过'
      };
      return texts[result] || result;
    };

    // 追溯类型文本
    const getTraceTypeText = (type) => {
      const texts = {
        'origin': '源头追溯',
        'feed': '饵料追溯',
        'medicine': '药物追溯',
        'transport': '运输追溯'
      };
      return texts[type] || type;
    };

    // 政策类型文本
    const getPolicyTypeText = (type) => {
      const texts = {
        'industry': '行业政策',
        'subsidy': '补贴政策',
        'regulation': '监管政策',
        'environment': '环保政策'
      };
      return texts[type] || type;
    };

    // 搜索检查
    const searchInspections = () => {
      inspectionPagination.current = 1;
      loadInspections();
    };

    // 重置检查搜索
    const resetInspectionSearch = () => {
      Object.assign(inspectionSearchForm, {
        farmName: '',
        inspectionType: '',
        result: ''
      });
      searchInspections();
    };

    // 搜索追溯
    const searchTraces = () => {
      tracePagination.current = 1;
      loadTraces();
    };

    // 重置追溯搜索
    const resetTraceSearch = () => {
      Object.assign(traceSearchForm, {
        traceId: '',
        earTag: '',
        traceType: ''
      });
      searchTraces();
    };

    // 搜索政策
    const searchPolicies = () => {
      policyPagination.current = 1;
      loadPolicies();
    };

    // 重置政策搜索
    const resetPolicySearch = () => {
      Object.assign(policySearchForm, {
        title: '',
        policyType: ''
      });
      searchPolicies();
    };

    // 表格变化处理
    const handleInspectionTableChange = (pagination) => {
      inspectionPagination.current = pagination.current;
      inspectionPagination.pageSize = pagination.pageSize;
      loadInspections();
    };

    const handleTraceTableChange = (pagination) => {
      tracePagination.current = pagination.current;
      tracePagination.pageSize = pagination.pageSize;
      loadTraces();
    };

    const handlePolicyTableChange = (pagination) => {
      policyPagination.current = pagination.current;
      policyPagination.pageSize = pagination.pageSize;
      loadPolicies();
    };

    // 显示添加模态框
    const showAddModal = (type) => {
      message.info(`添加${type === 'inspection' ? '检查' : '追溯'}功能开发中`);
    };

    // 查看详情
    const viewInspectionDetail = (record) => {
      message.info(`查看检查详情: ${record.inspection_id}`);
    };

    const viewTraceDetail = (record) => {
      message.info(`查看追溯详情: ${record.trace_id}`);
    };

    const viewPolicyDetail = (record) => {
      message.info(`查看政策详情: ${record.title}`);
    };

    // 其他操作
    const createRectification = (record) => {
      message.info(`创建整改通知: ${record.inspection_id}`);
    };

    const viewTraceChain = (record) => {
      message.info(`查看追溯链: ${record.trace_id}`);
    };

    const downloadPolicy = (record) => {
      message.info(`下载政策文件: ${record.title}`);
    };

    onMounted(() => {
      loadInspections();
      loadTraces();
      loadPolicies();
    });

    return {
      activeTab,
      stats,
      inspections,
      inspectionLoading,
      inspectionSearchForm,
      inspectionPagination,
      inspectionColumns,
      traces,
      traceLoading,
      traceSearchForm,
      tracePagination,
      traceColumns,
      policies,
      policyLoading,
      policySearchForm,
      policyPagination,
      policyColumns,
      loadInspections,
      loadTraces,
      loadPolicies,
      getInspectionTypeText,
      getInspectionResultColor,
      getInspectionResultText,
      getTraceTypeText,
      getPolicyTypeText,
      searchInspections,
      resetInspectionSearch,
      searchTraces,
      resetTraceSearch,
      searchPolicies,
      resetPolicySearch,
      handleInspectionTableChange,
      handleTraceTableChange,
      handlePolicyTableChange,
      showAddModal,
      viewInspectionDetail,
      viewTraceDetail,
      viewPolicyDetail,
      createRectification,
      viewTraceChain,
      downloadPolicy
    };
  }
};
</script>

<style scoped>
.government-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  margin-bottom: 16px;
  border-radius: 8px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stats-cards .ant-card {
  text-align: center;
}

.government-tabs {
  background: white;
  padding: 24px;
  border-radius: 8px;
}

.search-card {
  margin-bottom: 16px;
}

.search-card .ant-form {
  margin-bottom: 0;
}
</style>