<script setup>
import { defineProps, defineEmits, ref, nextTick, onMounted, onUnmounted, } from "vue"
import { useRouter } from 'vue-router'
import { useAppStore } from "@/store/app.js";

const router = useRouter()
const emit = defineEmits(['offAreaList']);
const choseArea = ref(false);

const props = defineProps({
  list: {
    type: Object,
    default: () => []
  }
})

// const list = ref([
//   {
//     name: '泸县',
//     pinyin: 'luxian',
//   },
//   // {
//   //   name: '江阳区',
//   //   pinyin: 'jiangyang',
//   // },
//   // {
//   //   name: '龙马潭区',
//   //   pinyin: 'longma',
//   // },
//   // {
//   //   name: '纳溪区',
//   //   pinyin: 'naxi',
//   // },
//   // {
//   //   name: '合江县',
//   //   pinyin: 'hejiang',
//   // },
//   // {
//   //   name: '叙永县',
//   //   pinyin: 'xuyong',
//   // },
//   // {
//   //   name: '古蔺县',
//   //   pinyin: 'gulin',
//   // },
// ])

const appStore = useAppStore();

// 选镇
const choseTownFn = (item) => {
  if (item.code.length == 6) {
    appStore.setMapInfo('luxian');
    appStore.setAddress({
      areaCode: item.code,
      streetCode: ''
    })
  } else {
    appStore.setAddress({
      areaCode: appStore.address.areaCode,
      streetCode: item.code
    })
  }
  emit('offAreaList', item);
}

const open = () => {
  choseArea.value = true;
}

const close = () => {
  choseArea.value = false;
}

const show = () => {
  choseArea.value = !choseArea.value;
}

defineExpose({
  open, close, show
})

const addressRef = ref(null);

const onClickOutside = (event) => {
  const componentElement = addressRef.value;
  if (!componentElement?.contains(event.target)) {
    choseArea.value = false;
  }
}

onMounted(() => {
  document.addEventListener('click', onClickOutside);
})

onUnmounted(() => {
  document.removeEventListener('click', onClickOutside);
})

</script>

<template>
  <transition name="fade" mode="out-in">
    <div ref="addressRef" class="address" v-if="choseArea == true">
      <div
        class="address-li"
        @click="choseTownFn(item)"
        v-for="(item, index) in list"
        :key="index"
      >
        {{ item.name }}
      </div>
    </div>
  </transition>
</template>

<style lang="scss" scoped>
.address {
  left: 1vw;
  top: 18px;
  position: absolute;
  width: 8rem;
  height: 15rem;
  background-color: #001e32;
  color: #c7dbe3;
  z-index: 9999;
  overflow-y: auto;
  box-sizing: border-box;
  padding: 5px;

  .address-li {
    padding: 2px 5px;
    cursor: pointer;

    border-bottom: 0.1px solid #0e293c;
  }
}

.address::-webkit-scrollbar {
  width: 0.63rem;
  background-color: #153041;
}

.address::-webkit-scrollbar-track {
  background-color: #153041;
}

::-webkit-scrollbar-thumb {
  background-color: #4ab9d0;
  border-radius: 5px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>