<template>
  <div class="page-container dust-container">
    <div class="header">
      <div class="item-box">
        <img src="@/assets/icons/warn.png" alt="dust" />
        <div class="title">
          <span>泄漏告警(条)</span>
          <div class="content">{{dusterLeakNum}}</div>
        </div>
      </div>

      <div class="item-box">
        <img src="@/assets/icons/health.png" alt="dust" />
        <div class="title">
          <span>综合健康度</span>
          <div class="content">{{healthPercent}}</div>
        </div>
      </div>

      <div class="item-box">
        <img src="@/assets/icons/close.png" alt="dust" />
        <div class="title">
          <span>闭环(条)</span>
          <div class="content">{{closeLoopNum}}</div>
        </div>
      </div>
    </div>

    <div class="content-box">
      <div class="search">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="工序">
            <el-select
              v-model="formInline.region"
              placeholder="请选择工序"
              style="width: 120px"
              clearable
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="除尘器名称">
            <el-input
              v-model="formInline.deviceName"
              placeholder="请输入除尘器名称"
              style="width: 240px"
              clearable
            />
          </el-form-item>

          <el-form-item>
            <el-button type="default" class="default-btn" @click="onSubmit"
              >重置</el-button
            >
            <el-button type="primary" class="search-btn" @click="onSubmit"
              >查询</el-button
            >
            <el-button type="success" class="add-btn" @click="handleAddDustCollector"
              >新增</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="table-box">
        <common-table
          :data="tableData"
          :columns="tableColumns"
          :default-page-size="10"
          @pagination-change="handlePaginationChange"
          :pagination-texts="{
            total: '共',
            sizeChange: '条/页',
            prev: '前一页',
            next: '后一页',
            jumper: '跳至',
          }"
        >
          <template #index="{ $index }">
            {{ getIndex($index) }}
          </template>
          <template #healthScore="{ row }">
            <span class="health-score" @click="handleHealthScoreClick(row)">{{
              row.healthScore
            }}</span>
          </template>
          <template #health2Score="{ row }">
            <span class="health-score" @click="handleHealth2ScoreClick(row)">{{
              row.health2Score
            }}</span>
          </template>
          <template #status="{ row }">
            <div class="status-matrix">
              <div
                v-for="(row, rowIndex) in row.status"
                :key="rowIndex"
                class="matrix-row"
              >
                <div
                  v-for="(status, colIndex) in row"
                  :key="colIndex"
                  class="status-dot"
                  :class="{
                    'status-normal': status.status === 1,
                    'status-warning': status.status === 2,
                    'status-error': status.status === 3,
                  }"
                ></div>
              </div>
            </div>
          </template>

          <template #alarmCount="{ row }">
            <span :style="{ color: getHealthScoreColor(row.alarmCount) }">
              {{ row.alarmCount }}
            </span>
          </template>

          <template #operation="{ row }">
            <span class="view-btn" @click="handleView(row)">详情</span>
            <span class="edit-btn" @click="handleEdit(row)">编辑</span>
          </template>
        </common-table>
      </div>
    </div>

    <!-- 使用新的仓室数量设置弹窗组件 -->
    <RoomSettingDialog
      v-model="roomSettingVisible"
      :total-rooms="currentEditingRow?.healthScore || 0"
      :initial-distribution="currentEditingRow?.status || []"
      @confirm="handleRoomSettingConfirm"
    />

    <!-- 使用新的电磁阀数量设置弹窗组件 -->
    <ValveSettingDialog
      v-model="valveSettingVisible"
      :total-valves="valveForm.total"
      :status-data="currentEditingRow?.status || []"
      @confirm="handleValveSettingConfirm"
    />

    <!-- 使用新增除尘器弹窗组件 -->
    <AddDustCollectorDialog
      v-model="isAddDustCollectorVisible"
      @save="handleSaveDustCollector"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from "vue";
import { getDusterLeakNum, getHealthPercent, getCloseLoopNum } from "@/request/api/dustOverview";
import CommonTable from "@/components/commonTable/index.vue";
import RoomSettingDialog from "./components/roomSettingDialog.vue";
import ValveSettingDialog from "./components/valveSettingDialog.vue";
import AddDustCollectorDialog from "./components/addDustCollectorDialog.vue";

const formInline = ref({
  deviceName: "",
  region: 1,
});

