<template>
  <div>
    <div class="left-main" :class="[cardShow ? 'leavhide' : 'leavshow']">
      <div class="left-tabs">
        <div
          class="left-item"
          v-for="item in tabList"
          @click="itemSelect(item)"
        >
          <span :class="[item.id == selectId ? 'selectCss' : '']">
            {{ item.label }}</span
          >
        </div>
        <div class="leftIcon" @click="setCard">
          <img :src="cardShow ? leftIcon : rightIcon" />
        </div>
      </div>
      <div v-if="selectId == 1">
        <div class="left-select">
          <div>图层:</div>
          <el-select
            class="m-2 select"
            v-model="layerId"
            placeholder="Select"
            size="large"
            @change="selectLayer"
          >
            <el-option
              v-for="item in layerDate"
              :key="item.name"
              :label="item.layerName"
              :value="item.id"
            />
          </el-select>
        </div>
        <div>
          <el-button
            v-hasPermi="['ldmap:role:edit']"
            style="margin-left: 15px"
            type="success"
            @click="
              () => {
                emit('uploadShow');
              }
            "
          >
            <span style="color: #fff">上传航拍图</span>
          </el-button>
        </div>
        <el-table :data="layerslist" style=" height: calc(100vh - 230px);">
          <el-table-column type="index" width="55" label="序号" />
          <el-table-column prop="houseFloors" width="100" label="图层名称">
            <template #default="scope">
              {{ scope.row.layerName }}
            </template>
          </el-table-column>
          <el-table-column
            prop="geometryId"
            show-overflow-tooltip
            label="航拍文件"
          >
            <template #default="scope">
              {{
                scope.row.tiffUrl.substr(
                  scope.row.tiffUrl.lastIndexOf("/") + 1,
                  scope.row.tiffUrl.length
                )
              }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="unit">
            <template #default="scope">
              <el-tag
                class="mx-1"
                effect="dark"
                :type="scope.row.layerUrl ? 'success' : 'danger'"
              >
                {{ scope.row.layerUrl ? "已发布" : "待发布" }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="selectId == 2">
        <div class="loadStyle">
          <el-button
            type="success"
            color="rgb(255,0,0, 0.6)"
            @click="checkType('0')"
          >
            <span style="color: #fff">房屋（{{ house.length }}）</span>
          </el-button>
          <el-button
            type="warning"
            color="rgb(94,208,81, 0.6)"
            @click="checkType('1')"
            ><span style="color: #fff"
              >河流（{{ river.length }}）</span
            ></el-button
          >
          <el-button
            type="info"
            color="rgb(118,116,218, 0.6)"
            @click="checkType('2')"
            ><span style="color: #fff"
              >道路（{{ road.length }}）</span
            ></el-button
          >
        </div>
        <el-table
          :data="tableDate"
          ref="refTable"
          highlight-current-row
          @current-change="handleCurrentChange"
        >
          <el-table-column type="index" width="55" label="序号" />
          <el-table-column
            prop="households"
            width="55"
            label="户数"
            v-if="selectType == '0'"
          >
            <template #default="scope">
              {{ scope.row.households || "/" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="houseFloors"
            width="55"
            label="楼层"
            v-if="selectType == '0'"
          >
            <template #default="scope">
              {{ scope.row.houseFloors || "/" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="geometryId"
            label="识别ID"
            v-if="selectType != '0'"
          />
          <el-table-column label="类型" width="55" align="center" prop="unit">
            <template #default="scope">
              {{ selectType == 0 ? "房屋" : selectType == 1 ? "河流" : "道路" }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            prop="unit"
            v-if="selectType == '0'"
          >
            <template #default="scope">
              <el-button
                type="warning"
                :color="
                  scope.row.isExit
                    ? 'rgb(94,208,81, 0.6)'
                    : 'rgb(230,162,60, 0.6)'
                "
                size="small"
                @click="exitRecogn(scope.row)"
                ><span style="color: #fff">属性</span></el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="selectId == 3">
        <div class="chooseType">
          <div class="waterout">计算水量:{{ watertotal }}</div>
          <div class="type">
            <div class="selectInfo">
              <div class="info">产品:</div>
              <el-select
                class="m-2 select"
                v-model="deviceId"
                placeholder="Select"
                @change="selectDevice"
              >
                <el-option
                  v-for="item in deviceDist"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </div>
            <div class="selectInfo">
              <div class="info" style="margin-left: 10px; width: 35px">
                水量:
              </div>
              <el-select
                class="m-2 select"
                v-model="waterId"
                placeholder="Select"
                style="width: 80px"
              >
                <el-option
                  v-for="item in deviceWater"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </div>
          </div>

          <div class="selectInfo">
            <div class="info" style="width: 65px">出水标准 :</div>
            <el-select
              class="m-2 select"
              v-model="waterLevel"
              placeholder="Select"
            >
              <el-option
                v-for="item in standard"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <!--
        <el-table
          :data="lineNowData"
          highlight-current-row
          style="height: calc(100vh - 258px)"
          @current-change="handleCurrentChange"
        >
          <el-table-column type="index" width="80" label="序号" />
          <el-table-column prop="label" label="管径" tooltip />
          <el-table-column label="类型" align="center" prop="unit">
            <template #default="scope">
              {{
                scope.row.type == "h"
                  ? "房屋"
                  : scope.row.type == "s"
                  ? "设备"
                  : "井"
              }}
            </template>
          </el-table-column>
        </el-table>
        -->
        <el-tree-v2
          :data="treeData"
          :props="props"
          show-checkbox
          :height="treeHeight"
          :default-checked-keys="defaultCheckedKeys"
          :default-expanded-keys="defaultExpandedKeys"
          @check-change="onCheckChange"
        >
          <template #default="{ node }">
            <div style="flex: 1" @click="chooseLineItem(node)">
              <div v-if="node.children">
                {{ node.label }}管道类型({{ node.children.length }})
              </div>
              <div v-else style="display: flex; justify-content: space-between">
                <div>{{ node.label }}{{ node.distance }}</div>
                <div style="margin-right: 20px">
                  <el-icon :color="getColor(node)" @click="exitLine(node)"
                    ><EditPen
                  /></el-icon>
                </div>
              </div>
            </div>
          </template>
        </el-tree-v2>
      </div>

      <div class="legend" v-if="selectId == 3">
        <div>图例</div>
        <div class="line-legend">布线管径颜色</div>
        <el-row>
          <el-col :span="12" class="legend-col" v-for="item in legendlineData">
            <div style="width: 60px; text-align: right">{{ item.label }}：</div>
            <div
              :style="{
                background:
                  'rgb(' +
                  item.color[0] +
                  ',' +
                  item.color[1] +
                  ',' +
                  item.color[2] +
                  ')',
              }"
              class="item"
            ></div>
          </el-col>
        </el-row>
        <div class="line-legend">点位颜色</div>
        <div style="display: flex; padding: 5px 15px">
          <div :span="24" class="legend-point" v-for="item in legendPointeData">
            <div style="text-align: right">{{ item.label }}:</div>
            <div
              :style="{
                background:
                  'rgb(' +
                  item.color[0] +
                  ',' +
                  item.color[1] +
                  ',' +
                  item.color[2] +
                  ')',
              }"
              class="item-point"
            ></div>
          </div>
        </div>
      </div>
      <div v-if="selectId == 4">
        <log></log>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import leftIcon from "@map/assets/tool/left.png";
import rightIcon from "@map/assets/tool/right.png";
import useMapDataStore from "@map/store/modules/mapData";
import useDistStore from "@map/store/modules/dist";
import emitter from "@map/utils/emitter";
import log from "./component/log";
import { toRaw } from "vue";
const { proxy } = getCurrentInstance();
const emit = defineEmits(["changeExit", "lineExit", "uploadShow"]);
let mapdata = useMapDataStore();
const {
  house,
  road,
  river,
  lineArray,
  pointArray,
  setLineStyle,
  watertotal,
  layerId,
  layerName,
  checkedLegend,
} = storeToRefs(mapdata);
const tableDate = ref();
const lineDate = ref([]);
const legendlineData = ref([]);
const legendPointeData = ref([]);
const selectType = ref(0);
const value1 = ref([]);
const $ldMap = inject("$ldMap"); // 调用全局变量
const treeHeight = ref("");
treeHeight.value = window.innerHeight - 258;
const layerslist = ref();
const layerDate = ref([]);
const props = {
  value: "id",
  label: "label",
  children: "children",
};
const treeData = ref();
onMounted(() => {
  window.onresize = () => {
    treeHeight.value = window.innerHeight - 258;
  };
  tableDate.value = house.value;
  getLayerList().then(() => {
      let firstData =layerslist.value[0]
      selectLayer(firstData.id);
      getlegend();


    });


  emitter.on("loadLayer", () => {
    getLayerList();
  });
  emitter.on("polyon", (e) => {
    if (e && e.action != 2 && selectId.value == 2) {
      try {
        proxy.$refs["refTable"].setCurrentRow(e);
        tableDate.value.forEach((item, index) => {
          if (item == e) {
            tableScrollToRow(proxy.$refs["refTable"], index + 1, false);
          }
        });
      } catch (error) {
        console.log(error);
      }
    }
  });
});
//定位到表格某一行

function tableScrollToRow(tableElement, rowindex, isprecise = false) {
  const theTableRows = tableElement.$el.querySelectorAll(
    ".el-table__body tbody .el-table__row"
  );
  let scrollTop = 0;
  for (let i = 0; i < theTableRows.length; i++) {
    if (i === rowindex) {
      break;
    }
    scrollTop += theTableRows[i].offsetHeight;
    if (!isprecise) {
      scrollTop *= rowindex - 1;
      break;
    }
  }
  tableElement.scrollTo(0, scrollTop);
}
const getColor = (node) => {
  node = node.data;
  let flag =
    node.startAltitude ||
    node.startElevation ||
    node.endAltitude ||
    node.endElevation;
  return flag == true ? "rgb(64,158,255, 0.8)" : "rgb(251,213,2, 0.8)";
};
//获取图层列表
const getLayerList = () => {
  return new Promise((resolve, reject) => {
    mapdata.getMylayerList().then((res) => {
      layerslist.value = res.data;
      layerDate.value = res.data.filter((item) => item.layerUrl);
      resolve();
    });
  });
};

let dist = useDistStore();
const { deviceDist, standard } = storeToRefs(dist);
const deviceId = ref("");
const waterId = ref("");
const waterLevel = ref(standard.value[0].id);
const deviceWater = ref([]);

deviceId.value = deviceDist.value[0].id;
deviceWater.value = deviceDist.value[0].waterList;
waterId.value = deviceWater.value[0].id;
const selectDevice = (e) => {
  deviceDist.value.forEach((item) => {
    if (e == item.id) {
      deviceWater.value = item.waterList;

      waterId.value = item.waterList[0].id;
    }
  });
};

const selectId = ref(1);
const itemSelect = (item) => {
  selectId.value = item.id;
};
const getlegend = () => {
  mapdata.getSetlineStyle().then((e) => {
    console.log(e);
    let point = e.point,
      line = e.line;
    for (let i in line) {
      legendlineData.value.push(line[i]);
    }
    for (let i in point) {
      if (point[i].visible) {
        legendPointeData.value.push(point[i]);
      }
    }
  });
};

const handleCurrentChange = (row) => {
  row && $ldMap.lighHightLayer(row.geometryId);
};
function exitRecogn(e) {
  emit("changeExit", e);
}
function selectLayer(e) {
  console.log(e);
  layerslist.value.forEach((item) => {
    if (item.id == e) {
      console.log(item);
      layerId.value = item.id;
      layerName.value = item.layerName
      $ldMap.initMap(item.coordinateSystem.epsg).then((e) => {

        $ldMap.addLayer({
        url: item.layerUrl,
        id: e,
      });


});

    }
  });
}

watch([house, river, road], (newData) => {
  selectId.value != 4 && (selectId.value = 2);
  tableDate.value = newData[selectType.value];
});
const lineNowData = ref([]);
watch(lineArray, (val) => {
  selectId.value = 3;
  lineDate.value = val;
  lineNowData.value = lineDate.value;

  showLineArrMap(lineNowData.value);
});

const defaultCheckedKeys = ref([]);
const defaultExpandedKeys = ref([1]);
function setTreeData(lineData) {
  let data = [
    {
      id: "1",
      label: "所有",
      children: [],
    },
  ];
  let list = {};
  lineData.forEach((res) => {
    if (!list[res.styleId]) {
      list[res.styleId] = {
        id: res.styleId,
        label: res.styleId != 999 ? res.styleId : "其他",
        children: [],
      };
    }

    list[res.styleId]["children"].push({
      ...res,
      // label:res.styleId+'管道'+'   长度：'+res.length+'米',
      label:
        res.code.substring(0, 5) + "管道" + "   长度：" + res.length + "米",
    });
    defaultCheckedKeys.value.push(res.id);
  });
  for (let i in list) {
    data[0].children.push(list[i]);
  }
  treeData.value = data;
}
function exitLine(node) {
  console.log(node.data);
  emit("lineExit", node.data);
}
function chooseLineItem(e) {
  if (e.level == 3) {
    console.log(e.data.id);
    $ldMap.chooseLineByid(e.data.id);
  }
}
watch(checkedLegend, (val) => {
  let data = new Set(val);

  lineNowData.value = lineDate.value.filter((res) => {
    if (data.has(res.styleId)) {
      return res;
    }
  });
  showLineArrMap(lineNowData.value);
});

async function showLineArrMap(data) {
  $ldMap.removePoint();
  $ldMap.removeLine()
  let treeData = await $ldMap.addDefaultByline(data);
  setTreeData(treeData);
}

const value = ref<String>(1);
//修改管线类型
function exitLineMaterial(val) {
  let tree = JSON.parse(JSON.stringify(treeData.value));
  let isAdd = false;
  let isNullIndex = -1;
  tree[0].children.forEach((item, index) => {
    if (item.id == val.diameter) {
      isAdd = true;
    }
    if (item.id == val.styleId) {
      for (let i = 0; i < item.children.length; i++) {
        if (item.children[i].id == val.id) {
          item.children.splice(i, 1);
          if (item.children.length == 0) {
            isNullIndex = index;
          }
        }
      }
    }
  });
  isNullIndex != -1 && tree[0].children.splice(isNullIndex, 1);
  val.styleId = val.diameter;
  if (isAdd) {
    tree[0].children.forEach((item, index) => {
      if (item.id == val.diameter) {
        item.children.push(val);
      }
    });
  } else {
    let obj = {
      id: val.styleId,
      label: val.styleId != "999" ? val.styleId : "其他",
      children: [val],
    };

    let i;
    for (i = 0; i < tree[0].children.length; i++) {
      if (val.styleId < tree[0].children[i].id) {
        tree[0].children.splice(i, 0, obj);
        break;
      }
    }
    if (i == tree[0].children.length) {
      tree[0].children.push(obj);
    }

    defaultCheckedKeys.value.push(val.styleId);
  }

  treeData.value = tree;
  $ldMap.exitLineByVal(val);
}
defineExpose({ exitLineMaterial });

const cardShow = ref(true);
const setCard = function () {
  cardShow.value = !cardShow.value;
};

function checkType(type) {
  selectType.value = type;
  tableDate.value =
    type == "0" ? house.value : type == "1" ? river.value : road.value;
}
const getTableHeight = computed<string>(() => {
  let winheight = window.innerHeight - 60 - 60 - 45;
  return winheight;
});
function onCheckChange(e, checked) {
  console.log(e, checked);
  if (!e.children) {
    $ldMap.getPoylineLayer(e.id, checked);
  } else {
    e.children.forEach((item) => {
      onCheckChange(item, checked);
    });
  }
}
const tabList = reactive([
  {
    label: "图层信息",
    id: "1",
  },
  {
    label: "算法识别",
    id: "2",
  },
  {
    label: "布线识别",
    id: "3",
  },
  {
    label: "运行日志",
    id: "4",
  },
]);
</script>

<style scoped lang="scss">
:deep(.ivu-tabs-nav .ivu-tabs-tab) {
  padding: 8px 5px !important;
}
:deep(.el-table tr) {
  background: transparent;
  color: #fff;
}

:deep(.el-table tr):hover {
  background: transparent;
}

:deep(.el-table__body tr.current-row > td.el-table__cell) {
  background-color: rgba(27, 124, 125, 0.5) !important;
}
:deep(
    .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell
  ) {
  background: rgb(184, 224, 250, 0.5) !important;
}
:deep(.el-table th.el-table__cell) {
  background: transparent;
}

:deep(.el-table__row) {
  &:hover {
    background: rgb(184, 224, 250);
    border: 1px solid #313463;
  }
}

.loadStyle {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}
.leftIcon {
  width: 50px;
  height: 48px;
  box-shadow: 0 0 20px 10px rgba(22, 143, 181, 0.5) inset;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  top: 0px;
  float: left;
  right: -50px;
  cursor: pointer;

  img {
    height: 30px;
  }
}
.selectCss {
  color: rgb(22, 143, 181);
  font-weight: bold;
}
.left-main {
  width: 18%;
  position: fixed;
  z-index: 1;
  top: 80px;

  height: calc(100vh - 60px);
  background: rgb(0, 26, 61, 0.5);
}
:deep(.el-tree-node:focus > .el-tree-node__content) {
  background: transparent;
}
.left-item {
  cursor: pointer;
}
.left-tabs {
  display: flex;
  color: #fff;
  box-shadow: 0 0 20px 10px rgba(22, 143, 181, 0.5) inset;
  justify-content: space-between;
  padding: 10px;
}
.chooseType {
  color: #fff;
  padding: 10px;
  font-size: 14px;
  .type {
    display: flex;
  }
}
.waterout {
  text-align: center;
  color: red;
  font-weight: bold;
  font-size: 16px;
}
.selectInfo {
  margin-top: 5px;
  display: flex;
  .info {
    width: 55px;
    margin-top: 5px;
    margin-right: 5px;
  }
}
.legend {
  color: #fff;
  text-align: center;
  width: 200px;
  height: 200px;
  right: -200px;
  position: absolute;
  bottom: 20px;
  background: rgb(0, 26, 61, 0.5);
  box-shadow: 3px 0px 2px 3px rgba(22, 143, 181, 0.5);
  .line-legend {
    text-align: left;
    font-size: 14px;
    color: #fff;
    margin-top: 5px;
  }
  .legend-col {
    display: flex;
    font-size: 12px;
    padding-left: 6px;
    margin-top: 4px;
  }
  .legend-point {
    display: flex;
    flex: 1;
    font-size: 12px;
    justify-content: center;
  }
  .item-point {
    width: 15px;
    height: 15px;
    border-radius: 50%;
    margin: 3px 5px;
  }
  .item {
    width: 31px;
    height: 13px;
    border-radius: 3px;
    margin-top: 3px;
  }
}
.left-select {
  color: #fff;
  display: flex;
  padding: 10px;
  line-height: 35px;
  .select {
    flex: 1;
  }
  :deep(.el-input--large) {
    height: 35px;
  }
  :deep(.el-select .el-input__wrapper) {
    background: rgb(0, 26, 61, 0.5);
    color: #fff;
  }

  :deep(.el-select .el-input__inner) {
    color: #fff;
  }
}
:deep(.el-tag.el-tag--info) {
  background: rgb(0, 26, 61, 0.5);
  color: #fff;
}
:deep(.el-select__tags) {
}
.leavhide {
  animation: fadeshow 1s ease forwards;
}
.leavshow {
  animation: fadenum 1s ease forwards;
}
@keyframes fadenum {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-100%);
  }
}
.el-tree {
  background: transparent;
  color: #fff;
  text-align: left;
}
:deep(.el-tree-node__content:hover) {
  background: transparent;
}
:deep(.el-checkbox) {
  width: auto !important;
}
@keyframes fadeshow {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0%);
  }
}
</style>
