<template>
  <div class="main deviceClass">
    <el-card class="box-card-tree">
      <button
        class="btn green"
        style="margin-bottom: 10px"
        @click="handleTreeAdd()"
      >
        新增
      </button>
      <button
        class="btn green"
        @click="handleTreeDel()"
        :disabled="state.isDel == ''"
      >
        删除
      </button>
      <el-tree
        :data="state.treedata"
        :props="state.defaultProps"
        node-key="id"
        highlight-current
        :default-expanded-keys="['23']"
        @node-click="handleNodeClick"
      />
    </el-card>
    <el-card class="box-card">
      <el-tabs type="card" class="tab">
        <el-tab-pane label="传感点">
          <div class="devicemenu">
            <button
              class="btn"
              style="margin-bottom: 10px"
              @click="handleEdit(state.addFormData)"
              :disabled="state.desc.code == ''"
            >
              新增
            </button>
            <el-input
              style="width: 180px; margin: 0 10px"
              v-model="state.SearchVal"
              placeholder="筛选"
              :prefix-icon="Search"
              @input="fifterSearch()"
              size="small"
            />
            <button
              class="btn"
              size="mini"
              type="primary"
              :disabled="state.desc.code == ''"
            >
              导入
            </button>
            <button
              class="btn"
              size="mini"
              type="primary"
              @click="export2Excel"
              :disabled="state.desc.code == ''"
            >
              导出
            </button>
          </div>
          <!-- <el-row :gutter="24" align="middle">
            <el-col :span="2">
              <button
                 class="btn green"
                style="margin-bottom: 10px"
                @click="handleEdit(state.addFormData)"
                :disabled='state.desc.code==""'
                >新增</button
              ></el-col
            >
            <el-col :span="5">
              <el-input
                v-model="state.SearchVal"
                placeholder="筛选"
                :prefix-icon="Search"
                @input="fifterSearch()"
                size="small"
              />
            </el-col>
          </el-row> -->
          <el-table
            :data="state.fifterSearchTableData"
            stripe
            style="width: 100%"
            height="700"
          >
            <el-table-column type="index" width="50" align="center" />
            <el-table-column
              prop="metriccode"
              label="测点编码"
              align="center"
            ></el-table-column>
            <el-table-column label="名称" align="center">
              <template #default="scope">
                <el-popover placement="right" :width="260" trigger="click">
                  <template #reference>
                    <el-button
                      type="text"
                      style="color: #b3bdc0"
                      size="small"
                      >{{ scope.row.name }}</el-button
                    >
                  </template>
                  <el-table
                    :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="单位"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="categorydata"
              label="测点类型"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="categorysci"
              label="物理类型"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="description"
              label="描述"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template #default="scope">
                <el-button
                  type="text"
                  style="color: #b3bdc0"
                  @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  style="color: #b3bdc0"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <div class="pagination">
          <el-pagination
            background
            layout="total, prev, pager, next"
            hide-on-single-page
            :current-page="query.page"
            :page-size="query.limit"
            :total="pageTotal"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
        <el-tab-pane label="故障模式">
          <faultmode />
        </el-tab-pane>
        <el-tab-pane label="基本信息" style="width: 50%">
          <el-form :model="state.desc" label-width="100px">
            <el-form-item label="结构编码">
              <el-input v-model="state.desc.code"></el-input>
            </el-form-item>
            <el-form-item label="上级节点">
              <el-cascader
                v-model="state.desc.parentcode"
                :options="state.cascaderdata"
                :props="{ checkStrictly: true, emitPath: false }"
                :show-all-levels="false"
                clearable
              />
            </el-form-item>
            <el-form-item label="设备ID">
              <el-input v-model="state.desc.deviceid" disabled></el-input>
            </el-form-item>
            <el-form-item label="结构名称">
              <el-input v-model="state.desc.name"></el-input>
            </el-form-item>
            <el-form-item label="结构英文名称">
              <el-input v-model="state.desc.enname"></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                v-model="state.desc.description"
                :rows="4"
                clearable
                type="textarea"
              ></el-input>
            </el-form-item>
            <el-form-item label="序号">
              <el-input v-model="state.desc.orderno"></el-input>
            </el-form-item>
            <el-form-item label="是否有效">
              <el-switch
                class="elswitch"
                v-model="state.desc.enabled"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </el-form-item>
          </el-form>
          <button
            style="float: right"
            class="btn green"
            @click="savedesc"
            :disabled="state.desc.code == ''"
          >
            保存
          </button>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 传感点编辑弹出框 -->
    <el-dialog v-model="editVisible" width="40%" custom-class="modal">
      <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.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="结构">
              <el-cascader
                v-model="editFormData.structurecode"
                :options="state.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>
          <button
            class="btn green"
            v-show="state.deviceModelSel != ''"
            size="mini"
            type="primary"
            @click="deviceModelAdd()"
          >
            新增机型
          </button>
          <el-table
            :data="editFormData.deviceModelMetrics"
            style="width: 100%"
            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="dialog-footer">
          <button class="btn green" @click="editVisible = false">取 消</button>
          <button class="btn green" type="primary" @click="saveEdit">
            确 定
          </button>
        </span>
      </template>
    </el-dialog>
    <!-- tree add 弹出框 -->
    <el-dialog v-model="treeVisible" width="40%" custom-class="modal">
      <el-form :model="state.treeAddFormData" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="结构编码">
              <el-input
                v-model="state.treeAddFormData.code"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="上级节点" label-width="100px">
              <el-cascader
                v-model="state.treeAddFormData.parentcode"
                :options="state.cascaderdata"
                :props="{ checkStrictly: true, emitPath: false }"
                :show-all-levels="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="state.treeAddFormData.name"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="结构英文名称" label-width="100px">
              <el-input
                v-model="state.treeAddFormData.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="state.treeAddFormData.orderno"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="4">
            <el-form-item label="是否有效">
              <el-switch
                v-model="state.treeAddFormData.enabled"
                class="elswitch"
                active-color="#13ce66"
                inactive-color="#ff4949"
              /> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="设备ID">
              <el-input
                v-model="state.treeAddFormData.deviceid"
                disabled
              ></el-input> </el-form-item
          ></el-col>
        </el-row>
        <el-form-item label="描述">
          <el-input
            v-model="state.treeAddFormData.description"
            :rows="4"
            clearable
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <button class="btn green" @click="treeVisible = false">取 消</button>
          <button class="btn green" type="primary" @click="saveTreeAdd">
            确 定
          </button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive, provide, computed } from "vue";
