<template>
  <div class="page-container dust-container">
    <div class="header">
      <div class="item-box crusor-click" @click="handleDusterLeakNumClick">
        <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 crusor-click" @click="handleCloseLoopNumClick">
        <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: 180px"
              filterable
              :filter-method="filterProductionLine"
            >
              <el-option key="all" label="全部" value="all" />
              <el-option
                v-for="item in productionLineFiltered"
                :key="item.productionLineId"
                :label="item.productionLineName"
                :value="item.productionLineId"
              />
            </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="refreshData"
              >重置</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"
          :total="total"
          :pagination-texts="{
            total: '共',
            sizeChange: '条/页',
            prev: '前一页',
            next: '后一页',
            jumper: '跳至',
          }"
        >
          <template #index="{ $index }">
            {{ getIndex($index) }}
          </template>
          <template #compartNum="{ row }">
            <span class="health-score" @click="handleHealthScoreClick(row)">{{
              row.compartNum
            }}</span>
          </template>
          <template #valveNum="{ row }">
            <span class="health-score" @click="handleValveNumClick(row)">{{
              row.valveNum
            }}</span>
          </template>
          <template #compartHealthList="{ row }">
            <div class="status-matrix" v-if="row.compartHealthList.length > 0">
              <div
                v-for="(childRow, rowIndex) in row.compartHealthList"
                :key="rowIndex"
                class="matrix-row"
              >
                <div
                  v-for="(status, colIndex) in childRow"
                  :key="colIndex"
                  class="status-dot"
                  @click="handleStatusDotClick(row, colIndex)"
                  :class="{
                    'status-normal': status.healthStatus === 1,
                    'status-warning': status.healthStatus === 3,
                    'status-error': status.healthStatus === 2,
                  }"
                ></div>
              </div>
            </div>
            <div v-else>-</div>
          </template>

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

          <template #pressureDiffLow="{ row }">
            <span> {{ row.pressureDiffLow }}～{{ row.pressureDiffHigh }} </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"
      :data="currentEditingRow"
      @confirm="handleRoomSettingConfirm"
    />

    <!-- 使用新的电磁阀数量设置弹窗组件 -->
    <ValveSettingDialog
      v-model="valveSettingVisible"
      :data="currentEditingRow"
      @confirm="handleValveSettingConfirm"
    />

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

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, watch } from "vue";
import {
  getDusterLeakNum,
  getHealthPercent,
  getCloseLoopNum,
  getProductionLine,
  getDusterList,
  postAddDuster,
  postUpdateDuster,
  postAddCompartAllocation,
  postAddValveInfo,
} from "@/request/api/dustOverview";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/auth";
import CommonTable from "@/components/commonTable/index.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import RoomSettingDialog from "./components/roomSettingDialog.vue";
import ValveSettingDialog from "./components/valveSettingDialog.vue";
import AddDustCollectorDialog from "./components/addDustCollectorDialog.vue";
import moment from "moment";
const router = useRouter();

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

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

const productionLine = ref([]);
const productionLineFiltered = ref([]); // 用于存储过滤后的工序

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

const tableData = ref([]);

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

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

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

watch(productionLine, (newVal) => {
  productionLineFiltered.value = newVal;
});

const filterProductionLine = (query) => {
  if (!query) {
    productionLineFiltered.value = productionLine.value;
  } else {
    productionLineFiltered.value = productionLine.value.filter((item) =>
      item.productionLineName.toLowerCase().includes(query.toLowerCase())
    );
  }
};

const getHealthScoreColor = (score) => {
  // 去除百分号
  const value = parseInt(score.replace("%", ""));
  if (value == 100) return "#67C23A";
  if (value >= 70) return "#E6A23C";
  return "#F56C6C";
};

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

const handleView = (row) => {
  router.push({
    path: "/monitor",
    query: {
      dusterNo: row.deviceNo,
    },
  });
};

const handleEdit = (row) => {
  currentEditingDustCollector.value = row;
  isAddDustCollectorVisible.value = true;
};

const handlePaginationChange = (pagination) => {
  currentPage.value = pagination.currentPage;
  pageSize.value = pagination.pageSize;
  getData();
};

const onSubmit = () => {
  currentPage.value = 1;
  pageSize.value = 10;
  getData();
};

// 修改打开弹窗的处理函数
const handleHealthScoreClick = (row) => {
  if (row.compartNum < 1) {
    ElMessageBox.alert("当前仓室数量为0，无法进行设置", "提示");
    return;
  }
  currentEditingRow.value = JSON.parse(JSON.stringify(row));
  roomSettingVisible.value = true;
};

