<template>
  <div class="left-main" :class="[cardShow ? 'leavhide' : 'leavshow']">
    <div class="leftIcon" @click="setCard">
      <img :src="cardShow ? rightIcon : leftIcon" />
    </div>
    <div class="left-tabs">
      <div class="left-item" @click="lineFirst = !lineFirst">
        <img
          alt="算法识别"
          :class="[lineFirst ? 'activeImg' : '']"
          :src="upIcon"
        />
        特征物识别
      </div>
      <transition>
        <div class="item-data" v-if="lineFirst">
          <el-button type="primary" @click="emitFind">开始识别</el-button>

          <!-- <el-button
              type="info"
              color="rgb(8, 240, 36, 0.6)"
              @click="verificationChange()"
              ><span style="color: #fff">数据核验</span></el-button> -->

          <el-button
            v-hasPermi="['ldmap:role:edit']"
            type="info"
            color="rgb(18, 180, 106, 0.6)"
            :disabled="recognition"
            @click="setPolygonData"
            ><span style="color: #fff">特征物保存</span></el-button
          >
          <div class="loadStyle">
            <el-button
              v-hasPermi="['ldmap:role:edit']"
              type="success"
              :disabled="recognition"
              color="rgb(255,0,0, 0.6)"
              @click="addPolygon('House')"
              ><span style="color: #fff">新增房屋</span></el-button
            >
            <el-button
              v-hasPermi="['ldmap:role:edit']"
              type="warning"
              color="rgb(94,208,81, 0.6)"
              :disabled="recognition"
              @click="addPolygon('River')"
              ><span style="color: #fff">新增河流</span></el-button
            >
            <el-button
              v-hasPermi="['ldmap:role:edit']"
              type="info"
              :disabled="recognition"
              color="rgb(118,116,218, 0.6)"
              @click="addPolygon('Road')"
              ><span style="color: #fff">新增道路</span></el-button
            >
            <el-button
              v-hasPermi="['ldmap:role:edit']"
              type="info"
              color="rgb(8, 240, 36, 0.6)"
              :disabled="recognition"
              @click="addPointDevice()"
              ><span style="color: #fff">新增站点</span></el-button
            >
          </div>

          <div style="margin-top: 10px">
            <el-button
              v-hasPermi="['ldmap:role:edit']"
              type="info"
              color="rgb(28, 140, 196, 0.6)"
              :disabled="recognition"
              @click="cutPolygon()"
              ><span style="color: #fff">切割特征物</span></el-button
            >
            <el-button
            v-hasPermi="['ldmap:role:edit']"
            type="info"
            color="rgb(128, 40, 96, 0.6)"
            :disabled="recognition"
            @click="elevationPolygon()"
            ><span style="color: #fff">

             <template v-if="!isShow">展示</template>
             <template v-else> 关闭</template>道路高程</span></el-button
          >
          </div>
          <div style="margin-top: 10px">
            <el-button
              v-hasPermi="['ldmap:role:edit']"
              :disabled="recognition"
              type="info"
              color="rgb(180, 100, 166, 0.6)"
              @click="exportPng()"
              ><span style="color: #fff">导 出</span></el-button
            >
            <el-button
            v-hasPermi="['ldmap:role:edit']"
            :disabled="recognition"
            type="info"
            color="rgb(180, 100, 6, 0.6)"
            @click="exportCad()"
            ><span style="color: #fff">导 出 Cad</span></el-button
          >
          </div>

        </div>
      </transition>
    </div>
    <div class="left-tabs">
      <div class="left-item" @click="lineSecond = !lineSecond">
        <img alt="官网布线" :src="lineSecond ? upIcon : downIcon" />

        管网布线
      </div>

      <div v-if="lineSecond" class="item-data">
        <el-button type="primary" @click="emitLine">开始布线</el-button>
        <el-button
        v-hasPermi="['ldmap:role:edit']"
        type="info"
        :disabled="pipeline"
        color="rgb(18, 180, 106, 0.6)"
        @click="optimizeMaxLength"
        ><span style="color: #fff">检修井优化</span></el-button
      >
        <!-- <el-button
          v-hasPermi="['ldmap:role:edit']"
          type="info"
          :disabled="pipeline"
          color="rgb(18, 180, 106, 0.6)"
          @click="optimizePoline"
          ><span style="color: #fff">检修井优化</span></el-button
        > -->
        <el-button
          v-hasPermi="['ldmap:role:edit']"
          type="info"
          :disabled="pipeline"
          color="rgb(18, 180, 106, 0.6)"
          @click="setPolineData"
          ><span style="color: #fff">管线数据保存</span></el-button
        >

        <div style="margin-top: 10px">
          <el-button
            v-hasPermi="['ldmap:role:edit']"
            type="primary"
            :disabled="pipeline"
            color="rgb(255,0,0, 0.6)"
            @click="addPointBy('h')"
            ><span style="color: #fff">新增房屋点</span>
          </el-button>
          <el-button
            v-hasPermi="['ldmap:role:edit']"
            type="primary"
            :disabled="pipeline"
            color="rgb(7, 253, 253, 0.6)"
            @click="addPointBy('x')"
            ><span style="color: #fff">新增检修井</span>
          </el-button>
        </div>
        <div style="margin-top: 10px">
          <el-button
            color="rgb(152, 51, 147, 0.6)"
            :disabled="pipeline"
            v-hasPermi="['ldmap:role:edit']"
            @click="addLine('once')"
          >
            <span style="color: #fff">新增管线</span>
          </el-button>
          <el-button
            color="rgb(12, 51, 200, 0.6)"
            :disabled="pipeline"
            v-hasPermi="['ldmap:role:edit']"
            @click="addLine('multiple')"
          >
            <span style="color: #fff">多点管线</span>
          </el-button>
        </div>

        <div v-if="showCheck" style="margin-top: 10px">
          <el-checkbox-group
            v-model="checkedpoint"
            @change="handleCheckedPointChange"
          >
            <el-checkbox
              v-for="item in legendPointeData"
              :key="item.styleId"
              :disabled="pipeline"
              :label="item.styleId"
              border
              style="width: 30%; margin-right: 3%"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
        <div style="margin-top: 10px">
          <el-checkbox
            v-model="checkedqdf"
            label="qdf"
            border
            style="width: 30%; margin-right: 3%"
            >户用机</el-checkbox
          >
          <el-button
            v-hasPermi="['ldmap:role:edit']"
            type="primary"
            v-if="checkedqdf"
            color="rgb(20, 3, 153, 0.6)"
            @click="addPointByPng('png')"
            ><span style="color: #fff">新增户用机</span>
          </el-button>
        </div>
      </div>
    </div>
    <div class="left-tabs">
      <div class="left-item" @click="lineThird = !lineThird">
        <img alt="工程报价" :src="lineThird ? upIcon : downIcon" />
        工程报价
      </div>

      <div v-if="lineThird" class="item-data">
        <el-button type="primary" @click="setPrice">报价清单</el-button>
      </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 upIcon from "@map/assets/tool/up.png";