import { ElMessageBox, ElMessage, ElLoading } from "element-plus";
import faultmode from "./faultmode.vue";
import { outExportExcel } from "@tools/excel/exportExcel";
import {
  tree,
  point,
  metrics,
  delmetrics,
  treeAdd,
  treeDel,
  device_list,
} from "@/api/api.js";
let editVisible = ref(false); //传感点
let treeVisible = ref(false); //传感点
let editFormData = ref({});
onMounted(() => {
  getData();
  getDeviceModel();
});
let state = reactive({
  isDel: "", //是否能被删除
  SearchVal: "",
  treedata: [],
  cascaderdata: [],
  defaultProps: {
    children: "children",
    label: (a) => {
      return a.node.name;
    },
  },
  pointTableData: [],
  fifterSearchTableData: [],
  textarea: "",
  textarea1: "",
  treeCurClick: null,
  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: "101010205",
    unitname: null,
    unitnamecn: null,
    deviceModelMetrics: [],
  },
  treeAddFormData: {
    code: "",
    parentcode: "",
    deviceid: "windturbine",
    name: "",
    enname: "",
    description: "",
    orderno: "",
    enabled: true,
  },
  options: [
    {
      value: "AI",
      label: "AI",
    },
    {
      value: "DI",
      label: "DI",
    },
    {
      value: "CI",
      label: "CI",
    },
  ],
  desc: {
    code: "",
    parentcode: "",
    deviceid: "",
    name: "",
    enname: "",
    description: "",
    orderno: "",
    enabled: true,
  },
  treeDelVal: "",
  deviceModel: [],
  deviceModelSel: "",
});

// 父子传参
provide(
  "cascaderdata",
  computed(() => state.cascaderdata)
);
//fifterSearch
const fifterSearch = () => {
  if (state.SearchVal == "") {
    return state.fifterSearchTableData = state.pointTableData;
  } else {
    state.fifterSearchTableData = state.pointTableData.filter((e) => {
      return (
        e.name.includes(state.SearchVal) |
        e.categorydata.includes(state.SearchVal) |
        e.metriccode.includes(state.SearchVal)
      );
    });
  }
};
// tree click
const handleNodeClick = (data) => {
  console.log(data);
  state.isDel = data.children;
  state.desc = data.node;
  state.addFormData.structurecode = data.node.code;
  getPoint(data.node);
};
// 测点 编辑
const handleEdit = (row) => {
  editFormData.value = row;
  editVisible.value = true;
};
// tree add
const handleTreeAdd = () => {
  treeVisible.value = true;
};
// tree Del
const handleTreeDel = () => {
  console.warn(state.desc);
  if (state.isDel != null) {
    ElMessage.error(`不能删除该节点!!`);
    return;
  }
  ElMessageBox.confirm(`确定要删除 ${state.desc.name} 吗？`, "提示", {
    type: "warning",
  })
    .then(async () => {
      const res = await treeDel(state.desc.id);
      console.warn(res);
      if (res == 1) {
        ElMessage.success(`删除成功!`);
        getData();
      } else {
        ElMessage.warning(`删除失败!`);
      }
    })
    .catch(() => {});
};
// delTreeBtn
const delTreeBtn = async () => {
  console.warn(state.treeDelVal);
  const res = await treeDel(state.treeDelVal);
  console.warn(res);
  if (res == 1) {
    ElMessage.success(`删除成功!`);
    getData();
  } else {
    ElMessage.warning(`删除失败!`);
  }
  state.treeDelVal = "";
};
//保存tree add
const saveTreeAdd = async () => {
  const res = await treeAdd(state.treeAddFormData);
  console.warn(res);
  if (res.status == 20000) {
    ElMessage.success(`操作成功!`);
    treeVisible.value = false;
    getData();
  } else {
    ElMessage.warning(res.msg);
  }
};

