<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 } from "vue";

import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from "@element-plus/icons-vue";

import request from "@/api/axios.js";
import { baseURL, socketURL } from "@/api/axios.js";
import config from "@api/config.js";
import { exportMethod } from "@/api/utils.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 }) => {
  // console.log("nbnbnbnbnbnbn", current);
  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 ${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 ros = await request.post(
    "/rest/sql",
    `SELECT DISTINCT station FROM ${databaseName}.${tableName}`
  );
  console.log('69966', 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;
};

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 ${
        tableData.value[0].databaseName
      }.${tableData.value[0].tableName}
   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 - 1}
   `
    );

    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('nbnbnb',newdata);
    });
    console.log(999999, newdata);
    tableData.value = newdata;
  }
};

// 下载建点
// const jianbao = async (urlKey) => {
//   const requestUrl = config[urlKey];
//   console.log('zxzxzx',requestUrl);
//   let el = document.createElement("a");
//   el.href = `${requestUrl}/taos/template`;
//   el.download = "";
//   el.target = "_blank";
//   document.body.appendChild(el);
//   el.click();
//   document.body.removeChild(el);
// };


//导出Excel
const exportDepReceRank = () => {

  // const requestUrl = config[urlKey];
  // console.log('nnnnnnnnn');

  let myObj = {
    method: "get",
    url: `http://192.168.10.9:5087/taos/template`,
    fileName: "导出的Excel",
  };
  exportMethod(myObj);
};

const uploadRef = ref();
const fslist = async (urlKey) => {
  const requestUrl = config[urlKey];
  const res = await request.post(`${requestUrl}/taos/uploadexcel`);
  console.log("nbnbnbnbn", res);
  
};

// 路由传递数据
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);
let 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); //当前的页数
const pagenb = ref(100); //当前的条数
let myData = JSON.parse(sessionStorage.getItem("myData"));

console.log("hahhah", pagenumber.value);
const left1 = async () => {
  pagenumber.value -= 1;
  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];
    }
    newdata.push(dateItem);
  });
  tableData.value = newdata;
};
const right1 = async () => {
  pagenumber.value += 1;
  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];
    }
    newdata.push(dateItem);
  });
  tableData.value = newdata;
};

const formlist = reactive({
  cedian: "",
  miaoshu: "",
  changzhan: "",
  leibie: "",
  shebeiid: "",
  shibiema: "",
  beilv: "",
  beizhu: "",
});


let dialogFormVisible = ref(false);
let editIndex = ref(-1);
//编辑
const handleEdit = (index) => {
  dialogFormVisible.value = true;
  editIndex.value = index;
  formlist.cedian = tableData.value[editIndex.value].point;
  formlist.miaoshu = tableData.value[editIndex.value].station;
  formlist.changzhan = tableData.value[editIndex.value].description;
  formlist.leibie = tableData.value[editIndex.value].category;
  formlist.shebeiid = tableData.value[editIndex.value].equipment;
  formlist.shibiema = tableData.value[editIndex.value].uniformcode;
  formlist.beilv = tableData.value[editIndex.value].rate;
  formlist.beizhu = tableData.value[editIndex.value].remark;
};

const queren = () => {
  dialogFormVisible.value = false;
  tableData.value[editIndex.value].point = formlist.cedian;
  tableData.value[editIndex.value].station = formlist.miaoshu;
  tableData.value[editIndex.value].description = formlist.changzhan;
  tableData.value[editIndex.value].category = formlist.leibie;
  tableData.value[editIndex.value].equipment = formlist.shebeiid;
  tableData.value[editIndex.value].uniformcode = formlist.shibiema;
  tableData.value[editIndex.value].rate = formlist.beilv;
  tableData.value[editIndex.value].remark = formlist.beizhu;
};

//删除
const handleDelete = (index) => {
  editIndex.value = index;
  tableData.value.splice(editIndex.value, 1);
};

/**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";
  });

  console.log("asasa", config);
});

/**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>
      <el-upload
        ref="upload"
        class="upload-demo"
        action="http://192.168.10.9:5087/taos/uploadexcel"
        :limit="1"
        :on-exceed="handleExceed"
        :auto-upload="false"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
      </el-upload>

      <el-form-item class="!mb-0 ml-5">
        <el-button @click="fslist('redisURL')" type="success">上传</el-button>
      </el-form-item>
      <el-form-item class="!mb-0 ml-5">
        <el-button @click="exportDepReceRank" type="primary"
          >下载建点、修改点模板</el-button
        >
      </el-form-item>
    </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"
              >
                <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-column label="操作" width="200">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      :icon="Edit"
                      circle
                      @click="handleEdit(scope.$index, scope.row)"
                    />

                    <el-button
                       type="danger"
                       :icon="Delete"
                       circle
                      @click="handleDelete(scope.$index, scope.row)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-scrollbar>
          </div>

          <el-button @click="left1" :disabled="pagenumber <= 1"
            >上一页</el-button
          >
          <span class="pl-2"> {{ pagenumber }} </span>
          <el-button @click="right1">下一页</el-button>
        </el-col>
      </el-row>
    </div>

    <el-dialog v-model="dialogFormVisible">
      <el-form :model="formlist">
        <el-form-item label="测点">
          <el-input v-model="formlist.cedian" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formlist.miaoshu" />
        </el-form-item>
        <el-form-item label="场站">
          <el-input v-model="formlist.changzhan" />
        </el-form-item>
        <el-form-item label="类别">
          <el-input v-model="formlist.leibie" />
        </el-form-item>
        <el-form-item label="设备id">
          <el-input v-model="formlist.shebeiid" />
        </el-form-item>
        <el-form-item label="统一识别码">
          <el-input v-model="formlist.shibiema" />
        </el-form-item>
        <el-form-item label="倍率" v-model="formlist.beilv">
          <el-input v-model="formlist.beilv" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formlist.beizhu" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="queren"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
