<template>
  <div class="equipment-management black-theme all-select-btn" data-testid="equipment-management-container">
    <div class="search" data-testid="equipment-management-search-form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="工序">
          <el-select
            v-model="formInline.productionLineId"
            placeholder="请选择工序"
            style="width: 120px"
            data-testid="equipment-production-line-select"
          >
            <el-option
              v-for="(item, index) in processOptions"
              :key="item.productionLineId"
              :label="item.productionLineName"
              :value="item.productionLineId"
              :id="`equipment-production-line-option-${index}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="除尘器名称">
          <el-input
            v-model="formInline.dusterName"
            placeholder="请输入除尘器名称"
            style="width: 240px"
            clearable
            data-testid="equipment-duster-name-input"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="formInline.deviceName"
            placeholder="请输入设备名称"
            style="width: 240px"
            clearable
            data-testid="equipment-device-name-input"
          />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select
            v-model="formInline.deviceTypeId"
            placeholder="请选择设备类型"
            style="width: 120px"
            data-testid="equipment-device-type-select"
          >
            <el-option
              v-for="(item, index) in deviceTypeEnum"
              :key="item.deviceTypeId"
              :label="item.deviceType"
              :value="item.deviceTypeId"
              :id="`equipment-device-type-option-${index}`"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="default" class="reset-btn-balck-theme" @click="onReset" data-testid="equipment-reset-button"
            >重置</el-button
          >
          <el-button
            type="default"
            class="search-btn-balck-theme margin-right-10"
            @click="onQuery"
            data-testid="equipment-search-button"
            >查询</el-button
          >
          <el-upload
            ref="upload"
            class="upload-demo"
            :action="uploadUrl"
            :on-exceed="handleExceed"
            :on-error="handleError"
            :on-success="handleSuccess"
            :on-progress="handleProgress"
            :before-upload="beforeUpload"
            :headers="{
              token: getToken('TOKEN'),
            }"
          >
            <el-button type="default" class="export-btn-balck-theme margin-right-10" data-testid="equipment-import-button"
              >导入</el-button
            >
          </el-upload>
          <el-button type="default" class="export-btn-balck-theme" @click="onExportFile" data-testid="equipment-export-button"
            >导出</el-button
          >
          <el-button type="default" class="export-btn-balck-theme" @click="onDownloadTemplate" data-testid="equipment-template-button"
            >模板下载</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="table-box" data-testid="equipment-table-container">
      <common-table
        :data="tableData"
        :columns="tableColumns"
        :default-page-size="20"
        @pagination-change="handlePaginationChange"
        :total="total"
        align="center"
        :pagination-texts="{
          total: '共',
          sizeChange: '条/页',
          prev: '前一页',
          next: '后一页',
          jumper: '跳至',
        }"
        data-testid="equipment-common-table"
      >
        <template #index="{ $index }">
          {{ getIndex($index) }}
        </template>

        <template #operation="{ row }">
          <el-button class="green-color" text @click="getParamsConfig(row)" v-if="[10001, 10002].includes(row.deviceTypeId)" data-testid="equipment-params-button"> 参数设置 </el-button>
        </template>
      </common-table>
    </div>
    <setParamsDialog
      v-model:dialogVisible="dialogVisible"
      @close="closeDialog"
      :infoObjProps="infoObj"
    ></setParamsDialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import setParamsDialog from "./components/paramsSetings.vue";
import CommonTable from "@/components/commonTable/index.vue";
import "@/css/elementUiSelf.css";
import { getDataFun, exportFile } from "@/request/method.js";
import { getToken } from "@/utils/auth";
import axios from "axios";
const ENV = import.meta.env;
const uploadUrl = ENV.VITE_APP_BASE_API5 + "/importDeviceAndSignal";
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const getIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index + 1;
};

const formInline = reactive({
  deviceName: "",
  dusterName: "",
  deviceTypeId: " ",
  productionLineId: " ",
});