// 测点 删除
const handleDelete = (row) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      console.warn(row);
      const res = await delmetrics(row.id);
      console.warn(res);
      if (res == 1) {
        ElMessage.success(`删除成功!`);
      } else {
        ElMessage.success("删除失败");
      }
      getPoint(state.desc);
    })
    .catch(() => {});
};
// 保存编辑
const saveEdit = async () => {
  postmetrics();
};
//测点 add
const postmetrics = async () => {
  console.warn(editFormData.value);
  const res = await metrics(editFormData.value);
  console.warn(res);
  if (res.status == 20000) {
    ElMessage.success(`操作成功!`);
    editVisible.value = false;
  } else {
    ElMessage.success(res.msg);
  }
  getPoint(state.desc);
};
// getData
const getData = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "数据加载中...",
    background: "rgba(0, 0, 0, 0.5)",
  });
  const res = await tree();
  loading.close();
  console.warn(res);
  state.treedata = res.children;
  state.cascaderdata = cascaderforEach(res);
  console.warn(state.cascaderdata);
};
//deviceModelAdd 新增机型
const deviceModelAdd = async () => {
  if (state.deviceModelSel == "") return;
  console.warn();
  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;
  console.warn(res);
};
///// 基本信息

const savedesc = async () => {
  const res = await treeAdd(state.desc);
  console.warn(res);
  if (res.status == 20000) {
    ElMessage.success(`操作成功!`);
  } else {
    ElMessage.success(res.msg);
  }
};

///// 基本信息
// getPoint
const getPoint = async (node) => {
  const res = await point(node.code, query.page, query.limit);
  console.warn(res);
  pageTotal.value = res.total;
  state.pointTableData = res.records?.sort((a, b) => {
    return a.id - b.id;
  });
  fifterSearch();
};
// 递归解析基础数据
const cascaderforEach = (val) => {
  if (val.children != null) {
    val.children.forEach((v) => {
      v["value"] = v.node.code;
      v["label"] = v.node.name;
      v["id"] = v.node.id;
      cascaderforEach(v);
    });
    return val.children;
  }
};
// 批量导出
const export2Excel = () => {
  const tableData = state.pointTableData;
  const tableHeader = [
    "测点编码",
    "名称",
    "单位",
    "测点类型",
    "物理类型",
    "描述",
  ];
  const tableKey = [
    "metriccode",
    "name",
    "unitname",
    "categorydata",
    "categorysci",
    "description",
  ];
  outExportExcel(tableHeader, tableKey, tableData, "测点导出excel");
};
const query = reactive({
  page: 1,
  limit: 15,
});
let pageTotal = ref(0);
// 分页导航
const handlePageChange = (val) => {
  query.page = val;
  getPoint(state.desc);
};
</script>
<style lang="scss" scoped>
.main {
  display: flex;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  justify-content: space-between;
  .box-card-tree {
    width: 20%;
    margin-right: 1%;
    overflow: auto;
  }
  .box-card {
    flex: 1;
    .desc {
      display: flex;
      margin-bottom: 30px;
      span {
        width: 100px;
      }
    }
  }
}
</style>
<style lang="less" >
.deviceModelClass {
  .el-table__header tr,
  .el-table__header th {
    padding: 0;
    height: 40px;
  }
  .el-table__body tr,
  .el-table__body td {
    padding: 0;
    height: 40px;
  }
}
.tab {
  .el-tabs__item.is-active {
    color: @green;
  }
  .el-tabs__item {
    color: #b7b7b7;
  }
}
.elswitch {
  .el-switch__input {
    position: absolute !important;
  }
}
.deviceClass {
  .el-row {
    margin-bottom: 16px;
  }
}
</style>