<template>
  <div class="page-container collectorList all-select-btn" data-testid="collector-list-container">
    <div class="content-box" data-testid="collector-list-content">
      <div class="search" data-testid="collector-list-search-form">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="仓室">
            <el-input
              v-model="formInline.compart"
              placeholder="请输入仓室名称"
              style="width: 180px"
              clearable
              data-testid="collector-compart-input"
            />
          </el-form-item>
          <el-form-item label="除尘器名称">
            <el-input
              v-model="formInline.dusterName"
              placeholder="请输入除尘器名称"
              style="width: 180px"
              clearable
              data-testid="collector-duster-name-input"
            />
          </el-form-item>
          <el-form-item label="更换时间">
            <el-date-picker
              v-model="formInline.date"
              type="datetimerange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              popper-class="date-picker-popper"
              :teleported="false"
              data-testid="collector-date-picker"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="default" class="reset-btn-balck-theme" @click="onReset" data-testid="collector-reset-button"
              >重置</el-button
            >
            <el-button type="default" class="search-btn-balck-theme" @click="onSubmit" data-testid="collector-search-button"
              >查询</el-button
            >
            <el-button
              type="default"
              style="width: 140px"
              class="export-btn-balck-theme"
              @click="openDialog()"
              data-testid="collector-analysis-button"
              >更换周期分析</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="table-box" data-testid="collector-table-container">
        <common-table
          ref="pageRef"
          :data="tableData.list"
          :columns="tableColumns"
          :default-page-size="20"
          :total="total"
          @pagination-change="handlePaginationChange"
          :pagination-texts="{
            total: '共',
            sizeChange: '条/页',
            prev: '前一页',
            next: '后一页',
            jumper: '跳至',
          }"
          data-testid="collector-common-table"
        >
          <template #index="{ $index }">
            {{ getIndex($index) }}
          </template>
          <template #dusterName="{ row }">
            <span class="health-score green-color" @dblclick="openDialog(row.dusterName)" data-testid="collector-duster-name-link">{{
              row.dusterName
            }}</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>

    <!-- 除尘器曲线 -->
    <el-dialog
      class="dustListDialog"
      v-model="dustLineisShow"
      title="更换周期分析"
      width="1000px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      data-testid="dust-line-dialog"
    >
      <div class="input-group" data-testid="dust-selector-group">
        <span>除尘器名称：</span>
        <el-select
          v-model="selectDustNo"
          placeholder="请选择"
          @change="changeDust"
          style="width: 120px"
          data-testid="dust-name-select"
        >
          <el-option
            v-for="(i,index) in dustList.list"
            :key="i"
            :label="`${i.dusterName}`"
            :value="i.dusterNo"
            :id="`dust-option-${index}`"
          />
        </el-select>
      </div>
      <div class="echartBox" data-testid="chart-container">
        <chartLine :dustLineInfo="dustLineInfo.list"></chartLine>
      </div>
      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button @click="dustLine = false">取消</el-button>
          <el-button type="primary" @click="handleRoomSettingConfirm">
            确认
          </el-button>
        </span>
      </template> -->
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, reactive } from "vue";
import CommonTable from "@/components/commonTable/index.vue";
import { getToken, removeToken, setToken } from "@/utils/auth";
import chartLine from "./components/chart-line.vue";
import { getDataFun, postDataJSON } from "@/request/method.js";
import moment from "moment";

const formInline = ref({
  compart: "",
  dusterName: "",
  date: ["", ""],
});

const currentPage = ref(1);
const pageSize = ref(20);
const dustLineisShow = ref(false);

const tableColumns = ref([
  {
    prop: "index",
    label: "序号",
    width: "5%",
  },
  {
    prop: "dusterName",
    label: "除尘器名称",
    width: "8%",
  },
  {
    prop: "compart",
    label: "仓室",
    width: "10%",
  },
  {
    prop: "bagLocation",
    label: "布袋位置（排/列）",
    width: "6%",
  },
  {
    prop: "bagChangeNextTime",
    label: "布袋更换提醒时间",
    width: "8%",
  },
  {
    prop: "bagChangeTime",
    label: "更换时间",
    width: "8%",
  },
  {
    prop: "bagChangeAuthor",
    label: "更换人",
    width: "5%",
  },
  // {
  //   prop: "dusterName",
  //   label: "所属除尘器",
  //   width: "8%",
  // },
  {
    prop: "bagChangePeriod",
    label: "更换周期(与上次更换比)",
    width: "6%",
  },
]);

