<template>
  <div>
    <div v-if="dialogFormVisible" class="dialog">
      <div class="head_box">
        <span class="title">{{ title }}</span>
        <div>
          <el-button
            v-if="!infoActive"
            type="primary"
            size="small"
            @click="submit"
            :loading="btnLoading"
          >保存</el-button
          >
          <el-button size="small" @click="close">关闭</el-button>
        </div>
      </div>

      <div class="dialogWrapper">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          :inline="true"
          :disabled="infoActive"
        >
          <el-form-item prop="bddMc" label="必到点名称:">
            <el-input
              style="width: 80%;"
              min="0"
              placeholder="请填写必到点名称"
              v-model="form.bddMc"
            ></el-input>
          </el-form-item>
          <el-form-item prop="fgdwId" label="所属方格:">
            <el-select
              :disabled="typeStatus === 'del'"
              placeholder="请选择所属方格"
              filterable
              clearable
              v-model="form.fgdwId"
              @change="handleChange"
            >
            <el-option
              v-for="item in fgList"
              :key="item?.id"
              :label="item?.mc"
              :value="item?.id"
            />
            </el-select>
          </el-form-item>
          <el-form-item prop="bddDz" label="必到点地址:">
            <el-input
              placeholder="请填必到点地址"
              clearable
              v-model="form.bddDz"
            ></el-input>
          </el-form-item>
          <el-form-item prop="jd" label="经度:">
            <el-input
              disabled
              placeholder="请填写经度"
              v-model="form.jd"
            ></el-input>
          </el-form-item>
          <el-form-item prop="wd" label="纬度:">
            <el-input
              disabled
              placeholder="请填写纬度"
              v-model="form.jd"
            ></el-input>
          </el-form-item>
        </el-form>

        <div style="height: calc(100vh - 336px)">
          <gd-map />
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, computed, onMounted } from "vue";
import { fetchTbZdxlFgdwSelectList, fetchTbZdxlFgdwBddSave, fetchTbZdxlFgdwBddUpdate, fetchTbZdxlFgdwId } from "@/api/service/taskProgress";
const { proxy } = getCurrentInstance();
import GdMap from "@/components/Map/GdMap/index.vue"
import emitter from "@/utils/eventBus";
const btnLoading = ref(false); //按钮截流
const title = ref("新增必到点采集");
const formRef = ref(null);
const infoActive = ref(true);
const visible = ref(false);
const fgList = ref([])
const typeStatus = ref("")

//级联选择器配置
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:modelValue', 'ok']);

const dialogFormVisible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    if (!infoActive.value && typeStatus?.value !== 'del') {
    // 获取经纬度
    setTimeout(() => {
      emitter.emit("getMapClickCoordinates");

      // 更新地图标注位置
      emitter.on("mapClickCoordinates", async (res) => {
        emitter.emit("deletePointArea")
    
        form.value.jd = res.lng
        form.value.wd = res.lat

        emitter.emit("addPointArea", {
          coords: [{ jd: res.lng, wd: res.lat }],
          coordinates: res?.coordinates,
          icon: require("@/assets/lz/dw.png"),
          sizeX: 30,
          sizeY: 35
        });
      })
    }, 500);
    } else {
        emitter.off('getMapClickCoordinates')
    }

    emits("update:modelValue", val);
  }
})

//表单数据
const form = ref({
  bddList: []
});

//表单验证
const rules = reactive({
  bddMc: [
    {
      required: true,
      message: "请填写必到点名称",
      trigger: "change"
    }
  ],
  fgdwId: [
    {
      required: true,
      message: "请选择所属方格",
      trigger: "change"
    }
  ],
  bddDz: [
    {
      required: true,
      message: "请填必到点地址",
      trigger: "change"
    }
  ],
  jd: [
    {
      required: true,
      message: "请填写经度",
      trigger: "change"
    }
  ],
  wd: [
    {
      required: true,
      message: "请填写纬度",
      trigger: "change"
    }
  ],
});

// 获取方格
const getFgList = async () => {
  const res = await fetchTbZdxlFgdwSelectList()
  if (res && res?.length > 0) {
    fgList.value = res
  }
}

// 获取方格详情
const getFgDetails = async (id, type) => {
  const res = await fetchTbZdxlFgdwId(id)
  if (res) {
    setMap(res, type)
  }
}


//新增
function open(row = {}, type) {
  typeStatus.value = type
  infoActive.value = type === 'view';
  form.value = { ...row, xfbbName: row?.xfxz };
  if (type === 'view') {
    title.value = "查看信息"
  } else if (type === 'del') {
    title.value = "编辑必到点采集"
  } else {
    title.value = "新增必到点采集"
  }

  if (type === 'view' || type === 'del') {
    getFgDetails(form?.value?.fgdwId , !(type === 'view' || type === 'del'))
  }
  dialogFormVisible.value = true;
}

//关闭弹窗
function close() {
  formRef.value.resetFields();
  dialogFormVisible.value = false;
}


const handleChange = (val) => {
  const data = fgList?.value?.find(i => i?.id === val)
  setMap(data)
}

const setMap = (data, type = true) => {
  emitter.emit("deletePointArea", "addfg")
  const { x1 = "", y1 = "", x2 = "", y2 = "", id = "", zxX = "", zxY = "", mc = "" } = data
  const centerPoint = [zxX, zxY]
  const position = [[Number(x1),Number(y1)],[Number(x2),Number(y2)]]
  const text = mc
  const obj = [{ position: position, text, id, userData: data}]

  emitter.emit("echoPlane", { fontColor:'#12fdb8',coords: obj, type:'rectangle', flag:'addfg', color:'rgba(2,20,51,0.5)', linecolor:'#1C97FF'})
  emitter.emit("setMapCenter", { location: centerPoint, zoomLevel: 14 });


  // 更新地图标注位置
  if (type) return
  emitter.emit("deletePointArea")
  
  emitter.emit("addPointArea", {
    coords: [{ jd: form.value?.jd, wd: form.value?.wd }],
    coordinates: [form.value?.jd, form.value?.wd],
    icon: require("@/assets/lz/dw.png"),
    sizeX: 30,
    sizeY: 35
  });
}

//提交
const submit = async () => {
  try {
    await formRef.value.validate()

    if (form.value?.id) {
      await fetchTbZdxlFgdwBddSave(form.value)
    } else {
      await fetchTbZdxlFgdwBddUpdate(form.value)  
    }

    proxy.$message({
      type: "success",
      message: "修改成功"
    });
    dialogFormVisible.value = false;
    emits("ok")

  } catch (error) {
    console.log(error);
  }
}

onMounted(() => {
  getFgList()
})

defineExpose({ open })
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

.dialog {
  .dialogWrapper {
    margin: 20px 20px 0 20px;

    .el-form--inline {
      padding: 0 0 0rem 0;
    }
  }
}

.label {
  margin-bottom: 1rem;
}
</style>