import downIcon from "@map/assets/tool/down.png";
import useMapDataStore from "@map/store/modules/mapData";
import { ElMessageBox, ElMessage } from "element-plus";
import useMapLogStore from "@map/store/modules/mapLog";

import cut from "@map/utils/map/cut";
import exporGis from "@map/utils/map/export";
let mapLog = useMapLogStore();
let mapdata = useMapDataStore();
import { storeToRefs } from "pinia";
const $ldMap = inject("$ldMap"); // 调用全局变量
const value = ref(null);
const pipeline = ref(true);
const recognition = ref(true);
const { proxy } = getCurrentInstance();
const {
  showCheck,
  pointArray,
  maxPointIndex,
  checkedLegend,
  checkedpoint,
  layerName,
  layerId,
  profilesId,
  secen,
} = storeToRefs(mapdata);
onMounted(() => {
  getlegend();

  document.addEventListener("keyup", (e) => {
    if (e.key == "Delete") {
      let layerVal = $ldMap.delSketch();
      if (layerVal) {
        mapdata.delData(layerVal);
      }
    }
  });
});
watch(profilesId, (val) => {
  if(secen.value=='recognition'){
    recognition.value = val == null;
    pipeline.value = true
  }else{
    pipeline.value = val ==null;
    recognition.value=true
  }


});
const legendlineData = ref([]);
const legendPointeData = ref([]);
const checkAll = ref(true);

watch(layerId, (val) => {
  if (checkedqdf.value) {
    mapdata.getSetpointStyle().then((e) => {
      septicTank.value = e;
      imgUlr.value = e.img;
      $ldMap.addsepticTank(e);
    });
  } else {
    septicTank.value = null;
  }
});
const checkedqdf = ref(false);
const septicTank = ref();
const imgUlr = ref();
watch(checkedqdf, (val) => {
  console.log(val);
  if (val) {
    if (septicTank.value) {
      $ldMap.setPngPoint(true);
    } else {
      mapdata.getSetpointStyle().then((e) => {
        septicTank.value = e;
        imgUlr.value = e.img;
        $ldMap.addsepticTank(e);
      });
    }
  } else {
    $ldMap.setPngPoint(false);
  }
});
function addPointByPng(type) {
  $ldMap.addOpionPoint(type, imgUlr.value);
}

