<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="统计区间" prop="dateRange">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="onDateChange"
                clearable />
            </el-form-item>
<!--            <el-form-item label="设备模型" prop="deviceModeId">-->
<!--              <el-input v-model="queryParams.deviceModeId" placeholder="输入设备模型ID" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
            <el-form-item label="设备编号" prop="machineCode">
              <el-input v-model="queryParams.machineCode" placeholder="输入设备编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="故障类型" prop="faultType">
              <el-select v-model="queryParams.faultType" placeholder="选择故障类型" clearable>
                <el-option label="外部故障" value="1" />
                <el-option label="内部故障" value="2" />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :search="true" @queryTable="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" :data="list">
        <el-table-column label="统计周期" prop="periodLabel" min-width="140" />
        <el-table-column label="设备类型" prop="deviceType" min-width="100" />
        <el-table-column label="设备编号" prop="machineCode" min-width="120" />
        <el-table-column label="故障类型" prop="faultType" min-width="100" >
<!--          <template #default="scope">-->
<!--            <dict-tag :options="activity_fault_type" :value="scope.row.faultType"/>-->
<!--          </template>-->
          <template #default="scope">
            <span>{{ formatFaultType(scope.row.faultType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="故障次数" prop="faultCount" min-width="90" align="right" />
        <el-table-column label="总停机时长（小时）" prop="totalDowntimeHours" min-width="150" align="right" />
        <el-table-column label="MTBF（小时）" prop="mtbfHours" min-width="120" align="right" />
        <el-table-column label="MTTR（分钟）" prop="mttrMinutes" min-width="120" align="right" />
        <el-table-column label="产量损失（件）" prop="outputLoss" min-width="130" align="right" />
        <el-table-column label="工单延误数" prop="delayCount" min-width="110" align="right" />
        <el-table-column label="高频故障原因" prop="topCause" min-width="200" show-overflow-tooltip />
<!--        <el-table-column label="改善措施" prop="topResolution" min-width="200" show-overflow-tooltip />
        <el-table-column label="措施实施时间" prop="topResolutionTime" min-width="140">
          <template #default="scope">
            <span>{{ formatDate(scope.row.topResolutionTime) }}</span>
          </template>
        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0"
                  :total="total"
                  v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize"
                  @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup lang="ts" name="FaultTraceReport">
import { listFaultTrace, exportFaultTrace} from '@/api/dms/report/';
import { FaultTraceQuery, FaultTraceVO } from '@/api/dms/report/types';
import { useDict } from '@/utils/dict';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { activity_fault_type } = useDict('activity_fault_type');

const showSearch = ref(true);
const loading = ref(false);
const list = ref<FaultTraceVO[]>([]);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const queryParams = reactive<FaultTraceQuery>({
  pageNum: 1,
  pageSize: 10,
  startDate: undefined,
  endDate: undefined,
  deviceModeId: undefined,
  machineCode: undefined,
  faultType: undefined
});

const dateRange = ref<[string, string] | undefined>(undefined);

const onDateChange = (val?: [string, string]) => {
  if (val && val.length === 2) {
    queryParams.startDate = val[0];
    // 结束时间用 < endDate，前端+1天可选；这里直接传 ISO 日期，后端用 < endDate 处理
    queryParams.endDate = val[1];
  } else {
    queryParams.startDate = undefined;
    queryParams.endDate = undefined;
  }
};

const formatDate = (val?: string | null) => {
  if (!val) return '';
  return val.substring(0, 10);
};

// 调试函数：打印faultType值和字典对应关系
const debugFaultType = (faultType: any) => {
  console.log('=== 前端字典调试 ===');
  console.log('faultType原始值:', JSON.stringify(faultType), '类型:', typeof faultType);
  console.log('字典选项:', activity_fault_type.value);

  // 查找匹配的字典项
  const matchedDict = activity_fault_type.value.find(item => item.value === faultType);
  console.log('匹配的字典项:', matchedDict);

  return ''; // 不在页面显示调试信息
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listFaultTrace(queryParams);
    list.value = res.rows ?? [];
    total.value = res.total ?? 0;

        // 调试：打印接收到的数据
        console.log('=== 前端接收数据调试 ===');
    if (list.value.length > 0) {
      console.log('第一条记录 faultType:', JSON.stringify(list.value[0].faultType));
      console.log('第一条记录完整数据:', list.value[0]);
    }


  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = undefined;
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.startDate = undefined;
  queryParams.endDate = undefined;
  queryParams.deviceModeId = undefined;
  queryParams.machineCode = undefined;
  queryParams.faultType = undefined;
  getList();
};

// 格式化故障类型显示
const formatFaultType = (faultType: any) => {
  switch (faultType) {
    case 1:
    case '1':
      return '外部故障';
    case 2:
    case '2':
      return '内部故障';
    default:
      return '其他';
  }
};


const handleExport = async () => {
  proxy?.download('/dms/report/faultTrace/export', { ...queryParams }, `fault_trace_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getList();
});
</script>
