<template>
  <Layer
    :modelValue="modelValue"
    :customHeader="true"
    :showCancel="false"
    :showConfirm="false"
    @update:modelValue="$emit('update:modelValue', $event)"
    @confirm="onConfirm"
    @cancel="onCancel"
  >
    <template>
      <view class="multi-select-title">{{ title }}</view>
      <view class="multi-select-list">
        <view
          v-for="opt in options"
          :key="opt"
          class="multi-select-tag"
          :class="{ selected: selectedSet.has(opt) }"
          @click="toggle(opt)"
        >
          <text>{{ opt }}</text>
          <image
            v-if="selectedSet.has(opt)"
            class="check-icon"
            :src="$baseUrl + 'person/icon_gou.png'"
          />
        </view>
      </view>
      <view class="multi-select-btn" @click="onConfirm"> 保存 </view>
    </template>
  </Layer>
</template>

<script setup>
import { ref, watch, computed, getCurrentInstance } from "vue";
import Layer from "./Layer.vue";

const { proxy } = getCurrentInstance();
const $baseUrl = proxy.$baseUrl;

const props = defineProps({
  modelValue: Boolean,
  title: String,
  options: { type: Array, default: () => [] },
  modelSelected: { type: Array, default: () => [] },
  max: Number,
});
const emit = defineEmits([
  "update:modelValue",
  "update:selected",
  "confirm",
  "cancel",
]);

const selected = ref([...props.modelSelected]);
watch(
  () => props.modelSelected,
  (val) => (selected.value = [...val])
);

const selectedSet = computed(() => new Set(selected.value));

function toggle(opt) {
  if (selectedSet.value.has(opt)) {
    selected.value = selected.value.filter((v) => v !== opt);
  } else {
    if (!props.max || selected.value.length < props.max) {
      selected.value = [...selected.value, opt];
    }
  }
  emit("update:selected", selected.value);
}

function onConfirm() {
  emit("confirm", selected.value);
  emit("update:modelValue", false);
}
function onCancel() {
  emit("cancel");
  emit("update:modelValue", false);
}
</script>

<style lang="less" scoped>
.multi-select-btn {
  width: 686rpx;
  height: 94rpx;
  background: #d3a358;
  color: #fff;
  border-radius: 46rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  margin-top: 24rpx;
  font-size: 32rpx;
}
.multi-select-title {
  font-size: 32rpx;
  color: #222;
  font-weight: bold;
  margin-bottom: 24rpx;
}
.multi-select-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx 20rpx;
}
.multi-select-tag {
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  height: 56rpx;
  background: #ffffff;
  border-radius: 28rpx;
  color: #1d1e25;
  font-size: 24rpx;
  position: relative;
  .check-icon {
    width: 19rpx;
    height: 19rpx;
    position: absolute;
    right: 2rpx;
    top: 3rpx;
    display: block;
  }
  &.selected {
    background: #efe7da;
  }
}
</style> 