<template>
  <div class="p-4">
    <div class="flex justify-between items-center mb-4">
      <h2 class="text-xl font-bold">电表设备列表</h2>
      <el-input
          v-model="searchQuery"
          placeholder="搜索设备..."
          class="w-60"
          clearable
          prefix-icon="Search"
      >
      </el-input>
    </div>

    <el-card shadow="hover" class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span>设备统计</span>
          <el-button type="primary" size="small" @click="reloadData">
            <RefreshCw class="mr-1 w-15px"/>
            刷新
          </el-button>
        </div>
      </template>
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="stat-card bg-blue-50 p-4 rounded-lg">
          <div class="text-blue-500 text-lg font-medium">总设备数</div>
          <div class="text-2xl font-bold mt-2">{{ deviceStatistics.allDevice }}</div>
        </div>
        <div class="stat-card bg-green-50 p-4 rounded-lg">
          <div class="text-green-500 text-lg font-medium">在线设备</div>
          <div class="text-2xl font-bold mt-2">{{ deviceStatistics.onlineDevice }}</div>
        </div>
        <div class="stat-card bg-red-50 p-4 rounded-lg">
          <div class="text-red-500 text-lg font-medium">离线设备</div>
          <div class="text-2xl font-bold mt-2">{{ deviceStatistics.offlineDevice }}</div>
        </div>
      </div>
    </el-card>

    <el-table
        :data="filteredMeters"
        style="width: 100%"
        border
        stripe
        @row-click="handleRowClick"
        row-class-name="cursor-pointer hover:bg-gray-100"
    >
      <el-table-column prop="deviceName" label="设备名称"/>
      <el-table-column prop="tableNumber" label="电表编号" width="180"/>
      <el-table-column label="设备状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'online' ? 'success' : 'danger'" size="small">
            {{ scope.row.status === 'online' ? '在线' : '离线' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="alarmStatus" label="报警状态">
        <template #default="scope">
          <el-tag :type="scope.row.alarmStatus ? 'success' : 'danger'" size="small">
            {{ scope.row.alarmStatus ? '正常' : '报警' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="位置"/>
      <el-table-column prop="remarks" label="备注"/>
      <el-table-column label="操作" >
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click.stop="viewDetails(scope.row.tableNumber)"
          >
            <Eye class="mr-1 w-15px"/>
            查看详情
          </el-button>
          <el-button
              type="success"
              size="small"
              @click.stop="openMutualInductanceDialog(scope.row.id)"
          >
            <Eye class="mr-1 w-15px"/>
            互感值
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex justify-center mt-4">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredMeters.length"
      />
    </div>

    <!-- 互感值对话框 -->
    <el-dialog
        v-model="mutualInductanceDialogVisible"
        title="互感值设置"
        width="30%"
        destroy-on-close
    >
      <el-form :model="mutualInductanceForm" label-width="120px">
        <el-form-item label="互感值">
          <el-input
              v-model="mutualInductanceForm.mutualInductance"
              type="number"
              placeholder="请输入互感值"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="mutualInductanceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMutualInductance" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue';
import {Eye, RefreshCw} from 'lucide-vue-next'
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";

// 模拟电表数据
const meters = ref([]);

const deviceStatistics = ref({
  allDevice: 0,
  onlineDevice: 0,
  offlineDevice: 0
})

// 分页和搜索
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref('');

// 互感值对话框相关
const mutualInductanceDialogVisible = ref(false);
const mutualInductanceForm = ref({
  id: '',
  electricityId: '',
  mutualInductance: ''
});
const saveLoading = ref(false);

// 过滤后的电表列表
const filteredMeters = computed(() => {
  const query = searchQuery.value.toLowerCase().trim();
  if (!query) return meters.value;

  return meters.value.filter(meter =>
      meter.tableNumber.toLowerCase().includes(query) ||
      meter.location.toLowerCase().includes(query)
  );
});

// 定义emit以便向父组件传递事件
const emit = defineEmits(['showDetails']);

// 查看详情
const viewDetails = (tableNumber) => {
  emit('showDetails', tableNumber);
};

// 行点击事件
const handleRowClick = (row) => {
  viewDetails(row.tableNumber);
};

const getList = async () => {
  const arr = [];
  arr.push({
    column: "type",
    type: "eq",
    value: "2"
  })
  const res = await request.get("/base/devices/findByPage", {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      conditionJson: encodeURIComponent(JSON.stringify(arr)),
    }
  })

  if (res.code !== 200) {
    ElMessage.error(res.msg)
    return
  }
  meters.value = res.data.records.map(q => {
    return {
      id: q.id,
      tableNumber: q.deviceNumber,
      location: q.location,
      status: q.onlineStatus === 1 ? 'online' : 'offline',
      alarmStatus: q.alarmStatus === '0',
      deviceName: q.deviceName,
      remarks: q.remarks,
    }
  })
}

const getDeviceStatistics = async () => {
  const arr = [];
  arr.push({
    column: "type",
    type: "eq",
    value: "2"
  })
  const res = await request.get("/base/devices/getAll", {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      conditionJson: encodeURIComponent(JSON.stringify(arr)),
    }
  })

  if (res.code !== 200) {
    ElMessage.error(res.msg)
    return
  }
  deviceStatistics.value = {
    allDevice: res.data.length,
    onlineDevice: res.data.filter(q => q.onlineStatus === 1).length,
    offlineDevice: res.data.filter(q => q.onlineStatus === 0).length
  }
}

// 打开互感值对话框
const openMutualInductanceDialog = async (deviceId) => {
  mutualInductanceForm.value.electricityId = deviceId;
  mutualInductanceForm.value.id = '';
  mutualInductanceForm.value.mutualInductance = '';

  // 获取当前互感值
  await getMutualInductance(deviceId);

  // 显示对话框
  mutualInductanceDialogVisible.value = true;
}

//根据id获取互感值
const getMutualInductance = async (deviceId) => {
  const arr = [];
  arr.push({
    column: "electricity_id",
    type: "eq",
    value: deviceId
  })
  const res = await request.get("/dbMutualInductance/getAll", {
    params: {
      conditionJson: encodeURIComponent(JSON.stringify(arr)),
    }
  })

  if (res.code !== 200) {
    ElMessage.error(res.msg)
    return
  }

  // 如果有数据，填充到表单中
  if (res.data && res.data.length > 0) {
    mutualInductanceForm.value.id = res.data[0].id;
    mutualInductanceForm.value.mutualInductance = res.data[0].mutualInductance;
  }
}

// 保存互感值
const saveMutualInductance = async () => {
  if (!mutualInductanceForm.value.mutualInductance) {
    ElMessage.warning('请输入互感值');
    return;
  }
  if(Number.isInteger(mutualInductanceForm.value.mutualInductance)){
    ElMessage.warning('请输入数字');
    return;
  }

  saveLoading.value = true;
  try {
    const res = await request.post("/dbMutualInductance/updateOrInsert", {
      electricityId: mutualInductanceForm.value.electricityId,
      id: mutualInductanceForm.value.id,
      mutualInductance: mutualInductanceForm.value.mutualInductance,
    });

    if (res.code === 200) {
      ElMessage.success('互感值保存成功');
      mutualInductanceDialogVisible.value = false;
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (error) {
    ElMessage.error('保存失败：' + error.message);
  } finally {
    saveLoading.value = false;
  }
}

const reloadData = () => {
  getList();
  getDeviceStatistics();
}

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