const currentPage = ref(1);
const pageSize = ref(10);
const dusterLeakNum = ref(0);
const healthPercent = ref('100%');
const closeLoopNum = ref(0);

const options = ref([
  {
    value: 1,
    label: "转炉",
  },
  {
    value: 2,
    label: "炼铁",
  },
]);

const tableColumns = ref([
  {
    prop: "index",
    label: "序号",
    width: "5%",
  },
  {
    prop: "deviceName",
    label: "除尘器名称",
    width: "12%",
  },
  {
    prop: "deviceNo",
    label: "除尘器编号",
    width: "12%",
  },
  {
    prop: "process",
    label: "所属工序",
    width: "5%",
  },
  {
    prop: "healthScore",
    label: "仓室数量",
    width: "8%",
  },
  {
    prop: "health2Score",
    label: "电磁阀数量",
    width: "8%",
  },
  {
    prop: "status",
    label: "仓室健康状态",
    width: "25%",
  },
  {
    prop: "alarmCount",
    label: "健康度",
    width: "5%",
  },
  {
    prop: "lastAlarmTime",
    label: "合理压差范围",
    width: "10%",
  },
  {
    prop: "operation",
    label: "操作",
    width: "10%",
  },
]);

const tableData = [
  {
    deviceName: "1#除尘器",
    deviceNo: "1234567890",
    process: "转炉",
    healthScore: 10,
    health2Score: 11,
    status: [
      [
        {
          index: 1,
          status: 1,
          count: 1,
        },
        {
          index: 2,
          status: 2,
          count: 2,
        },
        {
          index: 3,
          status: 1,
          count: 1,
        },
        {
          index: 4,
          status: 1,
          count: 1,
        },
        {
          index: 5,
          status: 3,
          count: 1,
        },
      ],
      [
        {
          index: 6,
          status: 1,
          count: 1,
        },
        {
          index: 7,
          status: 1,
          count: 1,
        },
        {
          index: 8,
          status: 1,
          count: 1,
        },
        {
          index: 9,
          status: 1,
          count: 1,
        },
        {
          index: 10,
          status: 2,
          count: 1,
        },
      ],
    ],
    alarmCount: "98%",
    lastAlarmTime: "-",
    location: "一号转炉东侧",
  },
  {
    deviceName: "2#除尘器",
    deviceNo: "1234567890",
    process: "转炉",
    healthScore: 10,
    health2Score: 11,
    status: [
      [
        {
          index: 1,
          status: 1,
          count: 1,
        },
        {
          index: 2,
          status: 2,
          count: 2,
        },
        {
          index: 3,
          status: 1,
          count: 1,
        },
        {
          index: 4,
          status: 1,
          count: 1,
        },
        {
          index: 5,
          status: 3,
          count: 1,
        },
      ],
      [
        {
          index: 6,
          status: 1,
          count: 1,
        },
        {
          index: 7,
          status: 1,
          count: 1,
        },
        {
          index: 8,
          status: 1,
          count: 1,
        },
        {
          index: 9,
          status: 1,
          count: 1,
        },
        {
          index: 10,
          status: 2,
          count: 1,
        },
      ],
    ],
    alarmCount: "45%",
    lastAlarmTime: "100～3000",
    location: "二号转炉西侧",
  },
  {
    deviceName: "3#除尘器",
    deviceNo: "1234567890",
    process: "炼铁",
    healthScore: 12,
    health2Score: 13,
    status: [
      [
        {
          index: 1,
          status: 1,
          count: 1,
        },
        {
          index: 2,
          status: 2,
          count: 2,
        },
        {
          index: 3,
          status: 1,
          count: 1,
        },
        {
          index: 4,
          status: 1,
          count: 1,
        },
        {
          index: 5,
          status: 3,
          count: 1,
        },
      ],
      [
        {
          index: 6,
          status: 1,
          count: 1,
        },
        {
          index: 7,
          status: 1,
          count: 1,
        },
        {
          index: 8,
          status: 1,
          count: 1,
        },
        {
          index: 9,
          status: 1,
          count: 1,
        },
        {
          index: 10,
          status: 2,
          count: 1,
        },
        {
          index: 11,
          status: 1,
          count: 1,
        },
        {
          index: 12,
          status: 2,
          count: 1,
        },
      ],
    ],
    alarmCount: "78%",
    lastAlarmTime: "100～3000",
    location: "炼铁区域北侧",
  },
];

