<template>
  <div class="devicemenu">
    <el-space wrap :size="10">
      <el-input
        v-model="state.SearchVal"
        placeholder="筛选"
        style="width: 180px"
        size="mini"
      />
      <el-button class="buttons" size="mini" round @click="search"
        >查询</el-button
      >
      <el-button
        class="buttons"
        size="mini"
        round
        @click="handleEdit(state.addFormData)"
        :disabled="desc.code == ''"
        >新增</el-button
      >
      <el-upload
        class="upload-demo"
        :disabled="desc.code == ''"
        action="/sharding/device/input"
        :show-file-list="false"
        :on-success="handleSuccess"
        :on-progress="handleProgress"
        :on-error="handleError"
      >
        <el-button :disabled="desc.code == ''" class="buttons" size="mini" round
          >导入</el-button
        >
      </el-upload>
      <el-button
        class="buttons"
        size="mini"
        round
        @click="export2Excel"
        :disabled="desc.code == ''"
        >导出</el-button
      >
    </el-space>
  </div>
  <div class="yxpoint-table">
    <el-table
      :data="state.pointTableData"
      stripe
      style="width: 100%"
      height="calc(100% - 45px)"
    >
      <el-table-column type="index" width="50" />
      <el-table-column prop="metricCode" label="测点编码"></el-table-column>
      <el-table-column label="名称">
        <template #default="scope">
          <el-popover
            placement="right"
            popper-class="point-popover"
            :width="260"
            trigger="click"
          >
            <template #reference>
              <el-button
                type="text"
                style="color: #05bb4c"
                size="small"
                @click="handleClick(scope)"
                >{{ scope.row.name }}</el-button
              >
            </template>
            <el-table
              size="mini"
              :data="scope.row.deviceModelMetrics"
              max-height="400px"
            >
              <el-table-column
                property="devicemodel"
                label="机型"
                align="center"
              ></el-table-column>
              <el-table-column
                property="uniformcode"
                label="统一编码"
                align="center"
              ></el-table-column>
              <el-table-column
                property="multiplier"
                label="倍率"
                align="center"
              ></el-table-column>
            </el-table>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="unitName" label="单位"></el-table-column>
      <el-table-column prop="categoryData" label="测点类型"></el-table-column>
      <el-table-column prop="categorysci" label="物理类型"></el-table-column>
      <el-table-column prop="categorysci" label="数据类型"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button
            type="text"
            style="color: #05bb4c"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            style="color: red"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        layout="total, sizes, prev, pager, next"
        :page-sizes="[19, 50, 100, 200, 500]"
        @size-change="
          (value) => {
            query.limit = value;
            query.page = 1;
            getPoint(desc);
          }
        "
        :current-page="query.page"
        :page-size="query.limit"
        :total="pageTotal"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
  </div>
  <!-- 传感点编辑弹出框 -->
  <el-dialog v-model="editVisible" width="40%">
    <el-form :model="editFormData" label-width="80px">
      <el-form-item label="编码">
        <el-input v-model="editFormData.metriccode"></el-input>
      </el-form-item>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="名称">
            <el-input v-model="editFormData.name"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="英文名称">
            <el-input v-model="editFormData.enname"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="标准单位">
            <el-input v-model="editFormData.unitname"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="单位名称">
            <el-input v-model="editFormData.unitnamecn"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述">
        <el-input
          v-model="editFormData.description"
          :rows="3"
          type="textarea"
          clearable
        ></el-input>
      </el-form-item>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="数据类型">
            <el-select v-model="editFormData.categorydata" placeholder="Select">
              <el-option
                v-for="item in state.categorydataoptions"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结构">
            <el-cascader
              v-model="editFormData.structurecode"
              :options="cascaderdata"
              :props="{ checkStrictly: true, emitPath: false }"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="物理类型">
            <el-input v-model="editFormData.categorysci"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="系统分类">
            <el-input v-model="editFormData.categorysys"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="适配机型" class="deviceModelClass">
        <el-select
          v-model="state.deviceModelSel"
          style="margin-right: 20px"
          placeholder="新增机型"
          size="mini"
        >
          <el-option
            v-for="item in state.deviceModel"
            :key="item.code"
            :label="item.code"
            :value="item.code"
          >
          </el-option>
        </el-select>
        <el-button
          v-show="state.deviceModelSel != ''"
          size="mini"
          class="buttons"
          round
          @click="deviceModelAdd()"
          >新增机型
        </el-button>
        <el-table
          :data="editFormData.deviceModelMetrics"
          style="width: 100%; margin-top: 10px"
          max-height="200px"
        >
          <el-table-column prop="devicemodel" label="机型" />
          <el-table-column label="倍率">
            <template #default="scope">
              <el-input v-model="scope.row.multiplier" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="统一编码">
            <template #default="scope">
              <el-input v-model="scope.row.uniformcode" size="mini" />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="footerButton">
        <el-button size="mini" round @click="editVisible = false"
          >取 消</el-button
        >
        <el-button size="mini" round @click="saveEdit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, inject, reactive, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  point,
  metrics,
  delmetrics,
  device_list,
  getWtModel,
} from "@/api/zhbj/index.js";
import { outExportExcel } from "@/tools/excel/exportExcel.js"; //引入文件
onMounted(() => {
  getPoint(desc.value);
  getDeviceModel();
  getequipmentmodel_list();
});
let editFormData = ref({});
let editVisible = ref(false); //传感点
let desc = inject("desc");
let treeId = inject("treeId");
let cascaderdata = inject("cascaderdata");
watch(
  () => treeId,
  (newV, old) => {
    state.addFormData.structurecode = desc.value.code;
    getPoint(desc.value);
  },
  {
    deep: true,
  }
);
let state = reactive({
  pointTableData: "",
  SearchVal: "",
  selectPoint: "",
  selectModel: "",
  modelList: [],
  categorydataoptions: ["AI", "DI", "CI"],
  addFormData: {
    categorydata: "AI",
    categoryres1: null,
    categoryres2: null,
    categoryres3: null,
    categoryres4: null,
    categoryres5: null,
    categorysci: null,
    categorysys: null,
    description: null,
    deviceid: "windturbine",
    enname: null,
    id: null,
    metriccode: "",
    name: "",
    structurecode: "",
    unitname: null,
    unitnamecn: null,
    deviceModelMetrics: [],
  },
});
const query = reactive({
  page: 1,
  limit: 19,
});
let pageTotal = ref(0);
const search = async () => {
  getPoint(desc.value);
};
// getPoint
const getPoint = async (node) => {
  const res = await point(
    node.code,
    query.page,
    query.limit,
    state.selectPoint,
    state.SearchVal,
    "windturbine",
    state.selectModel
  );
  pageTotal.value = res.total;
  state.pointTableData = res.records
    ?.sort((a, b) => {
      return a.id - b.id;
    })
    .map((item, index) => {
      return { ...item, index: index + 1 };
    });
};
// 机型
const getequipmentmodel_list = async () => {
  const { data } = await getWtModel();
  state.modelList = data;
};
// 测点 编辑
const handleEdit = (row) => {
  if (!row.deviceModelMetrics) {
    row.deviceModelMetrics = [];
  }
  editFormData.value = row;
  editVisible.value = true;
};
//测点 add
const postmetrics = async () => {
  const res = await metrics(editFormData.value);
  if (res.code == 200) {
    ElMessage.success(`操作成功!`);
    editVisible.value = false;
  } else {
    ElMessage.success(res.msg);
  }
  getPoint(desc.value);
};
// 保存编辑
const saveEdit = async () => {
  postmetrics();
};
// 测点 删除
const handleDelete = (row) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      const res = await delmetrics(row.id);
      if (res == 1) {
        ElMessage.success(`删除成功!`);
      } else {
        ElMessage.success("删除失败");
      }
      getPoint(desc.value);
    })
    .catch(() => {});
};

