<template>
  <div class="layerControlDiv">
    <div class="bottonList" style="margin-top: -10px; margin-left: -10px; margin-right: -10px">
      <span class="bottonListSpan" style="padding-left: 10px; color: #fff !important; opacity: 1">图层管理</span>
      <div @click="closeLayerStatus" style="float: right; cursor: pointer; margin-right: 10px; color: #25c7e3">
        <CloseOutlined type="delete-outlined" title="关闭" />
      </div>
    </div>
    <div class="layerList">
      <template v-for="(option, index) in layerList" :key="'layerList_' + index">
        <div v-if="!option.title">
          <div v-show="option.isShow" class="layerListItem" :class="option.value == option.url ? 'noSider' : ''">
            <a-checkbox style="padding-right: 10px; padding-left: 30px" v-model:checked="option.type"
              @change="layer(option, layerList)" />
            <span class="layerSpan" :title="option.label"
              :class="[option.value == option.url ? 'wideSpan' : 'narrowSpan']">{{ option.label }}</span>
            <div @click.stop="transparency2" v-show="option.value != option.url" class="layerControlWrapper">
              <a-slider @click.stop="transparency2" @change="transparency(option)" class="tftest"
                v-model:value="option.sliderValue" />
              <span>&nbsp;&nbsp;&nbsp;&nbsp;{{ option.sliderValue }}%</span>
            </div>
          </div>
        </div>
        <div class="layerListTitle" style="display: flex" v-else>
          <img src="/src/assets/images/tucen-show.png" class="jiushidu" v-show="!option.isShow"
            @click="hideOptions(layerList, option.label, true)" alt="" />
          <img src="/src/assets/images/tucen-unshow.png" class="secondimg" v-show="option.isShow"
            @click="hideOptions(layerList, option.label, false)" alt="" />

          <a-icon type="plus" />

          <a-checkbox style="padding-right: 10px; padding-left: 0px" v-model:checked="option.checked"
            @change="titlechange(option)" />
          <span class="name2" :title="option.label">{{ option.label }} </span>
        </div>
      </template>
    </div>
    <tailBaseLine />
    <!-- <label v-for="(option, index) in layerList" :key="index" @click.stop="layer(option)" class="checkbox">
      <input type="checkbox" v-if="!option.title" checkbox="checked" :value="option.value" v-model="option.type" />
      <span v-if="!option.title" class="checkmark"></span>
      <span class="name2" :title="option.label">{{ option.label }}</span>
      <div v-if="!option.title" @click.stop="transparency2" class="layerControlWrapper">
        <a-slider @click.stop="transparency2" @change="transparency(option)" class="tftest" v-model:value="option.sliderValue" />
        <span>&nbsp;&nbsp;&nbsp;&nbsp;{{ option.sliderValue }}%</span>
      </div>
    </label> -->
    <!-- <label>其它</label>
    <tailBaseLine /> -->
  </div>
</template>

