<template>
  <div class="dialog">
    <div class="gradient-text dialog-title">请选择事发地点</div>
    <div class="icon-close" @click="handleClose"></div>
    <div class="dialog-content">
      <div class="form">
        <div class="line">
          <div class="form-item">
            <div class="text">详细地址</div>
            <el-input v-model="form.address" class="custom-input" placeholder="请输入" />
            <div v-if="searchPop" class="scroll_box">
              <div style="height: 60px; line-height: 60px">
                <span style="font-weight: bold">搜索结果列表</span>
                <i class="el-icon-close" style="float: right; font-size: 20px; cursor: pointer" @click="closeSearchList()" />
              </div>

              <el-scrollbar class="scroll" style="height: 250px">
                <div v-for="(item, index) in searchList" v-show="searchList.length" :key="index" class="item" @click="handlePanTo(index)">
                  <el-image class="img" :src="item.img" :alt="item.name" lazy>
                    <template #error>
                      <div class="image-slot">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </template>
                  </el-image>
                  <div>
                    <div class="text">{{ item.name }}</div>
                    <div>{{ item.address }}</div>
                  </div>
                </div>
                <div v-show="!searchList.length" class="empty" style="text-align: center">没有搜索到内容</div>
              </el-scrollbar>

              <el-pagination
                background
                small
                :hide-on-single-page="true"
                layout="prev, pager, next"
                :total="total"
                :page-size="pageSize"
                :current-page="pageNum"
                style="margin-top: 10px"
                @current-change="handleChangePage"
              >
              </el-pagination>
            </div>
          </div>
          <div class="btn1" @click="handleInput(0)">搜索</div>
        </div>
        <div class="line">
          <div class="form-item">
            <div class="text">经度</div>
            <el-input v-model="form.longitude" class="custom-input" placeholder="请输入" />
          </div>
          <div class="form-item" style="margin-left: 80px">
            <div class="text">详细地址</div>
            <el-input v-model="form.latitude" class="custom-input" placeholder="请输入" />
          </div>
        </div>
      </div>
      <div id="positionMap" class="map_box" :style="{ width: width, height: height }">
        <div id="map" class="map"></div>
      </div>
      <div class="footer">
        <div class="btn2" @click="handleClose">取消</div>
        <div class="btn1" style="margin-left: 40px" @click="submit">确定</div>
      </div>
    </div>
  </div>
</template>

<script setup name="PositionMap">
import AMapLoader from '@amap/amap-jsapi-loader';
import { useRouter } from 'vue-router';
import { addEvent } from '@/api/emergencyCommandMap/JointDuty';

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    }
  }
});
const router = useRouter();
const emits = defineEmits(['update:visible']);
// 地图对象
let map = null;
let amap = {};
let marker = null; //地图上的点标记
let contextMenu = null;
let lnglatPosition = ref([]); //选中的新坐标
let rules = reactive({
  address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
  latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }]
});
let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);