//deviceModelAdd 新增机型
const deviceModelAdd = async () => {
  if (state.deviceModelSel == "") return;
  let obj = {
    deviceid: editFormData.value.deviceid,
    devicemodel: state.deviceModelSel,
    id: null,
    metriccode: editFormData.value.metriccode,
    multiplier: 0,
    uniformcode: "",
  };
  editFormData.value.deviceModelMetrics.push(obj);
};
//getDeviceModel
const getDeviceModel = async () => {
  const res = await device_list();
  state.deviceModel = res;
};

// 分页导航
const handlePageChange = (val) => {
  query.page = val;
  getPoint(desc.value);
};

// 批量导入
const handleSuccess = (response, file, fileList) => {
  ElMessage.success("导入成功!");
  getPoint(desc.value);
};
const handleProgress = (response, file, fileList) => {};
const handleError = (response, file, fileList) => {
  ElMessage.success("导入失败!");
};

// 批量导出
const export2Excel = async () => {
  const tableData = await point(
    desc.value.code,
    1,
    99999999,
    state.selectPoint,
    state.SearchVal,
    "windturbine",
    state.selectModel
  );
  ElMessage.success(`导出成功!`);
  const tableHeader = [
    "上级结构编码",
    "测点编码",
    "名称",
    "英文名称",
    "单位",
    "测点类型",
    "物理类型",
    "描述",
  ];
  const tableKey = [
    "structurecode",
    "metriccode",
    "name",
    "enname",
    "unitname",
    "categorydata",
    "categorysci",
    "description",
  ];
  outExportExcel(tableHeader, tableKey, tableData.records, "测点导出excel");
};
const handleClick = ({ row }) => {
  console.log(row.index);
};
</script>
<style lang="less" scoped>
.buttons {
  background-color: rgba(5, 187, 76, 0.2);
  border: 1px solid #3b6c53;
  color: #b3b3b3;
  font-size: 14px;
  &:hover {
    background-color: rgba(5, 187, 76, 0.5);
    color: #ffffff;
  }
}

.devicemenu {
  margin-bottom: 10px;
}
.yxpoint-table {
  height: calc(100% - 39px);
}
.devicemenu {
  margin-bottom: 10px;
}
</style>
<style lang="less">
.point-popover {
  &.is-light {
    background: #081410;
  }
  .el-table {
    background: transparent;
    & th.el-table__cell {
      background: transparent;
    }
    & tr {
      background-color: transparent;
    }
    &::before {
      background-color: transparent;
    }
  }
  .el-popper__arrow::before {
    background: #081410 !important;
    border: 1px solid #081410 !important;
  }
}
</style>
