<template>
  <view>
    <view class="area">
      <view class="img" :style="{ backgroundPosition: items.position }"></view>
      <view class="area_text">{{ codeNum ? items.code : items?.country }}</view>
    </view>
    <Picker
      :data="arealist"
      ref="popupRef"
      v-model="internalCode"
      labelKey="country"
      valueKey="code"
      @confirm="confirm"
    >
      <template #pickerItem="{ item }">
        <view class="picker_item"> {{ item.country }} {{ item.code }} </view>
      </template>
    </Picker>
  </view>
</template>
<script setup>
import Picker from "./picker";
import { useSystemStore } from "@/store";
import { ref, computed, watch } from "vue";
const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: null,
  },
  codeNum: Boolean,
});

const useSystem = useSystemStore();
const popupRef = ref(null);
const arealist = computed(() => useSystem.getCountryCodes);
const internalCode = ref(props.modelValue);

watch(
  () => props.modelValue,
  (newVal) => {
    internalCode.value = newVal;
  },
  { immediate: true }
);

watch(
  () => internalCode.value,
  (newVal) => {
    emit("update:modelValue", newVal);
  }
);

const emit = defineEmits(["update:modelValue", "confirm"]);

const confirm = (data) => {
  emit("confirm", data);
  emit("update:modelValue", data.code);
  internalCode.value = data.code;
};

const open = () => {
  popupRef.value && popupRef.value.open();
};
const items = computed(() => {
  let areas = JSON.parse(JSON.stringify(arealist.value));
  if (!areas || !areas.length) {
    return {};
  }
  const list = areas.find((item) => item.code == props.modelValue);
  if (!props.modelValue) {
    const defaultItem = areas[0] || {};
    internalCode.value = defaultItem.code;
    emit("confirm", defaultItem);
    return defaultItem;
  }
  emit("confirm", list);
  return list || {};
});
defineExpose({
  open,
});
</script>
<style lang="less" scoped>
.area {
  display: flex;
  align-items: center;

  .img {
    background: url(@/static/login/country_img.png) no-repeat 0 0;
    -webkit-background-size: 24px 3876px;
    background-size: 24px 3876px;
    width: 24px;
    height: 16px;
    overflow: hidden;
  }

  .area_text {
    margin-left: 10rpx;
    color: var(--black);
    font-size: 28rpx;
    line-height: 16px;
  }
}
</style>