<script>
import TailBaseLine from './TailBaseLine.vue';
import TFMapUitl from '/@/utils/TFMapUitl.ts';
import { CloseOutlined } from '@ant-design/icons-vue';
import { reactive, toRaw, watch, ref } from 'vue';
import { getSourceInfo } from '/@/api/map/getData.ts';
import eventBus from '/@/utils/eventBus';
import { title } from 'process';
export default {
  name: 'LayerControl',
  components: { TailBaseLine, CloseOutlined },
  setup(_, ctx) {
    eventBus.on('mapConfig', (e) => stageLayer(JSON.parse(JSON.stringify(e))));
    let layerList = ref([]);
    let newArr = reactive([]);
    const key = ref('');
    function titlechange(val) {
      console.log('layerList', layerList.value);
      console.log(val, 'val');
      console.log(val.checked, 'val');
      let isCatch = false;
      console.log('这是titlechange开始', layerList.value);
      layerList.value.map((e) => {
        if (e.label == val.label && e.title) {
          isCatch = true;
        } else if (e.label != val.label) {
          if (e.title) {
            isCatch = false;
          }
        }
        if (isCatch) {
          e.type = val.checked;
          if (!e.title) {
            layer(e);
          }
        }
        console.log('这是titlechange结束', layerList.value);
      });
      console.log('结束了会触发watch?', layerList.value);
    }

    watch(
      layerList,
      (newVal, oldVal) => {
        const processedArray = [];
        let currentGroup = null;
        newVal.forEach((item) => {
          if (item.title) {
            if (currentGroup) {
              processedArray.push(currentGroup);
            }
            currentGroup = { ...item, child: [] };
          } else {
            currentGroup.child.push(item);
          }
        });

        if (currentGroup) {
          processedArray.push(currentGroup);
        }
        newVal.map((e) => {
          processedArray.map((a) => {
            if (e.label === a.label) {
              const hasFalse = a.child.some((item) => item.type === false);
              e.checked = !hasFalse;
            }
          });
        });
      },
      {
        deep: true,
      }
    );
    //图层控制、图层的显示与隐藏
    function layer(e, list = '') {
      if (e.value == e.url) {
        otherLayerControl(e);
      } else if (e.value == 1) {
      } else {
        if (!e.title) {
          if (e.value == 'hl') {
            console.log('showOverlay');
            map.showOverlay('hlgeojson*', e.type);
          } else {
            console.log('showLayer2D');
            map.showLayer2D(e.value, e.type);
          }
        }
      }
      updateLayerList();
    }
    //加载图层
    function stageLayer(e) {
      console.log('图层控制数据----------', e);
      TFMapUitl.clearArray(layerList.value);
      var e = e.sort(function (a, b) {
        if (!a.fzxh) return 1;
        if (!b.fzxh) return -1;
        return a.fzxh - b.fzxh;
      });
      console.log('图层控制数据', e);
      var obj = {};
      e.map((i) => {
        if (i.fwfz) {
          if (obj[i.fwfz]) {
            obj[i.fwfz].push(i);
          } else {
            obj[i.fwfz] = [];
            obj[i.fwfz].push(i);
          }
        }
      });
      for (var i in obj) {
        layerList.value.push({ label: i, title: true, isShow: true, checked: false });
        var arr = obj[i];
        // var arr = arr.sort((a, b) => {
        //   return a.fwxh - b.fwxh;
        // });
        arr.map((e) => {
          var type = e.id == 'hl' ? true : e.show;
          if (!e.url) {
            type = false;
          }
          layerList.value.push({
            isShow: true,
            label: e.title,
            value: e.id,
            type: type,
            url: e.url,
            class: TFMapUitl.specialControl[e.id] || e.id,
            sliderValue: e.alpha ? e.alpha * 100 : 100,
            fwfz: e.fwfz,
          });
          if (e.id == TFMapUitl.specialControl.hllx) {
            eventBus.emit('TailBaseLineControl', type);
          }
        });
      }
      getSortedLayerList();
      // getSourceInfo({ size: 1000, current: 1, searchStr: key.value }).then((res) => {
      //   let resData = res.result.records;
      //   let one = [];
      //   let two = [];
      //   layerList.value.map((b) => {
      //     if (b.url) {
      //       //一级标题

      //       two.push(b);
      //     } else {
      //       // let obj =b
      //       let obj = JSON.parse(JSON.stringify(b));
      //       obj.sonArr = [];
      //       //二级标题
      //       one.push(obj);
      //     }
      //   });
      //   // let shili = [
      //   //   { label: '一级', son: [{ label: '二级' }, { label: '二级' }] },
      //   //   { label: '二级', son: [{ label: '二级' }, { label: '二级' }] },
      //   // ];
      //   // let shili2 = [
      //   //   { label: '一级', son: [] },
      //   //   { label: '二级' },
      //   //   { label: '二级' },
      //   //   { label: '二级', son: [] },
      //   //   { label: '二级' },
      //   //   { label: '二级' },
      //   // ];
      //   console.log(one, two);
      //   resData.map((a) => {
      //     two.map((twodata) => {
      //       if (twodata.label == a.zymc) {
      //         // console.log(twodata.label, 'twodata.label');
      //         one.map((onedata) => {
      //           if (onedata.label == a.fwfz && twodata.fwfz == a.fwfz) {
      //             // console.log(onedata.label, 'onedata.label');
      //             // console.log(twodata, 'twodata');
      //             onedata.sonArr.push(twodata);
      //           }
      //         });
      //       }
      //     });
      //   });
      //   console.log(one, 'onedata');
      //   newArr = [];
      //   one.forEach((obj, index) => {
      //     newArr.push(obj);
      //     if (obj.sonArr && obj.sonArr.length > 0) {
      //       newArr.push(...obj.sonArr);
      //     }
      //   });
      //   console.log(newArr, 'newArr');
      //   layerList.value = newArr;
      //   console.log('layerList重新赋值？？？？？？？？？？？？？？？？', layerList.value);
      // });

      window.setTimeout((e) => {
        updateLayerList();
      }, 200);
    }
    async function getSortedLayerList() {/*  */
      try {
        const res = await getSourceInfo({ size: 1000, current: 1, searchStr: key.value });
        const resData = res.result.records;
        const one = [];
        const two = [];

        layerList.value.forEach((b) => {
          if (b.url) {
            two.push(b);
          } else {
            const obj = { ...b, sonArr: [] };
            one.push(obj);
          }
        });

        resData.forEach((a) => {
          two.forEach((twodata) => {
            if (twodata.label === a.zymc && twodata.fwfz === a.fwfz) {
              const onedata = one.find((onedata) => onedata.label === a.fwfz);
              if (onedata) {
                onedata.sonArr.push(twodata);
              }
            }
          });
        });

        const newArr = [];
        one.forEach((obj) => {
          newArr.push(obj);
          if (obj.sonArr && obj.sonArr.length > 0) {
            newArr.push(...obj.sonArr);
          }
        });
        layerList.value = newArr;
      } catch (error) {
        console.error('获取图层信息失败', error);
      }
    }
    function closeLayerStatus() {
      console.log('closeLayerStatus');
      ctx.emit('closeLayerStatus', false);
    }

    //图层控制模块使用滑动条时，阻止事件向上冒泡
    function transparency2(event) {
      console.log('transparency2');
      if (event.cancelBubble instanceof Boolean) {
        event.cancelBubble = true;
      }
      if (event.preventDefault && typeof event.preventDefault == 'function') {
        event.preventDefault();
      }
    }

    //图层控制模块中图层透明度控制
    function transparency(option, key) {
      console.log('图层控制模块中图层透明度控制');
      map.setLayer2D(option.value, 'alpha', option.sliderValue / 100);
      // if (doubleScreenMap) {
      //   console.log('33333333333333');
      //         doubleScreenMap.setLayer2D(option.value, 'alpha', option.sliderValue / 100);
      //       }
    }
    //特殊图层的控制
    function otherLayerControl(e) {
      if (e.class == TFMapUitl.specialControl.hllx) {
        eventBus.emit('TailBaseLineControl', e.type);
      } else {
        if (e.class) {
          const temp = e.class.split(',');
          temp.forEach((item) => {
            if (item == 'layerControl_zhjcsb*') map.showOverlay('devicesWord*', e.type)
            map.showOverlay(item, e.type)
          });
        }
      }
    }

    function updateLayerList() {
      const tempData = JSON.parse(JSON.stringify(toRaw(layerList.value)));
      tempData.map((i) => (tempData[i.class] = i));
      window.mapConfig.layerList = tempData;
    }
    function hideOptions(list, op, type) {
      console.log(type, 'type');
      // console.log('list',list);
      // console.log('op',op);
      // let showArr=[]
      let isCatch = false;
      list.map((e) => {
        // console.log(e,'e');
        if (e.label == op && e.title) {
          // console.log('匹配到了！',e.label);
          e.isShow = type;
          isCatch = true;
        } else if (e.label != op) {
          if (e.title) {
            // console.log('这不是满足条件的标题',e.label);
            isCatch = false;
          }

          if (isCatch) {
            // console.log('修改这几项的属性',e);
            e.isShow = type;
            console.log(e, 'e');
          }
        }
      });
      console.log('这是经过开关处理的', list);
    }
    return {
      newArr,
      titlechange,
      hideOptions,
      layerList,
      closeLayerStatus,
      getSortedLayerList,
      transparency2,
      transparency,
      layer,
      key,
    };
  },
};
</script>