const getStatusType = (status) => {
  const statusMap = {
    正常运行: "success",
    轻微异常: "warning",
    故障: "danger",
  };
  return statusMap[status] || "info";
};

const getHealthScoreColor = (score) => {
  const value = parseInt(score);
  if (value >= 90) return "#67C23A";
  if (value >= 70) return "#E6A23C";
  return "#F56C6C";
};

const getIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index + 1;
};

const handleView = (row) => {
  console.log("查看详情", row);
};

const handleEdit = (row) => {
  console.log("编辑", row);
};

const handlePaginationChange = (pagination) => {
  currentPage.value = pagination.currentPage;
  pageSize.value = pagination.pageSize;
  console.log("分页变化", pagination);
};

const onSubmit = () => {
  console.log("submit!", formInline.value);
};

// 仓室设置相关
const roomSettingVisible = ref(false);
const currentEditingRow = ref(null);

// 电磁阀设置相关
const valveSettingVisible = ref(false);
const valveForm = ref({
  total: 120,
});

// 新增除尘器相关
const isAddDustCollectorVisible = ref(false);

// 修改打开弹窗的处理函数
const handleHealthScoreClick = (row) => {
  currentEditingRow.value = JSON.parse(JSON.stringify(row));
  roomSettingVisible.value = true;
};

// 确认设置
const handleRoomSettingConfirm = (distributionData) => {
  if (currentEditingRow.value) {
    // 创建新的状态矩阵
    const newStatus = [];
    let chamberIndex = 1;

    // 根据分布数据重新生成状态矩阵
    distributionData.forEach((rowData, rowIndex) => {
      const rowArray = [];
      
      // 获取当前行中应该有多少个仓室
      const rowCount = rowData.count;
      
      for (let i = 0; i < rowCount; i++) {
        // 尝试获取原始数据或创建新数据
        let existingRoom = null;
        
        if (currentEditingRow.value.status[rowIndex] && 
            currentEditingRow.value.status[rowIndex][i]) {
          existingRoom = {...currentEditingRow.value.status[rowIndex][i]};
        }
        
        rowArray.push(existingRoom || {
          index: chamberIndex,
          status: 1, // 默认状态正常
          count: 1  // 默认阀门数量
        });
        
        chamberIndex++;
      }
      
      newStatus.push(rowArray);
    });
    
    // 更新行的状态矩阵和总数
    currentEditingRow.value.status = newStatus;
    currentEditingRow.value.healthScore = chamberIndex - 1; // 总仓室数
  }
};

// 点击电磁阀数量时打开弹窗
const handleHealth2ScoreClick = (row) => {
  // 创建一个扁平化的状态数组用于电磁阀设置
  currentEditingRow.value = JSON.parse(JSON.stringify(row));
  const flattenedStatus = row.status.flat().map(item => ({...item}));
  currentEditingRow.value.status = flattenedStatus;
  valveForm.value.total = row.health2Score;
  valveSettingVisible.value = true;
};

// 确认电磁阀设置
const handleValveSettingConfirm = (updatedStatusData) => {
  if (currentEditingRow.value && updatedStatusData) {
    // 更新总数
    const originalRow = tableData.find(item => item === currentEditingRow.value);
    if (originalRow) {
      originalRow.health2Score = valveForm.value.total;
      
      // 更新各个仓室的电磁阀数量
      const flatStatusMap = new Map();
      updatedStatusData.forEach(cell => {
        flatStatusMap.set(cell.index, cell.count);
      });
      
      // 将更新后的数量应用到原始的2D结构中
      originalRow.status.forEach(row => {
        row.forEach(chamber => {
          if (flatStatusMap.has(chamber.index)) {
            chamber.count = flatStatusMap.get(chamber.index);
          }
        });
      });
    }
  }
  valveSettingVisible.value = false;
};

// 打开新增除尘器弹窗
const handleAddDustCollector = () => {
  isAddDustCollectorVisible.value = true;
};

// 保存新增除尘器
const handleSaveDustCollector = (data) => {
  console.log("保存新增除尘器数据:", data);
  // 添加到表格数据中
  tableData.push({
    ...data,
    alarmCount: "100%", // 设置默认健康度
    location: "", // 可以根据需要设置默认位置
  });
  
  // 这里可以调用API进行保存
  // await api.addDustCollector(data);
  
  // 关闭弹窗
  isAddDustCollectorVisible.value = false;
};