const tableData = ref([]);
const tableColumns = ref([
  {
    prop: "index",
    label: "序号",
    width: "5%",
  },
  {
    prop: "dusterName",
    label: "除尘器名称",
    width: "15%",
  },
  {
    prop: "dusterNo",
    label: "除尘器编号",
    width: "15%",
  },
  {
    prop: "productionLine",
    label: "所属工序",
    width: "5%",
  },
  {
    prop: "deviceName",
    label: "设备名称",
    width: "5%",
  },
  {
    prop: "deviceNo",
    label: "设备编码",
    width: "5%",
  },
  {
    prop: "deviceTypeDesc",
    label: "设备类型",
    width: "5%",
  },
  {
    prop: "signalName",
    label: "信号名称",
    width: "15%",
  },
  {
    prop: "signalNo",
    label: "信号ID",
    width: "5%",
  },
  {
    prop: "position",
    label: "安装位置",
    width: "10%",
  },
  {
    prop: "operation",
    label: "操作",
    width: "10%",
  },
]);
const dialogVisible = ref(false);
const setParams = () => {
  dialogVisible.value = true;
};
const closeDialog = (val) => {
  dialogVisible.value = val;
};
// 工序
const processOptions = ref([
  { productionLineId: " ", productionLineName: "全部" },
]);
// 获取工序
const getProcessOptions = () => {
  const url = "/transaction/getProductionLine";
  const params = {
    branchFactoryId: getToken("dataBranchFactoryId"),
  };
  getDataFun(url, params)
    .then((res) => {
      res.data.forEach((item) => {
        processOptions.value.push(item);
      });
    })
    .catch((err) => {
      processOptions.value = [
        { productionLineId: "", productionLineName: "全部" },
      ];
    });
};
// 设备类型枚举值
const deviceTypeEnum = ref([{ deviceType: "全部", deviceTypeId: " " }]);
// 获取设备类型
const getDeviceType = () => {
  const url = "/getDcTomDeviceType";
  const params = {};
  getDataFun(url, params)
    .then((res) => {
      res.data.forEach((element) => {
        deviceTypeEnum.value.push(element);
      });
    })
    .catch((err) => {
      deviceTypeEnum.value = [{ deviceType: "全部", deviceTypeId: "" }];
    });
};
// 获取设备列表
const getDeviceContent = () => {
  const url = "/getPageDcTomDeviceResp";
  const params = {
    pageSize: pageSize.value, // 当前页数据条数
    pageNo: currentPage.value, // 当前页页码
    customerId: getToken("customerId"), // 客户ID
    deviceName: formInline.deviceName, // 设备名称
    dusterName: formInline.dusterName, // 除尘器名称
    deviceTypeId: formInline.deviceTypeId, // 设备类型
    productionLineId: formInline.productionLineId, // 工艺
  };
  getDataFun(url, params)
    .then((res) => {
      tableData.value = (res && res.data && res.data.records) || [];
      total.value = res.data.total || 0;
    })
    .catch((err) => {
      tableData.value = [];
      total.value = 0;
    });
};
// 重置
const onReset = () => {
  formInline.deviceName = "";
  formInline.dusterName = "";
  formInline.deviceTypeId = " ";
  formInline.productionLineId = " ";
  pageSize.value = 10;
  currentPage.value = 1;
  getDeviceContent();
};
// 查询
const onQuery = () => {
  getDeviceContent();
};
// 导入
const onImportFile = () => {
  const url = "/importDeviceAndSignal";
  const params = {
    customerId: getToken("customerId"), // 客户ID
    deviceName: formInline.deviceName, // 设备名称
    dusterName: formInline.dusterName, // 除尘器名称
    deviceTypeId: formInline.deviceTypeId, // 设备类型
    productionLineId: formInline.productionLineId, // 工艺
  };
};
// 导出
const onExportFile = () => {
  const url = "/exportDeviceAndSignal" + `?customerId=${getToken("customerId")}&deviceName=${encodeURIComponent(formInline.deviceName)}&dusterName=${encodeURIComponent(formInline.dusterName)}&deviceTypeId=${encodeURIComponent(formInline.deviceTypeId)}&productionLineId=${encodeURIComponent(formInline.productionLineId)}`;
  const params = {};
  exportFile("get", url, params).then((res) => {
    const blob = res;
    // 创建 URL 对象
    const url = URL.createObjectURL(blob);

    // 创建临时 <a> 元素
    const a = document.createElement("a");
    a.href = url;
    a.download = `设备数据.xls`; // 设置下载的文件名

    // 模拟点击下载
    document.body.appendChild(a);
    a.click();

    // 清理资源
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  });
};
// 模板下载
const onDownloadTemplate = () => {
  window.open(
    "https://visimg.bmetech.com/stone/img/1751950181533/设备数据.xlsx"
  );
  return;
  axios
    .get("https://visimg.bmetech.com/stone/img/1748314002767/设备数据.xlsx", {
      responseType: "blob",
    })
    .then((res) => {
      console.log(res);
      const blob = res.data;
      // 创建 URL 对象
      const url = URL.createObjectURL(blob);

      // 创建临时 <a> 元素
      const a = document.createElement("a");
      a.href = url;
      // 设置下载的文件名
      if (res.data.type === "application/vnd.ms-excel") {
        a.download = `设备数据.xls`; // 设置下载的文件名
      } else {
        a.download = `设备数据.xlsx`;
      }

      // 模拟点击下载
      document.body.appendChild(a);
      a.click();

      // 清理资源
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    });
};
// 页面参数改变
const handlePaginationChange = (pagination) => {
  currentPage.value = pagination.currentPage;
  pageSize.value = pagination.pageSize;
  getDeviceContent();
};
// 当超出限制时，执行的钩子函数
const handleExceed = (files) => {
  console.log("上传超出限制");
};
// 上传失败
const handleError = () => {
  ElMessage({
    message: "文件上传失败",
    type: "error",
    duration: 5 * 1000,
  });
};
const handleSuccess = (res) => {
  if (res.code == 1) {
    if (res.data && res.data.length > 0) {
      let text = ''
      res.data.forEach(item => {
        text += `第${item.row}行：${item.rule}\n；`
      })
      ElMessage({
        message: `${res.msg}：${text}`,
        type: "error",
        duration: 5 * 1000,
      });
    } else {
      ElMessage({
        message: '导入成功',
        type: "success",
        duration: 5 * 1000,
      });
    }
  }
  getDeviceContent();
};
const handleProgress = (evt, uploadFile) => {};
const beforeUpload = (file) => {
  if (
    file.type !== "application/vnd.ms-excel" &&
    file.type !==
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  ) {
    ElMessage({
      message: "请上传excel文件",
      type: "primary",
      duration: 5 * 1000,
    });
    return false;
  } else {
    return true;
  }
};
const infoObj = ref({});
// 获取参数
const getParamsConfig = (val) => {
  const url = "/getSensorConfig";
  const params = {
    deviceNo: val.deviceNo,
  };
  getDataFun(url, params)
    .then((res) => {
      // res.data = {
      //   id: 7,
      //   customerId: 26,
      //   deviceNo: "cgq_001",
      //   deviceName: "布袋传感器001",
      //   compartNum: 12,
      //   address: "地址",
      //   pulseValveFaultThreshold: "脉冲阀故障阈值",
      //   slope: "斜率",
      //   pulseValveNum: "脉冲阀数量",
      //   intercept: "截距",
      //   backblowInterval: "反吹间隔时间",
      //   baselineThreshold: "基线阈值",
      //   delayTime: "延时时间",
      //   clusterValue: "群聚值",
      //   integrationTime: "积分时间",
      //   communicationPort: "通信口",
      //   leakThreshold: "泄露阈值",
      //   onlineBackblow: true,
      //   fastBlow: true,
      //   faultThreshold: "故障阈值",
      //   d01Alarm: true,
      //   d13Alarm: true,
      //   valleyDection: "谷值判定",
      //   valveNum: "阀数量",
      //   liftValveFailure: "提升阀故障",
      //   compartSort: "仓室顺序",
      //   liftValveDelayTime: "提升阀延迟时间",
      //   diInput: true,
      //   showEarlyWarn: true,
      //   relateDevicesNum: "关联设备",
      //   liftValveCommunicationIp: "脉冲的设备通信ip",
      //   indoorPulseBlow: true,
      // };
      dialogVisible.value = true;
      infoObj.value = res.data || {};
    })
    .catch((err) => {
      ElMessage.error("获取参数设置失败");
    });
};
onMounted(() => {
  getDeviceType();
  getProcessOptions();
  getDeviceContent();
});
</script>

<style lang="scss" scoped>
.equipment-management {
  height: calc(100% - 14px);
  box-sizing: border-box;
  background: #fff;
  overflow: hidden;
  padding: 20px;
  display: flex;
  flex-direction: column;
  .search {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  .table-box {
    width: 100%;
    height: calc(100vh - 400px);
    flex: 1;
  }
  .el-button.is-text:not(.is-disabled):hover {
    background-color: #434343;
}
}
.default-btn {
  width: 85px;
}
.search-btn {
  width: 85px;
  background-color: var(--bg-primary);
  border: 1px solid var(--success);
}
.add-btn {
  width: 85px;
}
.margin-right-10 {
  margin-right: 10px;
}


</style>
<style>
.equipment-management .el-upload-list {
  display: none;
}
</style>