const tableData = reactive({
  list: [
    // {
    //   deviceName: "1#除尘器",
    //   compart: "1234567890",
    //   position: "转炉",
    //   changeDateRemind: "xx",
    //   changeDate: "xx",
    //   changePeo: "xx",
    //   ownerdeviceName: "xx",
    //   lastAlarmTime: "xx",
    //   changeRound: "xx",
    // },
  ],
});

const total = ref(0);
const getAllDustList = () => {
  const url = "/bag/cycle/getReplaceListPage";
  const params = {
    compart: formInline.value.compart,
    dusterName: formInline.value.dusterName,
    startTime: formInline.value.date[0]
      ? moment(new Date(formInline.value.date[0]).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        )
      : "",
    endTime: formInline.value.date[1]
      ? moment(new Date(formInline.value.date[1]).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        )
      : "",
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    customerId: getToken("customerId"),
  };
  return getDataFun(url, params).then((res) => {
    if (res && res.data) {
      tableData.list = res.data.records || [];
      total.value = res.data.total;
    } else {
      return [];
    }
  });
};

const selectDustNo = ref("");

const dustList = reactive({
  list: [],
});

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

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

const onSubmit = () => {
  currentPage.value = 1;
  pageRef.value.setCurrentPage(currentPage.value);
  getAllDustList();
};

const pageRef = ref(null);
const onReset = () => {
  formInline.value = {
    compart: "",
    dusterName: "",
    date: ["", ""],
  };
  currentPage.value = 1;
  pageSize.value = 20;
  pageRef.value.setCurrentPage(currentPage.value);
  getAllDustList();
};

const dustLineInfo = reactive({ list: [{}] });

const openDialog = (deviceName) => {
  changeDust(deviceName);
  dustLineisShow.value = true;
};

const getDustList = () => {
  const url = "/bag/cycle/getDusterList";
  return getDataFun(url, "").then((res) => {
    if (res && res.data) {
      return res.data;
    } else {
      return [];
    }
  });
};

const getDustInfo = () => {
  const url = "/bag/cycle/getReplaceAnalysis";
  const params = {
    dusterNo: selectDustNo.value,
  };
  return getDataFun(url, params).then((res) => {
    if (res && res.data) {
      return res.data;
    } else {
      return [];
    }
  });
};

const changeDust = async (dusterName) => {
  dustList.list = await getDustList();
  if (dusterName) {
    dustList.list.forEach((i) => {
      if (i.dusterName == dusterName) {
        selectDustNo.value = i.dusterNo;
      }
    });
  } else {
    selectDustNo.value = dustList.list[0].dusterNo || "";
  }
  let list = await getDustInfo();
  dustLineInfo.list = list;
};

onMounted(async () => {
  getAllDustList();
});

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

<style lang="scss" scoped>
.collectorList {
  width: 100%;
  height: calc(100% - 14px);
  box-sizing: border-box;
  :deep(.el-input--small) {
    width: 100%;
  }
  .content-box {
    display: flex;
    flex-direction: column;
    height: 100%;
    .search {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }
    .table-box {
      width: 100%;
      height: calc(100vh - 600px);
      flex: 1;
    }
  }

  .default-btn {
    .search {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }
    .table-box {
      width: 100%;
      height: calc(100vh - 230px);
    }
  }

  .default-btn {
    width: 85px;
  }
  .search-btn {
    width: 85px;
    background-color: var(--bg-primary);
    border: 1px solid var(--success);
  }
  .add-btn {
    width: 85px;
  }

  .health-score {
    color: var(--success);
    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: 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;
  }

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

  .dustListDialog {
    .echartBox {
      margin: 0 auto;
      width: 950px;
      height: 450px;
      > div {
        width: 950px;
        height: 450px;
      }
    }
  }
}
</style>