// 确认设置
const handleRoomSettingConfirm = (data) => {
  const params = data;
  postAddCompartAllocation(params).then((res) => {
    if (res.code == 1) {
      ElMessage.success("更新仓室数量成功");
      roomSettingVisible.value = false;
      getData();
    }
  });
};

// 点击电磁阀数量时打开弹窗
const handleValveNumClick = (row) => {
  // 创建一个扁平化的状态数组用于电磁阀设置
  if (row.compartHealthList.length > 0) {
    currentEditingRow.value = JSON.parse(JSON.stringify(row));
    valveSettingVisible.value = true;
  } else {
    ElMessage.error("当前仓室数量为0，无法进行设置");
  }
};

const handleStatusDotClick = (row, colIndex) => {
  router.push({
    path: "/bag-monitor",
    query: {
      dusterNo: row.deviceNo,
      dusterName: row.deviceName,
    }
  });
};

const handleDusterLeakNumClick = () => {
  router.push({
    path: "/alerts",
    query: {
      startTime: moment().subtract(24, 'hours').format("YYYY-MM-DD HH:mm:ss"),
      endTime: moment().format("YYYY-MM-DD HH:mm:ss"),
    },
  });
};

const handleCloseLoopNumClick = () => {
  router.push({
    path: "/my-loop/myAgency",
  });
};



// 确认电磁阀设置
const handleValveSettingConfirm = (updatedStatusData) => {
  const list = updatedStatusData.map((item) => {
    return {
      frontCompartNo: item.frontCompartNo,
      valveNum: item.valveNum,
      bagNum: item.bagNum,
      dusterNo: item.dusterNo,
    };
  });
  setValveInfo(list);
};

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

const setValveInfo = (data) => {
  postAddValveInfo(data).then((res) => {
    if (res.code == 1) {
      ElMessage.success("更新电磁阀数量成功");
      valveSettingVisible.value = false;
      getData();
    }
  });
};

const handleCancel = () => {
  isAddDustCollectorVisible.value = false;
  currentEditingDustCollector.value = null;
};
// 保存新增或编辑除尘器
const handleSaveDustCollector = (data) => {
  if (data.id) {
    // 编辑模式
    postUpdateDuster(data)
      .then((res) => {
        if (res.code == 1) {
          ElMessage.success("更新除尘器成功");
          isAddDustCollectorVisible.value = false;
          currentEditingDustCollector.value = null;
          getData();
        }
      })
      .catch((err) => {
        // ElMessage.error(err.message);
      });
  } else {
    // 新增模式
    postAddDuster(data)
      .then((res) => {
        if (res.code == 1) {
          ElMessage.success("新增除尘器成功");
          currentEditingDustCollector.value = null;
          isAddDustCollectorVisible.value = false;
          refreshData();
        }
      })
      .catch((err) => {
        // ElMessage.error(err.message);
      });
  }
};

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;
  });
};

const IproductionLine = () => {
  getProductionLine({
    branchFactoryId: getToken("dataBranchFactoryId"),
  }).then((res) => {
    productionLine.value = res.data || [];
    // 默认显示全部
    productionLineFiltered.value = res.data || [];
  });
};

const getData = () => {
  const params = {
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    productionLineId:
      formInline.value.region === "all" ? "" : formInline.value.region,
    keyword: formInline.value.deviceName,
  };
  getDusterList(params).then((res) => {
    if (res.code == 1) {
      tableData.value = res.data.records || [];
      total.value = res.data.total || 0;
    }
  });
};

const refreshData = () => {
  currentPage.value = 1;
  pageSize.value = 10;
  formInline.value = {
    region: "",
    deviceName: "",
  };
  getData();
};

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

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;
      }
    }
    .crusor-click {
      cursor: pointer;
      transition: box-shadow 0.3s ease; // 添加过渡动画
      &:hover {
        box-shadow: 0px 1.33px 16px 0px rgba(83, 100, 170, 0.5);
      }
    }
  }
  .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%;
    text-decoration: underline;
  }

  .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;
    cursor: pointer;
  }
  .edit-btn {
    cursor: pointer;
  }

  .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;
    }
  }
}

:deep(.el-table) {
  .el-table__column-resize-proxy {
    display: none !important;
  }
  
  .el-table__header th {
    user-select: none;
  }
}
</style>
