<template>
  <popupSelect
    ref="popupRef"
    title="请选择增值服务"
    @confirm="onConfirm"
  >
    <view class="content">
      <view class="flex-between option"
        v-for="(option, index) in increaseServiceOptions"
        :key="index"
        @click="onSelectServe(option.id)"
      >
        <view class="option-info"
        v-if="option && isNeedCertificate(option.needCertificate)">
          <view class="option-title">{{ option.title }}</view>
          <view class="option-desc">{{ option.detail }}</view>
        </view>
        <up-icon 
        v-if="option && isNeedCertificate(option.needCertificate)"
          name="checkmark-circle-fill" 
          :color="serves.includes(option.id) ? '#FFBF60' : '#BDBDBD'" 
          size="46rpx"
        ></up-icon>
      </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 []
      }
    },
    certificate: {
      type: String,
      default: ''
    }
  })

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

  const serves = ref([])
  
	const increaseServiceOptions = computed(() => {
		return store.getters.increaseServiceOptions || []
	})

  const onSelectServe = (serve) => {
    const oldServes = serves.value
    let newServes = []

    if (oldServes.includes(serve)) {
      newServes = oldServes.filter(item => item !== serve)
    } else {
      newServes = oldServes.concat(serve)
    }

    serves.value = newServes
  }

  function isNeedCertificate(needCertificate) {
    if (!needCertificate || typeof needCertificate !== 'string') {
      return true
    }

    let a = false

    const needCertificateArr = needCertificate.split(';')
    const certificateArr = props.certificate ? props.certificate.split(';') : []


    needCertificateArr.forEach(item => {
      if (certificateArr.includes(item)) {
        a = true
      }
    })

    return a
  }

  const popupRef = ref()

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

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

  defineExpose({ open, close })

</script>

<style lang="scss" scoped>

  .content {
    padding-bottom: 25rpx;
  }

  .option {
    padding: 0 49rpx 0 25rpx;
    background-color: #FFF5E5;
    border-radius: 8rpx;

    & + & {
      margin-top: 12rpx;
    }

    &-info {
      padding: 7rpx 0 13rpx 0;
    }

    &-title {
      color: #000000;
      font-size: 28rpx;
      line-height: 37rpx;
    }

    &-desc {
      margin-top: 12rpx;
      color: #707070;
      font-size: 20rpx;
      line-height: 26rpx;
    }
  }

</style>