<script setup lang="ts">
import {
  Cell as VanCell,
  CellGroup as VanCellGroup,
  Checkbox as VanCheckbox,
  CheckboxGroup as VanCheckboxGroup,
  Field as VanField,
  Popup as VanPopup,
  Search as VanSearch,
} from 'vant'
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'

const props = defineProps({
  columns: {
    type: Array,
    default() {
      return []
    },
  },
  selectValue: {
    type: Array,
    default() {
      return []
    },
  },
  option: {
    type: Object,
    default() {
      return { label: 'label', value: 'value' }
    },
  },
  // 是否支持搜索
  isSearch: {
    type: Boolean,
    default: true,
  },
})
const emits = defineEmits(['input', 'confirm', 'change', 'cancel'])
const { columns, selectValue, option, isSearch } = props
const show = ref(false)
const searchVal = ref('')
let columnsData = reactive(JSON.parse(JSON.stringify(columns)))
const checkboxValue = ref(JSON.parse(JSON.stringify(selectValue)))
const checkedAll = ref(false)
const resultValue = ref(JSON.parse(JSON.stringify(selectValue)))
const checkboxGroup = ref()
const checkboxes = ref()
function search(val) {
  if (val) {
    columnsData = columnsData.filter((item) => {
      return item[option.label].includes(val)
    })
  }
  else {
    columnsData = JSON.parse(JSON.stringify(columns))
  }
}
function getData(val) {
  const res = columns.filter((item) => {
    return val.includes(item[option.value])
  })
  return res
}
function onConfirm() {
  resultValue.value = checkboxValue.value
  show.value = !show.value
  emits('confirm', resultValue.value, getData(resultValue.value))
}
function change(val) {
  emits('change', val, getData(resultValue.value))
}
function cancel() {
  show.value = !show.value
  emits('cancel', resultValue.value)
}
function toggle(item, index) {
  // 假设 checkboxValue 是一个对象，我们通过 index 来切换对应 checkbox 的值
  const idx = checkboxValue.value.indexOf(item[option.value])
  if (idx !== -1) {
    checkboxValue.value.splice(idx, 1)
  }
  else {
    checkboxValue.value.push(item[option.value])
  }
}
function toggleAll() {
  // 遍历 checkboxValue 并设置所有 checkbox 的值为 checkedAll 的值
  if (checkedAll.value) {
    checkboxValue.value = columnsData.map(item => item[option.value])
  }
  else {
    checkboxValue.value = []
  }
}
function showPopu(disabled) {
  if (disabled !== undefined && disabled !== false)
    return false
  else
    show.value = !show.value
}
const stopWatchColumnsData = watch(() => columnsData, (newVal, _oldVal) => {
  checkedAll.value = newVal.length && newVal.length === checkboxValue.value.length
})
const stopWatchCheckboxValue = watch(() => checkboxValue.value.length, (newVal, _oldVal) => {
  checkedAll.value = newVal && newVal === columnsData.length
})
onBeforeUnmount(() => {
  stopWatchColumnsData?.()
  stopWatchCheckboxValue?.()
})
const resultLabel = computed({
  get() {
    return resultValue.value.join(',')
  },
  set() {

  },
})
</script>

<template>
  <div class="dh-field">
    <VanField
      v-model="resultLabel"
      v-bind="$attrs"
      readonly
      :border="false"
      :is-link="$attrs.disabled === undefined"
      @click="showPopu($attrs.disabled)"
    />
    <VanPopup v-model:show="show" position="bottom">
      <div class="van-picker__toolbar">
        <button type="button" class="van-picker__cancel" @click="cancel">
          取消
        </button>
        <div class="van-ellipsis van-picker__title">
          {{ $attrs.label }}
        </div>
        <button type="button" class="van-picker__confirm" @click="onConfirm">
          确认
        </button>
      </div>
      <div style="max-height:264px; overflow-y:auto;">
        <!--          <VanField v-if="isSearch" v-model="searchVal" input-align="left" placeholder="搜索" @update:search /> -->
        <VanSearch
          v-if="isSearch"
          v-model="searchVal"
          placeholder="搜索"
          @update:model-value="search"
          @cancel="search"
        />
        <VanCell title="全选">
          <template #right-icon>
            <VanCheckbox v-model="checkedAll" name="all" @click="toggleAll" />
          </template>
        </VanCell>
        <VanCheckboxGroup ref="checkboxGroup" v-model="checkboxValue" @change="change">
          <VanCellGroup>
            <VanCell
              v-for="(item, index) in columnsData"
              :key="item[option.value]"
              :title="item[option.label]"
              clickable
              @click="toggle(item, index)"
            >
              <template #right-icon>
                <VanCheckbox ref="checkboxes" :name="item[option.value]" @click.stop />
              </template>
            </VanCell>
          </VanCellGroup>
        </VanCheckboxGroup>
      </div>
    </VanPopup>
  </div>
</template>

<style lang="less" scoped>
.dh-field {
  width: 100%;
  padding: 0;
  background: #fff;
  .dh-cell.van-cell {
    padding: 10px 0;
  }
  .dh-cell.van-cell--required::before {
    left: -8px;
  }
  .van-popup {
    border-radius: 20px 20px 0 0;
  }
}
</style>