let searchList = ref([]);
let searchPop = ref(false);
let placeSearch;
// 提交事件时间改为当前时间currentTime
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
let form = reactive({
  address: '',
  longitude: '',
  latitude: '',
  event_title: '',
  event_type: '',
  event_level: '',
  event_status: '1',
  event_time: currentTime,
  report_time: '1977-01-01 00:00:00',
  deaths: '0',
  injuries: '0',
  missing: '0',
  event_source: '',
  event_description: '',
  casualties: '',
  del_flag: '9'
});
let geocoder = {};
let width = ref('100%');
let height = ref('100%');
watch(
  () => props.visible,
  (n) => {
    if (n) {
      nextTick(() => {
        initMap();
      });
    }
  },
  {
    immediate: true
  }
);
onMounted(() => {
  window.addEventListener('resize', handleResize);
});
onUnmounted(() => {
  if (!!map) {
    map.off('rightclick');
    map.destroy();
    map = null;
  }
  window.removeEventListener('resize', handleResize);
});
function handleInput(flag) {
  if (!form.address) return;

  if (!flag) {
    //搜索
    total.value = 0;
    pageNum.value = 1;
  }

  if (!placeSearch) {
    placeSearch = new amap.PlaceSearch({
      pageSize: 10, // 每页条数，默认10，范围1-50
      pageIndex: 1, // 页码
      extensions: 'all' // 默认base，返回基本地址信息；all：返回详细信息
    });
  }

  searchPop.value = true;
  placeSearch.setPageIndex(pageNum.value);
  placeSearch.search(form.address, (status, result) => {
    // console.log(result.poiList.pois, 'result')
    if (!!result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
      let arr = [];
      const pois = result.poiList.pois;
      total.value = result.poiList ? result.poiList.count : 0;
      arr = pois.map((item) => {
        return {
          name: item.name,
          address: item.address,
          img: item.photos[0]?.url,
          lnglat: [item.location.lng, item.location.lat]
        };
      });
      searchList.value = arr;
    } else {
      total.value = 0;
      searchList.value = [];
    }
  });
}
function handleChangePage(newNum) {
  if (!searchPop.value) return;
  pageNum.value = newNum;
  handleInput(1);
}
function closeSearchList() {
  searchPop.value = false;
  searchList.value = [];
  total.value = 0;
  pageNum.value = 1;
}
// 地图中心的平移至指定点位置
function handlePanTo(index) {
  let lnglat = searchList.value[index].lnglat;
  form.address = searchList.value[index].name + '(' + searchList.value[index].address + ')';
  form.longitude = lnglat[0];
  form.latitude = lnglat[1];

  map.panTo(lnglat);
  setMarks(lnglat);
  closeSearchList();
}
const initMap = async () => {
  let position = [110.93154257997, 21.669064031332];
  const AMap = await AMapLoader.load({
    key: '30d3d8448efd68cb0b284549fd41adcf', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.PlaceSearch', 'AMap.ContextMenu', 'AMap.PolygonEditor', 'AMap.Geocoder'] // 插件列表
  });
  map = new AMap.Map('map', {
    viewMode: '3D', //是否为3D地图模式
    center: position,
    zoom: 15
  });
  amap = AMap;
  geocoder = new AMap.Geocoder({
    // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
    city: '010'
  });
  // 创建右键菜单
  ContextMenu();
  map.on('rightclick', handleRightclick);
  handleResize();
};
function ContextMenu() {
  contextMenu = new AMap.ContextMenu();
  contextMenu.addItem(
    '选择标点',
    () => {
      form.longitude = lnglatPosition.value[0];
      form.latitude = lnglatPosition.value[1];
      contextMenu.close();
      let lnglat = [form.longitude, form.latitude];
      geocoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          form.address = result.regeocode.formattedAddress;
        }
      });
      setMarks(lnglat);
    },
    1
  );
}
// 右键事件
function handleRightclick(e) {
  let lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
  contextMenu.open(map, e.lnglat);
  lnglatPosition.value = lnglat;
}
function setMarks(lnglat) {
  //添加标记
  if (marker) map.remove(marker);
  marker = new AMap.Marker({
    position: lnglat,
    icon: new AMap.Icon({
      size: new AMap.Size(22, 28), //图标所处区域大小
      imageSize: new AMap.Size(22, 28), //图标大小
      image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png'
    }),
    anchor: 'bottom-center',
    offset: new AMap.Pixel(0, 0)
  });
  marker.setMap(map);
}
function handleClose() {
  emits('update:visible', false);
}
let queryFormRef = ref();
let containerRef = ref();
function handleResize() {
  const containerWidth = 2900 * (document.body.clientWidth / 8960);
  const containerHeight = 750 * (document.body.clientHeight / 2520);
  width.value = containerWidth + 'px';
  height.value = containerHeight + 'px';
  nextTick(() => {
    map.resize();
  });
}
function submit() {
  queryFormRef.value.validate((valid) => {
    if (valid) {
      console.log('提交数据', form);
      addEvent(form).then((res) => {
        router.push({
          path: '/emergencyCommandMap',
          query: {
            tempEventId: res.data
          }
        });
      });
    }
  });
}
</script>

<style lang="scss" scoped>
.map_box {
  position: relative;
  background: rgba(0, 0, 0, 0.3);
  margin-bottom: 20px;
}
.map {
  width: 100%;
  height: 100%;
}
.search {
  width: 50%;
  position: absolute;
  right: 2%;
  top: 10px;
  background: #fff;
  padding: 8px 8px;
  border-radius: 3px;
  display: flex;
}
.btn {
  margin-left: 10px;
}

