<template>
  <div class="page-container dust-container all-select-btn" data-testid="dust-overview-container">
    <div class="header" data-testid="dust-overview-header">
      <div class="item-box crusor-click" @click="handleDusterLeakNumClick" data-testid="dust-leak-alert-card">
        <img src="@/assets/icons/warn.png" alt="dust" />
        <div class="title">
          <span>泄漏告警(条)</span>
          <div class="content">{{ dusterLeakNum }}</div>
        </div>
      </div>

      <div class="item-box" data-testid="dust-health-card">
        <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" data-testid="dust-close-loop-card">
        <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" data-testid="dust-overview-content">
      <div class="search" data-testid="dust-search-form">
        <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"
              data-testid="dust-production-line-select"
            >
              <el-option key="all" label="全部" value="all"  id="production-line-option-all" />
              <el-option
                v-for="(item, index) in productionLineFiltered"
                :key="item.productionLineId"
                :label="item.productionLineName"
                :value="item.productionLineId"
                :id="`production-line-option-${index}`"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="除尘器名称">
            <el-input
              v-model="formInline.deviceName"
              placeholder="请输入除尘器名称"
              style="width: 240px"
              clearable
              data-testid="dust-device-name-input"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="default" class="reset-btn-balck-theme" @click="refreshData" data-testid="dust-reset-button"
              >重置</el-button
            >
            <el-button type="default" class="search-btn-balck-theme" @click="onSubmit" data-testid="dust-search-button"
              >查询</el-button
            >
            <el-button
              type="default"
              class="export-btn-balck-theme"
              @click="handleAddDustCollector"
              data-testid="dust-add-button"
              >新增</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="table-box" data-testid="dust-table-container">
        <common-table
          :data="tableData"
          :columns="tableColumns"
          :default-page-size="pageSize"
          @pagination-change="handlePaginationChange"
          :total="total"
          :pagination-texts="{
            total: '共',
            sizeChange: '条/页',
            prev: '前一页',
            next: '后一页',
            jumper: '跳至',
          }"
          data-testid="common-table"
        >
          <template #index="{ $index }">
            {{ getIndex($index) }}
          </template>
          <template #compartNum="{ row }">
            <span class="health-score" @click="handleHealthScoreClick(row)" data-testid="compartment-count-link">{{
              row.compartNum
            }}</span>
          </template>
          <template #valveNum="{ row }">
            <span class="health-score" @click="handleValveNumClick(row)" data-testid="valve-count-link">{{
              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)" data-testid="dust-view-button">详情</span>
            <span class="edit-btn" @click="handleEdit(row)" data-testid="dust-edit-button">编辑</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(20);
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 = 20;
  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"),
      deviceType: 200003 // 默认为布袋告警
    },
  });
};

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



// 确认电磁阀设置
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 = 20;
  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;
  background-color: #181d21;

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

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

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

      .title {
        width: 100%;

        span {
          color: #909399;
          line-height: 22px;
          font-size: 14px;
          font-weight: 500;
        }
      }

      .content {
        color: #fff;
        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;
      
      // :deep(.el-form-item__label) {
      //   color: #fff;
      // }
      
      // :deep(.el-input__inner),
      // :deep(.el-select__input) {
      //   background-color: #242a30;
      //   border-color: #2c3136;
      //   color: #fff;
      // }
      
      // :deep(.el-select-dropdown__item) {
      //   color: #fff;
      // }
      
      // :deep(.el-select-dropdown) {
      //   background-color: #242a30;
      //   border-color: #2c3136;
      // }
    }
    .table-box {
      width: 100%;
      height: calc(100vh - 400px);
      
      :deep(.el-table) {
        background-color: #181d21;
        color: #fff;
        
        th.el-table__cell {
          background-color: #242a30;
          color: #fff;
          border-bottom: 1px solid #2c3136;
        }
        
        td.el-table__cell {
          background-color: #181d21;
          border-bottom: 1px solid #2c3136;
        }
        
        .el-table__header-wrapper,
        .el-table__body-wrapper {
          background-color: #181d21;
        }
      }
      
      :deep(.el-pagination) {
        background-color: #181d21;
        color: #909399;
        
        .el-pagination__total,
        .el-pagination__jump,
        .btn-prev,
        .btn-next {
          color: #909399;
        }
        
        .el-input__inner {
          // background-color: #242a30;
          border-color: #2c3136;
          color: #a8abb2;
        } 
      }
    }
  }

  .default-btn {
    width: 85px;
    background-color: var(--text-secondary);
    border-color: #2c3136;
    color: #fff;
  }
  .search-btn {
    width: 85px;
    background-color: var(--bg-primary);
    border: 1px solid var(--success);
  }
  .add-btn {
    width: 85px;
    background-color: #67c23a;
    border-color: #67c23a;
  }

  .health-score {
    color: var(--success);
    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 #2c3136;
    border-radius: 4px;
    background-color: #242a30;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);

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

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

  :deep(.el-dialog) {
    background-color: #242a30;
    
    .el-dialog__title {
      color: #fff;
    }
    
    .el-dialog__body {
      padding: 20px;
      color: #909399;
    }
    
    .el-form-item__label {
      color: #fff;
    }
    
    .el-input__inner,
    .el-textarea__inner {
      background-color: #181d21;
      border-color: #2c3136;
      color: #a8abb2;
    }
  }

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

  .table-title {
    font-size: 14px;
    color: var(--success);
    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;
  // }
  :deep(.distribution-table  .el-table .el-table__row td) {
    color: #a8abb2;
  }

  .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: #242a30;
    border-radius: 4px;

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

    .valve-cell {
      width: 41px;
      background: #181d21;
      padding: 4px;
      border-radius: 4px;
      text-align: center;
      border: 1px solid #2c3136;

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

      .cell-value {
        :deep(.el-input-number) {
          width: 100px;
          
          .el-input__inner {
            background-color: #181d21;
            border-color: #2c3136;
            color: #a8abb2;
          }
        }
      }
    }
  }

  .readonly-value {
    font-size: 14px;
    color: #909399;
    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: rgba(230, 162, 60, 0.2);
    }

    &.warning-less {
      color: #f56c6c;
      background-color: rgba(245, 108, 108, 0.2);
    }
  }
}

:deep(.el-table) {
  .el-table__column-resize-proxy {
    display: none !important;
  }
  
  .el-table__header th {
    user-select: none;
    background-color: #242a30 !important;
    color: #fff !important;
    border-bottom: 1px solid #2c3136 !important;
  }
  
  .el-table__row {
    background-color: #181d21 !important;
    
    td {
      border-bottom: 1px solid #2c3136 !important;
      color: #fff;
    }
    
    &:hover > td {
      background-color: #242a30 !important;
    }
  }
  
  .el-table__empty-block {
    background-color: #181d21;
    
    .el-table__empty-text {
      color: #909399;
    }
  }
}
</style>