const IdusterLeakNum = () => {
  getDusterLeakNum().then(res => {
    dusterLeakNum.value = res.data || 0;
  })
}

const IhealthPercent = () => {
  getHealthPercent().then(res => {
    healthPercent.value = res.data || '100%';
  })
}

const IcloseLoopNum = () => {
  getCloseLoopNum().then(res => {
    closeLoopNum.value = res.data || 0;
  })
}

onMounted(async () => {
  IdusterLeakNum();
  IhealthPercent();
  IcloseLoopNum();
});

onBeforeUnmount(() => {});
</script>

<style lang="scss" scoped>
.dust-container {
  width: 100%;
  height: calc(100% - 14px);
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    gap: 16px;

    .item-box {
      flex: 1;
      max-width: 420px;
      height: 130px;
      background-color: #fff;
      border: 1.5px solid #e8e8e8;
      border-radius: 6px;
      box-shadow: 0px 1.33px 16px 0px rgba(83, 100, 170, 0.1);
      padding: 16px;
      box-sizing: border-box;
      display: flex;
      align-items: center;

      img {
        width: 72px;
        height: 72px;
        margin-right: 20px;
      }

      .title {
        width: 100%;

        span {
          color: rgba(36, 48, 71, 0.75);
          line-height: 22px;
          font-size: 14px;
          font-weight: 500;
        }
      }

      .content {
        color: #273849;
        line-height: 30px;
        font-size: 42px;
        font-weight: 600;
        margin-top: 10px;
      }
    }
  }
  .content-box {
    margin-top: 24px;
    .search {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }
    .table-box {
      width: 100%;
      height: calc(100vh - 400px);
    }
  }

  .default-btn {
    width: 85px;
  }
  .search-btn {
    width: 85px;
    background: #2182a0;
    border: 1px solid #2182a0;
  }
  .add-btn {
    width: 85px;
  }

  .health-score {
    color: #027ffc;
    cursor: pointer;
    display: block;
    width: 100%;
  }

  .status-matrix {
    width: fit-content;
    display: flex;
    padding: 10px;
    box-sizing: border-box;
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #ffffff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

    .matrix-row {
      display: flex;
      gap: 6px;
      justify-content: flex-start;
    }

    .status-dot {
      width: 14px;
      height: 14px;
      border-radius: 50%;
      &:hover {
        cursor: pointer;
        transform: scale(1.2);
      }
    }

    .status-normal {
      background-color: #67c23a; // 绿色
    }

    .status-warning {
      background-color: #e6a23c; // 橙色
    }

    .status-error {
      background-color: #f56c6c; // 红色
    }
  }

  .view-btn {
    margin-right: 8px;
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 12px;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  .distribution-table {
    margin-top: 20px;
    border-top: 1px solid #ebeef5;
    padding-top: 20px;
  }

  .table-title {
    font-size: 14px;
    color: #2182a0;
    margin-bottom: 16px;
    font-weight: 500;
  }

  :deep(.el-input-number.el-input-number--small) {
    width: 130px;
  }
  :deep(.distribution-table .el-table--border .el-table__cell) {
    border-right: 1px solid #ebeef5 !important;
  }

  .valve-setting {
    .setting-row {
      display: flex;
      align-items: center;
      gap: 20px;
      margin-bottom: 20px;

      .input-group {
        display: flex;
        align-items: center;
        gap: 8px;

        span {
          white-space: nowrap;
          color: #606266;
        }
      }
    }
  }

  .valve-distribution-grid {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;

    .valve-row {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }

    .valve-cell {
      width: 41px;
      background: white;
      padding: 4px;
      border-radius: 4px;
      text-align: center;
      border: 1px solid #dcdfe6;

      .cell-index {
        font-size: 12px;
        color: #909399;
        margin-bottom: 8px;
      }

      .cell-value {
        :deep(.el-input-number) {
          width: 100px;
        }
      }
    }
  }

  .readonly-value {
    font-size: 14px;
    color: #606266;
    line-height: 32px;
    padding: 0 12px;
  }

  .distribution-warning {
    display: inline-block;
    font-size: 13px;
    margin-left: 12px;
    padding: 2px 8px;
    border-radius: 4px;

    &.warning-more {
      color: #e6a23c;
      background-color: #fdf6ec;
    }

    &.warning-less {
      color: #f56c6c;
      background-color: #fef0f0;
    }
  }
}
</style>
