<template>
  <popupSelect
    ref="popupRef"
    title="请选择服务宠物类型"
    desc="（可多选）"
    @confirm="onConfirm"
  >
    <view class="flex-between content">

      <view class="type" 
        v-for="item in petTypeOptions"
        :key="`petType-${item.id}`"
        @click="onSelectPetType(item.id)"
      >
        <image :src="item.imageNo" mode="widthFix"></image>
        <template v-if="petTypes.includes(item.id)">
          <image class="active" :src="item.image" mode="widthFix"></image>
          <view class="active-icon">
            <up-icon name="checkmark-circle" color="#FFBF60" size="32rpx"></up-icon>
          </view>
        </template>
      </view>

    </view>
  </popupSelect>
</template>

<script setup>
  import { ref, computed } from 'vue'
	import { useStore } from 'vuex'

  import popupSelect from '../components/popupSelect.vue';

	const store = useStore()

  const props = defineProps({
    modelValue: {
      type: Array,
      default() {
        return []
      }
    }
  })

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

  const petTypes = ref([])

  const petTypeOptions = computed(() => {
		return store.getters.petTypeOptions
	})

  const onSelectPetType = (type) => {
    const oldTypes = petTypes.value
    let newTypes = []

    if (oldTypes.includes(type)) {
      newTypes = oldTypes.filter(item => item !== type)
    } else {
      newTypes = oldTypes.concat(type)
    }

    petTypes.value = newTypes
  }

  const popupRef = ref()

  const open = () => {
    store.dispatch('fetchPetTypeOptions')
    petTypes.value = props.modelValue
    popupRef.value.open()
  }

  const close = () => {
    popupRef.value.close()
  }
  
  const onConfirm = () => {
    emit('update:modelValue', petTypes.value)
    emit('confirm')
  }

  defineExpose({ open, close })

</script>

<style lang="scss" scoped>

  .content {
    padding: 46rpx 26rpx;
  }

  .type {
		width: 190rpx;
		position: relative;

		image {
			width: 100%;
		}

		.active {
			position: absolute;
			top: 0;
			left: 0;

      &-icon {
  			position: absolute;
        top: 14rpx;
        right: 18rpx;
      }
		}
	}
</style>