<style lang="less" scoped>
.layerControlDiv {
  position: relative;
  width: 100%;
  height: 600px;

  .layerList {
    padding-top: 10px;
    position: relative;
    height: calc(100% - 50px);
    overflow-y: auto;
    overflow-x: hidden;
  }
}

.bottonList {
  padding-top: 5px;
  padding-bottom: 5px;
  font-size: 16px;
  // background: #031A26;
  opacity: 1;
  border-bottom: 1px solid #0b5d7c;

  .bottonListSpan {
    // color: #fff;
    padding-left: 15px;
    font-size: 16px;
  }
}

.name2 {
  width: 123px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.layerListItem {
  display: flex;
  flex-direction: row;
  text-align: center;
  align-items: center;
}

.layerControlWrapper {
  width: 130px;
  display: flex;
  align-items: baseline;
  padding-left: 20px;
  margin-left: auto;

  .ant-slider.tftest {
    width: calc(100% - 55px);
  }

  span {
    position: relative;
    float: left;
    display: block;
    width: 50px;
  }
}

span.layerSpan {
  position: relative;
  width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}

.wideSpan {
  width: 240px !important;
  overflow: visible !important;
  white-space: normal !important;
}

.narrowSpan {
  width: 140px !important;
}

/deep/.ant-checkbox-inner {
  border: 1px solid white;
}

.noSider {
  padding: 7px 0px;
}

.layerList::-webkit-scrollbar {
  width: 4px;
  /* 设置滚动条宽度 */
}

.layerList::-webkit-scrollbar-track {
  /* 设置滚动条背景颜色 */
}

.layerList::-webkit-scrollbar-thumb {
  background-color: #007e8f;
  /* 设置滚动条滑块颜色 */
  border-radius: 4px;
  /* 设置滚动条滑块圆角 */
}

.layerList::-webkit-scrollbar-thumb:hover {
  background-color: #007e8f;
  /* 设置滚动条滑块在鼠标悬停时的颜色 */
}

.layerListTitle {
  // background-color: aliceblue;
  line-height: 30px;
  height: 30px;
  background-image: linear-gradient(to left, rgba(0, 139, 253, 0.2), rgba(67, 255, 249, 0.2));

  /* 设置背景颜色 */
  // width: 200px;
  img {
    margin-top: 6px;
    margin-left: 0px;
    margin-right: 5px;
    width: 20px;
    height: 19px;
  }
}

.jiushidu {
  -moz-transform: rotate(90deg);
  -webkit-transform: rotate(90deg);
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}

.secondimg {}
</style>