.scroll_box {
  width: calc(100% - 165px);
  background: #0a2c5c;
  position: absolute;
  left: 165px;
  top: 80px;
  z-index: 9;
  padding: 20px;
  border-radius: 3px;
  .close {
    position: absolute;
    right: 10px;
    top: 10px;
    cursor: pointer;
    font-size: 40px;
  }
  :deep(.el-pagination__total) {
    color: #a7ccdf;
    font-size: 32px;
  }

  :deep(.el-pagination) {
    .btn-next,
    .btn-prev {
      background-color: transparent;
      border: none;
      .el-icon {
        font-size: 22px;
        color: #a7ccdf;
      }
    }
    .el-pager li {
      width: 64px;
      height: 64px;
      line-height: 64px;
      text-align: center;
      font-size: 32px;
      color: #a7ccdf;
      background-color: #0e3064;
      border: 1px solid #0c57a7;
      margin: 0 6px;
      &:hover {
        background-color: #038dff;
        border: 1px solid #038dff;
      }
    }
    .el-pager li.is-active {
      background-color: #038dff;
      border: 1px solid #038dff;
    }
  }
}
.scroll {
  width: 100%;
  height: auto !important;

  .item {
    display: flex;
    font-size: 32px;
    cursor: pointer;
    padding: 8px;

    &:hover {
      background-color: #102e76;
    }

    .img {
      width: 80px;
      height: 80px;
      min-width: 80px;
      margin-right: 15px;
    }
    :deep(.image-slot) {
      width: 100%;
      height: 100%;
      background-color: #f5f7fa;
      text-align: center;
      line-height: 50px;
    }
    :deep(.el-icon-picture-outline) {
      font-size: 32px;
    }
    .text {
      color: #3385ff;
      margin-bottom: 6px;
    }
  }
}
:deep(.el-scrollbar__wrap) {
  overflow-x: hidden !important;
}

:deep(.is-horizontal) {
  display: none;
}

.empty {
  margin: 20px 0;
}
.dialog {
  position: absolute;
  top: 90px;
  left: 900px;
  width: 3000px;
  height: 2000px;
  z-index: 2000;
  font-size: 36px;
  padding: 160px 60px 20px 65px;
  font-size: 36px;
  color: #fff;
  background: url('@/assets/images/position/positionDialog.png') no-repeat;
  .dialog-title {
    position: absolute;
    top: 40px;
    left: 60px;
    font-size: 72px;
  }
  .icon-close {
    cursor: pointer;
    position: absolute;
    top: 0px;
    right: -7px;
    width: 77px;
    height: 72px;
    background: url('@/assets/images/map/rightMenu/close.png') no-repeat;
    background-size: 100% 100%;
  }
  .dialog-content {
    padding: 10px 0;
    .map_box {
      overflow: hidden;
    }
    .footer {
      display: flex;
      align-items: center;
      position: absolute;
      bottom: 45px;
      right: 45px;
    }
  }
}
.form {
  .line {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 30px;
    .form-item {
      flex: 1;
      display: flex;
      align-items: center;
      position: relative;
      .text {
        font-size: 36px;
        color: #eaf3fc;
        white-space: nowrap;
        margin-right: 20px;
      }
      :deep(.el-input__wrapper) {
        background-color: rgba(26, 144, 255, 0.15) !important;
        border: 4px solid rgba(26, 144, 255, 0.15) !important;
      }
      :deep(.el-input__inner) {
        height: 56px;
        line-height: 56px;
      }
    }
  }
}
.btn1 {
  width: 204px;
  height: 120px;
  background: url('@/assets/images/position/btn2.png') no-repeat;
  font-size: 36px;
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: -25px;
  cursor: pointer;
  margin-left: 70px;
}
.btn2 {
  width: 140px;
  height: 56px;
  background: url('@/assets/images/position/btn.png') no-repeat;
  font-size: 36px;
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: -25px;
  cursor: pointer;
  margin-left: 70px;
}
</style>
