<script setup name="prepare">
import searchCop from "./components/search.vue";
import excelCop from "@/components/excel.vue";
import treeCop from "@/components/tree.vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { onMounted, ref, onActivated, nextTick } from "vue";
import request from "@/api/axios.js";
import { baseURL, socketURL } from "@/api/axios.js";
/**配置参数 */
const treeHeight = ref(window.innerHeight - 260 + "px"); //tree高度
const excelHeight = ref(window.innerHeight - 260 + "px"); //excel高度
const tableHeight = ref(window.innerHeight - 260 + "px");

/**tree 开始 */
const treeData = ref([]);
const actTreeNode = ref(null); //当前激活的treeNode
const funRepeatMap = (arr) => {
  return arr.map((o) => {
    if (o.children) {
      const findIndex = o.children.findIndex((p) => !!p.type);
      if (findIndex !== -1) {
        o.childs = o.children;
        o.children = [];
        if (!actTreeNode.value) {
          //判断当且仅有process获取tree时 赋值
          actTreeNode.value = o;
        }
      }
    }
    return {
      ...o,
      children: o.children?.length ? funRepeatMap(o.children) : [],
    };
  });
};

const funStationGet = async (point) => {
  const res = await request.post(
    "/rest/sql",
    `SELECT DISTINCT station FROM ${treeData.value[0].id}.${point};`
  );
  // console.log("nb", res);
};

const funGetTree = async () => {
  actTreeNode.value = null;
  treeData.value = [];
  const res = await request.post("/rest/sql", "show databases;");
  const databaseNameArray = res.data || [];
  const blackList = ["information_schema", "performance_schema", "'mydbinfo'"];

  let resultDatabaesArray = [];

  databaseNameArray.forEach((pEle) => {
    pEle.forEach((cEle) => {
      const someRes = blackList.some((someEle) => {
        return someEle === cEle;
      });
      if (!someRes) {
        resultDatabaesArray.push(cEle);
      }
    });
  });

  let tempTreeData = [];

  resultDatabaesArray.forEach(async (ele) => {
    const { data } = await request.post("/rest/sql", `show ${ele}.stables;`);
    //处理树状结构数据
    if (data?.length) {
      let treeItem = {
        id: ele,
        label: ele,
        value: ele,
        children: [],
      };
      data.forEach((pEle) => {
        pEle.forEach((cEle) => {
          treeItem.children.push({
            id: cEle,
            label: cEle,
            value: cEle,
            children: [],
          });
        });
      });
      tempTreeData.push(treeItem);
    }
  });

  setTimeout(() => {

    treeData.value = tempTreeData;

  }, 1000);

  // nextTick(()=>{
  //    treeData.value=tempTreeData;
  // })

};

const funCurrentChange = async ({ current, currentNode }) => {
  const tableName = current.value;
  let databaseName = "";
  for (let i = 0; i < treeData.value.length; i++) {
    const pEle = treeData.value[i];
    for (let j = 0; j < pEle.children.length; j++) {
      const cEle = pEle.children[j];
      if (cEle.value === tableName) {
        databaseName = pEle.value;
        break;
      }
    }
  }

  //拿取表格数据
  const res = await request.post(
    "/rest/sql",
    `SELECT tbname as point,description,ts,val,station,category,facility,uniformcode,rate,remark FROM ${databaseName}.${tableName} limit 99;`
  );
  //映射数组里的数据
  let newdata = [];
  const map = {
    0: "point",
    1: "description",
    2: "ts",
    3: "val",
    4: "station",
    5: "category",
    6: "equipment",
    7: "uniformcode",
    8: "rate",
    9: "remark",
  };
  res.data.forEach((ele) => {
    let dateItem = {};
    for (let key in ele) {
      dateItem[map[key]] = ele[key];
    }
    dateItem.databaseName = databaseName;
    dateItem.tableName = tableName;
    newdata.push(dateItem);
  });
  // console.log(999999,newdata);
  tableData.value = newdata;
  // console.log('66b',tableData.value);
};

// 传递数据
const router = useRouter();
const dbclick = (a) => {
  // console.log(11111, a);
  const dbName = a.databaseName;
  const tbName = a.point;
  router.push({
    path: "/look/create",
    query: {
      databaseName: dbName,
      tableName: tbName,
    },
  });
};


/**table 开始 */
// const tableShowId = ref("");
const tableName = ref("");
const tableLoading = ref(false);
const tableData = ref([]);

/**submit */
const progress = ref(0);
const funWebSocket = () => {
  const webSocket = new WebSocket(`${socketURL}/ws/powerfitting/admin`);
  webSocket.onerror = () =>
    setTimeout(() => {
      funWebSocket();
    }, 2000);

  webSocket.onmessage = (event) => {
    const message = JSON.parse(event.data);
    if (message.code === 200) {
      progress.value = Number(message.data) * 100;
      if (progress.value === 100) {
        ElMessage.success("数据加载完成");
        funGetTree();
        progress.value = 0;
      }
    }
  };
};

const funSubmit = async (params) => {
  const res = await request.get("/power/prepare/data", { params: params });
  if (res.code === 200) {
    ElMessage.success(res.msg);
  }
};

funWebSocket();
/**mounted */
onMounted(() => {
  tableHeight.value = window.innerHeight - 260 + "px";
  excelHeight.value = window.innerHeight - 260 + "px";
  treeHeight.value = window.innerHeight - 260 + "px";
  window.addEventListener("resize", () => {
    tableHeight.value = window.innerHeight - 260 + "px";
    excelHeight.value = window.innerHeight - 260 + "px";
    treeHeight.value = window.innerHeight - 260 + "px";
  });
});
/**activated */
onActivated(() => {
  funGetTree();
});
</script>
<template>
  <div class="bg-white py-[10px] px-[10px] relative">
    <search-cop
      class="mb-[20px] shadow rounded-[6px] shadow-blue-500"
      @submit="funSubmit"
    >
    </search-cop>
    <div
      class="relative shadow rounded-[6px] shadow-blue-500 px-[10px] pt-[20px] pb-[10px]">
     
      <el-row :gutter="10">
        <el-col :span="5">
          <tree-cop
            :data="treeData"
            :height="treeHeight"
            @currentChange="funCurrentChange"
            @refresh="funGetTree"
            @node-click="treeNodeClick"
          >
          </tree-cop>
        </el-col>
       
        <el-col :span="19">
          <div>
            <el-scrollbar max-height="650px">

              <el-table
                :data="tableData"
                style="width: 100% ,height:800px"
                @cell-dblclick="dbclick"
              >

                <el-table-column prop="point" label="测点" align="center" width="200"/>
                <el-table-column
                  prop="description"
                  label="描述"
                  align="center"
                  width="200"
                />
                <el-table-column prop="ts" label="时间" align="center" width="200"/>
                <el-table-column prop="val" label="值" align="center" />
                <el-table-column prop="station" label="场站" align="center" />
                <el-table-column prop="category " label="类别" align="center" />
                <el-table-column
                  prop="equipment"
                  label="设备id"
                  align="center"
                />
                <el-table-column
                  prop="uniformcode"
                  label="统一识别码"
                  align="center"
                />
                <el-table-column prop="rate" label="倍率" align="center" />
                <el-table-column prop="remark" label="备注" align="center" />
              </el-table>
            </el-scrollbar>
            
          </div>
           <!-- <el-pagination layout="prev, pager, next" :total="1000" /> -->
        </el-col>
      </el-row>
    </div>


  </div>
</template>
