<template>
  <div class="kSelectPopIdx">
    <van-popup v-model:show="selPopShow" round position="bottom">
      <div class="o-ptb-10 l-re">
        <div class="o-plr-20 o-mb-20 l-flex-between">
          <div @click="selPopShow = false" class="c-text-16 c-color">{{ $t('kSelectPop.cancel') }}</div>
          <div class="c-text-16 c-text-b">{{ $t('kSelectPop.selectTitle') }}</div>
          <div @click="confirmClk" class="c-text-16 c-text-color">{{ $t('kSelectPop.confirm') }}</div>
        </div>
        <van-search v-model="searchValue" :placeholder="$t('kSelectPop.searchKey')" shape="round" background="#4d6add"
          @update:model-value="valueChange" />
        <div style="height: 50vh;overflow:hidden;overflow-y:auto;">
          <!-- 全选 -->
          <van-checkbox-group v-model="allChecked" ref="allCheckRef">
            <van-cell-group inset>
              <van-cell :title="$t('kSelectPop.allCheck')" @click="checkAll">
                <template #right-icon>
                  <van-checkbox name="all" @click="checkAll" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
          <div class="content">
            <van-checkbox-group v-model="checked" ref="checkboxGroup">
              <van-cell-group inset>
                <div v-for="(item, index) in props.selOptions" :key="index" class="kBordBott">
                  <van-cell :border="false" :title="item[selTitleAndName[0]]" @click="toggle(index)">
                    <template #right-icon>
                      <van-checkbox @click.stop="toggle(index)" :name="item[selTitleAndName[0]]"
                        :ref="(el) => (checkboxRefs[index] = el)" />
                    </template>
                  </van-cell>
                </div>
              </van-cell-group>
            </van-checkbox-group>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
/**
 * kSelectPop 选择弹窗组件
 * @description 本组件主要是用于单选或多选的组件。
 *
 */
import { ref, onBeforeUpdate } from "vue";
export default {
  props: {
    selOptions: {
      type: Array,
      default: () => {
        return [];
      },
    },
    selTitleAndName: {
      type: Array,
      default: () => {
        return ["name", "id"];
      },
    },
  },
  setup(props, { emit }) {
    // 点击确定按钮
    const confirmClk = () => {
      // console.log("选中", checked.value);
      let checkedOptions = [];
      props.selOptions.forEach((item) => {
        if (checked.value.includes(item.name) || (item.username != null && checked.value.includes(item.username)) || (item.clientId != null && checked.value.includes(item.clientId))) {
          checkedOptions.push(item.id);
        }
      })
      // console.log("checkedOptions", checkedOptions);
      emit("selconfirm", checked.value, checkedOptions);
    };
    // 搜索关键词
    const searchValue = ref('');
    const tempOptions = ref([]);
    const valueChange = () => {
      if (tempOptions.value.length == 0) {
        tempOptions.value = props.selOptions;
      }
      let newOptions = [];
      tempOptions.value.forEach((item) => {
        if (item.name.includes(searchValue.value) || (item.username != null && item.username.includes(searchValue.value)) || (item.clientId != null && item.clientId.includes(searchValue.value))) {
          newOptions.push(item);
        }
      })
      emit("searchData", newOptions);
      if (checked.value.length === tempOptions.value.length) {
        allCheckRef.value.toggleAll(true);
        checkboxGroup.value.toggleAll(true);
      } else {
        allCheckRef.value.toggleAll(false);
      }
    }
    // 全选
    const allCheckRef = ref(null);
    const allChecked = ref([]);
    // 点击全选
    const checkAll = () => {
      // 如果已存在全选，那么是取消
      if (allChecked.value.length > 0) {
        allCheckRef.value.toggleAll(false);
        checkboxGroup.value.toggleAll(false);
      } else {
        allCheckRef.value.toggleAll(true);
        checkboxGroup.value.toggleAll(true);
      }
    };

    // 弹窗是否显示
    const selPopShow = ref(false);
    const selPopOpen = (selectedOpt) => {
      if (selectedOpt) {
        // 找到选中的值在所有值里面的下标，做切换状态
        if (props.selOptions.length > 0) {
          console.log('selectedOpt', selectedOpt)
          checked.value = selectedOpt;
        }
      } else {
        // 请空选中的值
        checked.value = [];
        allChecked.value = [];
      }
      selPopShow.value = true;
    };
    // 关闭弹窗
    const selPopClose = () => {
      selPopShow.value = false;
    };
    // 单选
    const checkboxGroup = ref(null);
    const checked = ref([]);
    const checkboxRefs = ref([]);
    const toggle = (index) => {
      // 单个选中状态切换
      checkboxRefs.value[index].toggle();
      console.log("tempOptions.value.length", tempOptions.value.length)
      // 如果选中的长度和选项的长度相等，那么全选要选中状态
      if (checked.value.length === tempOptions.value.length) {
        allCheckRef.value.toggleAll(true);
      } else {
        allCheckRef.value.toggleAll(false);
      }
    };
    // 每次更新前恢复单个ref
    onBeforeUpdate(() => {
      checkboxRefs.value = [];
    });
    return {
      props,
      selPopShow,
      selPopOpen,
      toggle,
      checked,
      checkboxRefs,
      checkAll,
      checkboxGroup,
      allChecked,
      allCheckRef,
      confirmClk,
      selPopClose,
      searchValue,
      valueChange
    };
  },
};
</script>

<style lang="less" scoped>
.kSelectPopIdx {
  .content {
    .kBordBott {
      &:last-child {
        border-bottom: none;
      }
    }
  }
}
</style>