const isIndeterminate = ref(true);
const handleCheckAllChange = (val) => {
  checkedLegend.value = val
    ? legendlineData.value.map((res) => {
        return res.styleId;
      })
    : [];
};
const handleCheckedLegendChange = (value) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === legendlineData.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < legendlineData.value.length;
};

const pointLayerData = ref([]);
const handleCheckedPointChange = (value) => {
  let data = new Set(value);
  let arr = pointLayerData.value.filter((res) => {
    if (data.has(res.styleId)) {
      return res;
    }
  });
  addPointMap(arr);
};

watch(pointArray, (val) => {
  pointLayerData.value = val;
  addPointMap(val);
});
const getlegend = () => {
  mapdata.getSetlineStyle().then((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 cardShow = ref(true);
const setCard = function () {
  cardShow.value = !cardShow.value;
};
const lineFirst = ref(true);
const lineSecond = ref(false);
const lineThird = ref(false);
const emit = defineEmits();
const a = ref("");
function emitFind() {
  secen.value = "recognition";
  emit("update:findValue", true);
}
function optimizeMaxLength(){
  $ldMap.ponitBindByFivety()
}
function optimizePoline() {

  let length = 5;
  let num = $ldMap.pointBindByLength(length);
  ElMessageBox.alert(
    `检查井相近距离${length}米优化,已经优化点位:${num}个`,
    "优化提示",
    {
      confirmButtonText: "确定",
      callback: (action) => {},
    }
  );

}
function exportPng() {
  $ldMap.arcgisPrint();
}
function mergeOpt() {
  $ldMap.MergeOptimization();
}
function addPointBy(type) {
  mapdata.setMaxPointIndex(1);
  $ldMap.addOpionPoint(type, maxPointIndex.value);
}
function addLine(type) {
  $ldMap.startDrawLine(type);
}
const isShow = ref(false)
function elevationPolygon(){

  mapdata.getfindSkeleton().then(res=>{
    isShow.value = !isShow.value
    $ldMap.elevationData(isShow.value,res.data);
  })


}
function addPointMap(val) {
  $ldMap.removePoint();

  val.forEach((data) => {
    $ldMap.addDefaultByPoint(data);
  });
}

function cutPolygon() {
  let { flag, data } = cut();
  if (flag) {
  } else {
    ElMessage({ message: "请选择需要切割区域", type: "error" });
  }
}
function addPolygon(type) {
  // console.log(mapdata.house)
  $ldMap.DrawSketch("polygon", type);
}
function addPointDevice() {
  if ($ldMap.sketchLayer.pointLayer.graphics.items.length) {
    ElMessageBox.confirm("当前已添加设备点，是否删除当前设备点重新添加设备点", {
      confirmButtonText: "删除点位",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        $ldMap.sketchLayer.pointLayer.removeAll();
        $ldMap.DrawSketch("point");
      })
      .catch(() => {});
  } else {
    $ldMap.DrawSketch("point");
  }

  console.log();
}
function verificationChange() {
  emit("changeVerification");
}
function setPolineData() {
  let data = $ldMap.getpointByStart();

  console.log(JSON.stringify(data));

  let lineList = data.line.filter((item) => {
    return item[item.length - 1][2] != "s";
  });

  if (lineList.length) {
    $ldMap.hightLineLayer(lineList[0]);
    ElMessageBox.confirm("当前所以管线未连接到设备点，是否继续保存", {
      confirmButtonText: "保存",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        mapdata.saveLine(data).then(() => {
          mapLog.clearExitContent();
        });
      })
      .catch(() => {});
  } else {
    mapdata.saveLine(data).then(() => {
      mapLog.clearExitContent();
    });
  }
}
//保存特征物
function setPolygonData() {
  let polygonList = [];
  let polygondata = $ldMap.getSketchDataByType("polygon");
  let pointdata = $ldMap.getSketchDataByType("point");

  let arrParam = [];

  polygondata.forEach((res) => {
    let attributesData = res.attributes.data;
    if (attributesData.action != undefined) {
      if (attributesData.action) {
        let { id, layersId, geometryId, type, action } = attributesData;
        let rings = res.geometry.rings;
        let innerings = [],
          path = rings[0],
          extend = null;
        if (rings.length > 1) {
          innerings = rings.splice(1, rings.length);
          console.log(innerings);
        }
        if (type == "House" && attributesData.isExit) {
          let {
            area,
            houseFloors,
            houseMaterial,
            households,
            inWater,
            outWater,
            peopleNum,
          } = attributesData;
          extend = {
            area,
            houseFloors,
            houseMaterial,
            households,
            inWater,
            outWater,
            peopleNum,
          };
        }

        arrParam.push({
          id,
          layersId,
          action,
          geometryId,
          type,
          extend,
          path: path,
          innerings: innerings,
        });
      }
    }
  });
  let deviceObj = {};
  if (pointdata.length) {
    pointdata.forEach((res) => {
      deviceObj = {
        action: 1,
        type: "Station",
        path: [[res.geometry.x, res.geometry.y]],
        layersId: layerId.value,
        geometryId: "Station:" + Date.now(),
      };
    });
  } else {
    deviceObj = {
      action: 0,
    };
  }

  console.log(arrParam, deviceObj);
  mapdata.updateRecon(arrParam, deviceObj).then((res) => {
    mapLog.clearExitContent();
    mapLog.addContent({
      mapType: "regon", //regon:特征物，line:线
      actionType: "data", //add,exit,del,
      isrevoke: false, //是否允许撤回,
    });
    $ldMap.removeAllLayer();
    $ldMap.addDefaultData(mapdata.road, "Road");
    $ldMap.addDefaultData(mapdata.house, "House");
    $ldMap.addDefaultData(mapdata.river, "River");
    $ldMap.addDeviceData(mapdata.station, "Station");
  });
}

function exportCad(){
  // exporGis()
  if(profilesId.value){
    proxy.download("/pipe/recognition/exportCad?profilesId="+profilesId.value, {},
   `${layerName.value}.dwg`,{
    baseURL: "/map-api"
  },true);

  }else{
    ElMessage({ message: "请先选择特征物数据", type: "error" });
  }

}

function setPrice() {
  mapdata.createcsvFile().then((res) => {
    emit("update:priceFlag", true);
  });
}
function set() {}

function emitLine() {
  secen.value = "pipeline";
  emit("update:lineValue", true);
}

//添加div marker
function addMarker(icon, lng, lat) {
  var latlng = new L.LatLng(lat, lng);
  var marker = new L.Marker(latlng, { icon: icon, pane: drawPane });
  vectorsLayer.addLayer(marker);
  return marker;
}
</script>

<style scoped lang="scss">
:deep(.el-checkbox__label) {
  color: #fff;
}
:deep(.el-checkbox__inner) {
  background-color: rgba(0, 26, 61, 0.5);
}
:deep(.el-table) {
  width: 90%;
  margin: 0 auto;
  background: transparent;
}
:deep(.el-table tr):hover {
  background: transparent;
}
:deep(.el-table__body tr.current-row > td.el-table__cell) {
  background-color: rgb(184, 224, 250) !important;
}
:deep(.el-table th.el-table__cell) {
  background: transparent;
}

:deep(.el-table__row) {
  &:hover {
    background: rgb(184, 224, 250);
    border: 1px solid #313463;
  }
}
.leftIcon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 48px;
  box-shadow: 0 0 20px 10px rgba(22, 143, 181, 0.5) inset;
  position: absolute;
  top: 0px;
  left: -50px;
  img {
    height: 30px;
  }
}
.item {
  width: 31px;

  height: 13px;
  border-radius: 3px;

  margin-left: 23px;
  margin-top: 3px;
}
.left-tabs {
  color: #fff;
  .left-item {
    color: #fff;
    cursor: pointer;
    box-shadow: 0 0 20px 10px rgba(22, 143, 181, 0.5) inset;
    align-items: center;
    padding: 10px;
    display: flex;
    .activeImg {
      transform: rotate(180deg);
    }
    img {
      height: 15px;
      margin-right: 5px;
    }
  }
  .item-data {
    padding: 10px;
    min-height: 100px;
    .loadStyle {
      margin-top: 10px;
      display: flex;
      justify-content: s;
      align-items: center;
    }
  }
}
.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;
  }
}

.leavhide {
  animation: fadeshow 1s ease forwards;
}
.leavshow {
  animation: fadenum 1s ease forwards;
}
@keyframes fadenum {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(100%);
  }
}

@keyframes fadeshow {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0%);
  }
}
</style>
