<template>
  <!-- destroy-on-close -->
  <ElDialog v-model="showDialog" :close-on-click-modal="false" width="fit-content" @close="dialogCloseHandler">
    <ElForm :model="formData" :rules="rules" ref="stationForm" class="form-panel" label-width="auto" style="width: 600px">

      <ElFormItem label="组织信息 Id" prop="orgId">
        <!-- <ElInput v-model="formData.orgId" :disabled="status === 'view'" placeholder="组织信息 Id" /> -->

        <el-select v-model="formData.orgId" :disabled="status === 'view'" placeholder="产品类型" filterable remote reserve-keyword remote-show-suffix :remote-method="remoteOrg" :loading="loadingOrg">
          <el-option v-for="item in orgList" :key="item.id" :label="item.orgName" :value="item.id" />
        </el-select>
      </ElFormItem>
      <ElFormItem label="站点名称" prop="stationName">
        <ElInput v-model="formData.stationName" :disabled="status === 'view'" placeholder="站点名称" />
      </ElFormItem>
      <!-- <ElFormItem label="省；代码" prop="province">
        <ElInput v-model="formData.province" :disabled="status === 'view'" placeholder="省；代码" />
      </ElFormItem>
      <ElFormItem label="市；代码" prop="city">
        <ElInput v-model="formData.city" :disabled="status === 'view'" placeholder="市；代码" />
      </ElFormItem>
      <ElFormItem label="区县；代码" prop="area">
        <ElInput v-model="formData.area" :disabled="status === 'view'" placeholder="区县；代码" />
      </ElFormItem>
      <ElFormItem label="乡镇街道；代码" prop="town">
        <ElInput v-model="formData.town" :disabled="status === 'view'" placeholder="乡镇街道；代码" />
      </ElFormItem> -->
      <ElFormItem label="详细地址" prop="address">
        <el-select v-model="formData.address" :disabled="status === 'view'" placeholder="详细地址" filterable remote reserve-keyword remote-show-suffix :remote-method="remoteMethod" @change="addressChange" :loading="loading">
          <el-option v-for="item in addList" :key="item.id" :label="item.address" :value="item.address" />
        </el-select>
      </ElFormItem>
      <ElFormItem label="省" prop="provinceName">
        <ElInput v-model="formData.provinceName" :disabled="status === 'view'" placeholder="省" />
      </ElFormItem>
      <ElFormItem label="市" prop="cityName">
        <ElInput v-model="formData.cityName" :disabled="status === 'view'" placeholder="市" />
      </ElFormItem>
      <ElFormItem label="区县" prop="areaName">
        <ElInput v-model="formData.areaName" :disabled="status === 'view'" placeholder="区县" />
      </ElFormItem>
      <ElFormItem label="乡镇街道" prop="townName">
        <ElInput v-model="formData.townName" :disabled="status === 'view'" placeholder="乡镇街道" />
      </ElFormItem>

      <ElFormItem label="经度" prop="lng">
        <ElInput v-model="formData.lng" :disabled="status === 'view'" placeholder="经度" />
      </ElFormItem>
      <ElFormItem label="纬度" prop="lat">
        <ElInput v-model="formData.lat" :disabled="status === 'view'" placeholder="纬度" />
      </ElFormItem>
    </ElForm>

    <div id="container" style="width: 100%; height: 400px"></div>

    <template #footer>
      <ElButton @click="showDialog = false">{{ status === "view" ? "关闭" : "取消" }}</ElButton>
      <ElButton v-if="status !== 'view'" :loading="submiting" type="primary" @click="submitHandler">提交</ElButton>
    </template>
  </ElDialog>
</template>

<script lang="ts" setup>
import StationApi from "@/pages/cst/station/station-api.ts";
import Strings from "@/common/utils/strings.ts";
import FormUtil from "@/common/utils/formUtil.ts";
import Utils from "@/common/utils";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { geocoder, init, latLng, marker, search } from "./map.ts";
import OrgApi from "@/pages/cst/org/org-api.ts";

const emits = defineEmits(["editSucc"]);
const showDialog = ref(false);
const submiting = ref(false);
const status = ref<"add" | "view" | "modify">("add");

const stationFormIns = useTemplateRef<FormInstance>("stationForm");

