<template>
  <div>
    <el-row class="search-bar" :gutter="10">
      <el-col :span="18">
        <el-input size="small"></el-input>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="small" icon="search">搜索</el-button>
      </el-col>
    </el-row>

    <div id="map-container"></div>
    <!-- 添加或修改站点对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form ref="siteRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="站点名称" prop="siteName">
          <el-input v-model="form.siteName" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="分组" prop="groupId">
          <!-- <el-input v-model="form.groupId" placeholder="请输入分组ID" /> -->
          <el-select v-model="form.groupId" placeholder="请选择站点分组">
            <el-option
              v-for="item in siteGroupList"
              :key="item.groupId"
              :label="item.groupName"
              :value="item.groupId"
            />
          </el-select>
        </el-form-item>
        <city-select v-model="form" :label-width="80"></city-select>
        <!-- <el-form-item label="省" prop="province">
          <el-input v-model="form.province" placeholder="请输入省" />
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input v-model="form.city" placeholder="请输入市" />
        </el-form-item>
        <el-form-item label="区" prop="area">
          <el-input v-model="form.area" placeholder="请输入区" />
        </el-form-item> -->
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="经纬度" prop="coordinate">
          <el-input
            class="map-select"
            readonly
            v-model="form.coordinate"
            placeholder="请点击右侧按钮在地图上选点"
          >
            <template #append>
              <!-- <el-icon @click="open = false"><Pointer />
                </el-icon
            > -->
              <el-button @click="open = false" icon="pointer"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <!-- <el-form-item label="站点" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入站点ID" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="back">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listSiteGroup } from "@/api/site/group";
import AMapLoader from "@amap/amap-jsapi-loader";
import CitySelect from "@/components/CitySelect";
import { addSite, getSite, updateSite } from "@/api/site/site";
import tab from "@/plugins/tab";
import { useRoute } from "vue-router";

const route = useRoute();
const { proxy } = getCurrentInstance();
const geocoder = shallowRef(null); // 经纬度转地址插件
const AMap = shallowRef(null);
const map = shallowRef(null);
const siteGroupList = ref([]);
const open = ref(false);
const title = ref("");
const data = reactive({
  form: {},
  rules: {},
});

const { form, rules } = toRefs(data);
// 初始化地图
const initMap = async () => {
  try {
    AMap.value = await AMapLoader.load({
      key: "377d7c36dd385e2a722f29d4c6e1ffbf", // 申请好的Web端开发者Key，首次调用 load 时必填
      // key: "7891f1238368a895ff1967c79643102d", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        // "AMap.Driving",
        "AMap.Scale",
        // "AMap.PlaceSearch",
        // "AMap.AutoComplete",
        "AMap.Geocoder",
        // "AMap.TruckDriving",
      ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      AMapUI: {
        // 是否加载 AMapUI，缺省不加载
        version: "1.1", // AMapUI 版本
        plugins: ["overlay/SimpleMarker"], // 需要加载的 AMapUI ui插件
      },
      Loca: {
        // 是否加载 Loca， 缺省不加载
        version: "2.0", // Loca 版本
      },
    });
    geocoder.value = new AMap.value.Geocoder();
    map.value = new AMap.value.Map("map-container", {
      zoom: 16, // 缩放级别
      center: [117.290345, 31.797813], // 中心点
      city: "合肥",
    });
    window.mapins = map.value;
    /** 加载插件 */
    // 驾车路线规划插件
    // driving.value = new AMap.value.Driving({
    //   // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
    //   // policy: AMap.DrivingPolicy.MULTI_POLICIES,
    //   // map: map.value,
    //   panel: "panel",
    // });

    // 卡车路线规划插件 TODO:
    // truckDriving.value = new AMap.value.TruckDriving({ map: map.value });
    // // 地点搜索插件
    // placeSearch.value = new AMap.value.PlaceSearch({
    //   // map: map.value,
    //   city: "0551",
    // });
    // geocoder.value = new AMap.value.Geocoder();
    // // 搜索建议插件
    // autoComplete.value = new AMap.value.AutoComplete({});
    // /** 加载插件结束 */
    // resultInfoWindow.value = new AMap.value.InfoWindow({
    //   anchor: "bottom-center",
    // });
    // startMarker.value = new AMap.value.Marker({
    //   icon: startPng,
    //   anchor: "bottom-center",
    // });
    // endMarker.value = new AMap.value.Marker({
    //   icon: endPng,
    //   anchor: "bottom-center",
    // });
    // city: "010", //城市设为北京，默认：“全国”
    // radius: 1000, //范围，默认：500
    // AMap.value.Event.addListener(placeSearch.value, "markerClick", (e) => {
    //   //添加事件
    //   console.log(e); //获取点标注位置
    //   if (nowSearch.value === "start") {
    //     formData.value.startName = e.data.name;
    //     formData.value.startLngLat = [e.data.location.lng, e.data.location.lat];
    //   } else if (nowSearch.value === "end") {
    //     formData.value.endName = e.data.name;
    //     formData.value.endLngLat = [e.data.location.lng, e.data.location.lat];
    //   }
    // });
    map.value.on("click", handleMapClick);
    map.value.addControl(new AMap.value.Scale());
  } catch (error) {
    console.log(error);
  }
};
// 根据经纬度获取地址
const regeoCode = (lnglat /** [lng, lat] */) => {
  return new Promise((resolve, reject) => {
    geocoder.value.getAddress(lnglat, (status, result) => {
      if (status === "complete" && result.regeocode) {
        const address = result.regeocode.formattedAddress;
        resolve(address);
      } else {
        reject("根据经纬度查询地址失败");
      }
    });
  });
};

const handleMapClick = async (ev) => {
  open.value = true;
  form.value.coordinate = `${ev.lnglat.lng},${ev.lnglat.lat}`;
  form.value.address = await regeoCode([ev.lnglat.lng, ev.lnglat.lat]);
};

/** 提交按钮 */
function submitForm() {
  proxy.$refs["siteRef"].validate((valid) => {
    if (valid) {
      if (form.value.siteId != null) {
        updateSite(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          back();
        });
      } else {
        addSite(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          back();
        });
      }
    }
  });
}

function back() {
  reset();
  tab.closeOpenPage({ path: "/basic/site" });
}
// 表单重置
function reset() {
  form.value = {
    siteId: null,
    siteName: null,
    groupId: null,
    province: null,
    city: null,
    area: null,
    address: null,
    coordinate: null,
    remark: null,
    createBy: null,
    createTime: null,
    uuid: null,
    tenantId: null,
  };
  proxy.resetForm("siteRef");
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

onMounted(() => {
  initMap();
});

listSiteGroup().then((resp) => {
  siteGroupList.value = resp.rows;
});

reset();

if (route.query.siteId && route.query.uuid) {
  getSite(route.query.siteId, route.query.uuid).then((resp) => {
    form.value = resp.data;
    open.value = true;
    title.value = "修改站点";
  });
} else {
  open.value = true;
  title.value = "添加站点";
}
</script>

<style lang="scss" scoped>
#map-container {
  width: 100%;
  height: calc(100vh - 84px);
}
.search-bar {
  z-index: 99;
  width: 300px;
  position: absolute;
  left: 20px;
  top: 20px;
}
// :deep(.map-select) {
// }
</style>
