<script setup name="prepare">
import treeCop from "@/components/tree.vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  onMounted,
  ref,
  reactive,
  onActivated,
  nextTick,
  onUnmounted,
} 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'",
    "log",
  ];

  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;
      }
    }
  }
  sessionStorage.setItem(
    "myData",
    JSON.stringify({ nxxy: databaseName, nxxy1: tableName })
  );
  //拿取表格数据
  const res = await request.post(
    "/rest/sql",
    `SELECT tbname as point,description,ts,val,station,category,facility,uniformcode,rate,remark FROM ${myData.nxxy}.${myData.nxxy1} 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);

  if (stationList.value == "") {
    const ros = await request.post(
      "/rest/sql",
      `SELECT DISTINCT station FROM ${databaseName}.${tableName}`
    );
    console.log(6666666666666666, ros);
    let nbdata = [];
    ros.data.forEach((ele) => {
      ele?.[0] && nbdata.push(ele[0]);
    });
    // console.log(55555,nbdata);

    stationList.value = nbdata;

    console.log(7777777777, stationList.value);
    if (stationList.value.length) {
      queryForm.station = stationList.value[0];
    }
  }
};

const queryForm = reactive({
  station: "",
  tbname: "",
  description: "",
  uniformcode: "",
});

const stationList = ref([]);

const funStationChange = (val) => {
  console.log(111111111111, val);
  queryForm.station = val;
};
let myData = JSON.parse(sessionStorage.getItem("myData"));
// console.log(myData.nxxy);

const nbsubmit = async () => {
  if (queryForm.tbname == "" || queryForm.station == "") {
    ElMessage.error("测点不能为空");
  } else {
    const res = await request.post(
      "/rest/sql",
      `SELECT tbname as point,description,ts,val,station,category,facility,uniformcode,rate,remark FROM ${
        myData.nxxy
      }.${myData.nxxy1}
   where ${
     queryForm.station === "all"
       ? ""
       : "station='" + queryForm.station + "' and"
   } tbname like '%${queryForm.tbname}%' ${
        queryForm.description === ""
          ? ""
          : "and description like '%" + queryForm.description + "%'"
      } ${
        queryForm.uniformcode === ""
          ? ""
          : "and uniformcode=" + queryForm.uniformcode
      } limit ${pagenumber.value - 1}, ${pagenb.value}
   `
    );
    console.log(666666666666, res);
    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;
  }
};

// 传递数据
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,
    },
  });
};

const tableName = ref("");
const tableLoading = ref(false);
const tableData = ref([]);

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

let pagenumber = ref(1); //当前的页数
let pagenb = ref(99); //当前的条数

console.log(666666, pagenumber.value);
const left1 = async () => {
  pagenumber.value -= 1;

  let nbfist = (pagenumber.value - 1) * 100;
  pagenb.value = nbfist + 99;
  const res = await request.post(
    "/rest/sql",
    `SELECT tbname as point,description,ts,val,station,category,facility,uniformcode,rate,remark FROM ${myData.nxxy}.${myData.nxxy1} limit ${nbfist}, ${pagenb.value};`
  );
  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];
    }
    newdata.push(dateItem);
  });
  tableData.value = newdata;
};

const right1 = async () => {
  pagenumber.value += 1;
  let nbfist = (pagenumber.value - 1) * 100;
  pagenb.value = nbfist + 99;
  const res = await request.post(
    "/rest/sql",
    `SELECT tbname as point,description,ts,val,station,category,facility,uniformcode,rate,remark FROM ${myData.nxxy}.${myData.nxxy1} limit ${nbfist}, ${pagenb.value};`
  );

  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];
    }
    newdata.push(dateItem);
  });
  tableData.value = newdata;
};

//  const timer = ref(null);

const startTimer = async () => {
  if (queryForm.station?.length) {
    const res = await request.post(
      "/rest/sql",
      `select tbname as point,description,ts,last_row(*) as val,station,category,facility,uniformcode,rate,remark from ${myData.nxxy}.${myData.nxxy1} where tbname in ('slfj_nx_gd_qsf_fj_p3_l8_083_ai0100','slfj_nx_gd_qsf_fj_p3_l8_083_ai0102','slfj_nx_gd_qsf_fj_p3_l8_083_ai0103','slfj_nx_gd_qsf_fj_p3_l8_083_ai0104','slfj_nx_gd_qsf_fj_p3_l8_083_ai0105','xsfjjsfw_nx_gd_xsf_fj_p1_l2_013_ci0097','sbqjsfw_nx_gd_sbqf_fj_p1_l3_023_ci0668','sbqjsfw_nx_gd_sbqf_fj_p1_l3_023_ci0669','plsj2_nx_gd_plg_dd_p1_l6_026_ai0120','plsj2_nx_gd_plg_dd_p1_l6_026_ai0121','plsj2_nx_gd_plg_dd_p1_l6_026_ai0122',
      'plsj2_nx_gd_plg_dd_p1_l6_026_ai0124','plsj2_nx_gd_plg_dd_p1_l6_026_ai0125','plsj2_nx_gd_plg_dd_p1_l6_026_ai0127','plsj2_nx_gd_plg_dd_p1_l6_026_ai0128','plsj2_nx_gd_plg_dd_p1_l6_026_ai0129','sbqjsfw_nx_gd_sbqf_fj_p1_l3_023_ci0670','plsj2_nx_gd_plg_dd_p1_l6_026_ai0136','plsj2_nx_gd_plg_dd_p1_l6_026_ai0137','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0559','plsj2_nx_gd_plg_dd_p1_l6_026_ai0141','plsj2_nx_gd_plg_dd_p1_l6_026_ai0144','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0562','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0563','slfj_nx_gd_qsf_fj_p3_l8_083_ai0183','xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0014','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0536','slfj_nx_gd_qsf_fj_p3_l8_083_ai0184',
      'slfj_nx_gd_qsf_fj_p3_l8_083_ai0185','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0538','slfj_nx_gd_qsf_fj_p3_l8_083_ai0186','xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0019','slfj_nx_gd_qsf_fj_p3_l8_083_ai0189','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0540','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0541','slfj_nx_gd_qsf_fj_p3_l8_083_ai0190','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0543','xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0022','slfj_nx_gd_qsf_fj_p3_l8_083_ai0191','xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0023','slfj_nx_gd_qsf_fj_p3_l8_083_ai0192','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0546','slfj_nx_gd_qsf_fj_p3_l8_083_ai0172','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0547','xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0004','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0548','slfj_nx_gd_qsf_fj_p3_l8_083_ai0174',
      'xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0006','xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0009','slfj_nx_gd_qsf_fj_p3_l8_083_ai0178','slfj_nx_gd_qsf_fj_p3_l8_083_ai0179','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0550','xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0010','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0554','slfj_nx_gd_qsf_fj_p3_l8_083_ai0180','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0556','xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0012','slfj_nx_gd_qsf_fj_p3_l8_083_ai0181','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0557','slfj_nx_gd_qsf_fj_p3_l8_083_ai0182','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0514','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0515','slfj_nx_gd_qsf_fj_p3_l8_083_ai0163','slfj_nx_gd_qsf_fj_p3_l8_083_ai0164','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0517','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0518','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0519','slfj_nx_gd_qsf_fj_p3_l8_083_ai0166','slfj_nx_gd_qsf_fj_p3_l8_083_ai0167','slfj_nx_gd_qsf_fj_p3_l8_083_ai0168','slfj_nx_gd_qsf_fj_p3_l8_083_ai0169','plsj2_nx_gd_plg_dd_p1_l6_026_ai0102','plsj2_nx_gd_plg_dd_p1_l6_026_ai0103','plsj2_nx_gd_plg_dd_p1_l6_026_ai0105','plsj2_nx_gd_plg_dd_p1_l6_026_ai0106','plsj2_nx_gd_plg_dd_p1_l6_026_ai0107','plsj2_nx_gd_plg_dd_p1_l6_026_ai0108',
      'plsj2_nx_gd_plg_dd_p1_l6_026_ai0109','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0524','slfj_nx_gd_qsf_fj_p3_l8_083_ai0150','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0525','slfj_nx_gd_qsf_fj_p3_l8_083_ai0152','slfj_nx_gd_qsf_fj_p3_l8_083_ai0153','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0529','slfj_nx_gd_qsf_fj_p3_l8_083_ai0157','slfj_nx_gd_qsf_fj_p3_l8_083_ai0158','plsj2_nx_gd_plg_dd_p1_l6_026_ai0110','slfj_nx_gd_qsf_fj_p3_l8_083_ai0159','plsj2_nx_gd_plg_dd_p1_l6_026_ai0112','plsj2_nx_gd_plg_dd_p1_l6_026_ai0114','plsj2_nx_gd_plg_dd_p1_l6_026_ai0117','plsj2_nx_gd_plg_dd_p1_l6_026_ai0119','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0530','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0532','sbqfjjsfw_nx_gd_sbqf_fj_p1_l2_015_ci0533','slfj_nx_gd_qsf_fj_p3_l8_083_ai0160','xhgfjsfw_nx_gd_xhg_gf_p1_l3_029_ci0058','slfj_nx_gd_qsf_fj_p3_l8_083_ai0145','slfj_nx_gd_qsf_fj_p3_l8_083_ai0146') group by tbname;`
    );
    // console.log(res);
    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];
      }
      newdata.push(dateItem);
    });
    tableData.value = newdata;
  }else{
    clearInterval()
  }
};

// 实时刷新数据
setInterval(() => {
  startTimer();
  console.log("刷新");
}, 3000);


/**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";
  });
});
onUnmounted(() => {
  // stopsetInterval();
});

/**activated */
onActivated(() => {
  funGetTree();
});
</script>
<template>
  <div class="bg-white py-[10px] px-[10px] relative">
    <div
      class="pl-[20px] flex items-center h-[80px] relative mb-[20px] shadow rounded-[6px] shadow-blue-500"
    >
      <el-form class="" :inline="true" :model="queryForm">
        <el-form-item label="场站" class="!mb-0">
          <el-select
            v-model="queryForm.station"
            class="w-[150px]"
            @change="funStationChange"
          >
            <el-option
              label="全选"
              value="all"
              v-if="queryForm.station?.length"
            />
            <el-option
              v-for="item in stationList"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测点" class="!mb-0">
          <el-input v-model="queryForm.tbname" />
        </el-form-item>
        <el-form-item label="描述" class="!mb-0">
          <el-input v-model="queryForm.description" />
        </el-form-item>
        <el-form-item label="统一识别码" class="!mb-0">
          <el-input v-model="queryForm.uniformcode" />
        </el-form-item>
        <el-form-item class="!mb-0">
          <el-button type="primary" @click="nbsubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div
      class="relative shadow rounded-[6px] shadow-blue-500 px-[10px] pt-[20px] pb-[10px]"
    >
      <el-row :gutter="10">
        <el-col :span="4">
          <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:650px"
                @cell-dblclick="dbclick"
                @selection-change="handleSelectionChange"
              >
             
                <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>
          <div v-if="tableData?.length">
            <el-button @click="left1" :disabled="pagenumber <= 1"
              >上一页</el-button
            >
            <span class="pl-2">{{ pagenumber }}</span>
            <el-button @click="right1" class="ml-2">下一页</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