const formData = Utils.resetAble(reactive<StationTypes.SearchStationResult>({}));
const rules = reactive<FormRules<StationTypes.SearchStationResult>>({
  id: [{ required: true, message: "请填写Id", trigger: "blur" }],
  orgId: [{ required: true, message: "请填写组织信息 Id", trigger: "blur" }],
  stationName: [{ required: true, message: "请填写站点名称", trigger: "blur" }],
  province: [{ required: true, message: "请填写省；代码", trigger: "blur" }],
  city: [{ required: true, message: "请填写市；代码", trigger: "blur" }],
  area: [{ required: true, message: "请填写区县；代码", trigger: "blur" }],
  town: [{ required: true, message: "请填写乡镇街道；代码", trigger: "blur" }],
  provinceName: [{ required: true, message: "请填写省", trigger: "blur" }],
  cityName: [{ required: true, message: "请填写市", trigger: "blur" }],
  areaName: [{ required: true, message: "请填写区县", trigger: "blur" }],
  townName: [{ required: true, message: "请填写乡镇街道", trigger: "blur" }],
  address: [{ required: true, message: "请填写详细地址", trigger: "blur" }],
  lng: [{ required: true, message: "请填写经度", trigger: "blur" }],
  lat: [{ required: true, message: "请填写纬度", trigger: "blur" }],
  creatorId: [{ required: true, message: "请填写创建人", trigger: "blur" }],
  modifierId: [{ required: true, message: "请填写修改人", trigger: "blur" }],
  createTime: [{ required: true, message: "请填写创建时间", trigger: "blur" }],
  modifyTime: [{ required: true, message: "请填写修改时间", trigger: "blur" }],
  deleted: [{ required: true, message: "请填写是否删除", trigger: "blur" }],
});

function dialogCloseHandler() {
  formData.$reset();
  if (markers) {
    markers.setMap(null);
    markers = null;
  }
}

function submitHandler() {
  if (status.value === "view") return;
  submiting.value = true;
  if (formData.id != null) {
    FormUtil.submit(stationFormIns, () => StationApi.modify(formData))
      .then(() => {
        ElMessage.success("修改成功");
        emits("editSucc");
        showDialog.value = false;
      })
      .finally(() => {
        submiting.value = false;
      });
  } else {
    FormUtil.submit(stationFormIns, () => StationApi.add(formData))
      .then(() => {
        ElMessage.success("添加成功");
        emits("editSucc");
        showDialog.value = false;
      })
      .finally(() => {
        submiting.value = false;
      });
  }
}
let map: any;
let markers: any;

const getDetail = (latLng: string) => {
  if (markers) {
    markers.setMap(null);
    markers = null;
  }
  markers = marker(map, latLng);

  map.easeTo({ zoom: 13, center: latLng }, { duration: 1000 });

  geocoder(latLng)
    .getAddress({
      location: latLng,
    })
    .then((res: any) => {
      // address.value = res.result.formatted_addresses.standard_address
      let res1 = res.result;

      formData.address = res1.formatted_addresses.standard_address;
      formData.area = res1.ad_info.adcode;
      formData.areaName = res1.ad_info.district;
      formData.city = res1.ad_info.city_code;
      formData.cityName = res1.ad_info.city;
      formData.province = "340000";
      formData.provinceName = "安徽省";

      formData.lat = res1.location.lat;
      formData.lng = res1.location.lng;
      formData.town = res1.address_reference.town.id;
      formData.townName = res1.address_reference.town.title;
      console.log(formData, "formData");
    });
};

const orgList = ref<OrgTypes.SearchOrgResult[]>([]);
const loadingOrg = ref(false);

const remoteOrg = (query: string) => {
  loading.value = true;
  OrgApi.paging({ size: 50, orgName: query || undefined }).then((res) => {
    orgList.value = res.data.records;
    loadingOrg.value = false;
    // category.value = list.value.filter((item) => {
    //   return item.label.toLowerCase().includes(query.toLowerCase())
    // })
  });
  // } else {
  //   category.value = [];
  // }
};

const loading = ref(false);
const addList = ref<any>([]);
const remoteMethod = (query: string) => {
  if (query) {
    loading.value = true;

    search()
      .searchRectangle({
        keyword: query,
        bounds: map.getBounds(),
      })
      .then((res: any) => {
        addList.value = res.data;
        loading.value = false;
      });
  }
};

let addressChange = (e: string) => {
  console.log(e, "eee");
  if (addList.value) {
    let item = addList.value.find((add: any) => (add.address == e));
    if (item) getDetail(latLng(item.location.lat, item.location.lng));
  }
};

defineExpose({
  open(data: StationTypes.SearchStationResult = {}) {
    showDialog.value = true;
    if (!Strings.isBlank(data.id)) {
      status.value = "modify";
      StationApi.detail(data.id!).then((res) => {
        formData.$reset(res.data);
      });
    } else {
      status.value = "add";
      formData.$reset(data);
    }
    setTimeout(() => {
      if (!map) {
        map = init("container");
        map.on("click", (evt: any) => {
          getDetail(evt.latLng);
        });
      }
    }, 50);
  },
});
</script>

<style lang="stylus" scoped>
.form-panel {
  padding 20px
}
</style>
