<template>
  <van-popup v-model:show="props.show" style="width: 90%">
    <div class="popupTitle">{{ popupTitle }}</div>
    <van-search v-model="kwd" :placeholder="placeholder" @search="onUpdate" @clear="onClear" />
    <div class="check-data-box" ref="listBox" :loading="loading">
      <!-- 单选 -->
      <van-radio-group v-model="radioChecked" v-if="isRadio">
        <van-cell-group>
          <van-cell v-for="item in list.mulChooseList" clickable :key="item" :title="`${item.value}`" :border="false">
            <template #right-icon>
              <van-radio :name="item.key" @click="onRadionChange(item.key)" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
      <!-- 多选 -->
      <van-checkbox-group v-model="checkedLists" v-else @change="onCheckboxnChange">
        <van-cell-group>
          <van-cell v-for="item in list.mulChooseList" clickable :key="item" :title="`${item.value}`">
            <template #right-icon>
              <van-checkbox shape="square" :name="item.key" />
            </template>
            <template #label v-if="title === '选择警用器械'">
              数量：
              <van-stepper v-model="item.sl" integer />
            </template>
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
      <van-empty description="没有数据" image="default" v-if="list.mulChooseList.length <= 0 && showEmpty" />
    </div>
    <div class="popbtn-box">
      <van-button style="flex: 1" type="default" @click="onCancel">取消
      </van-button>
      <van-button style="flex: 1" type="primary" @click="onConfirm">确定</van-button>
    </div>
  </van-popup>
</template>

<script setup>
import { getBBData } from "@/api/xfbbAndZbbb.js";
import { defineProps, ref, defineEmits, watch, reactive, onMounted } from "vue";
import { dateFormat, hintToast } from "@/utils/tools";
const props = defineProps({
  selectType: String, //查询的类型  详情见watch 监听
  show: Boolean, //是否显示
  checkedList: Array, //默认选中 多选
  checked: String, //单选
});
const emits = defineEmits([
  "update:cancel",
  "update:confirm",
  "update:kwd",
  "update:tabs",
  "update:tag",
]);
const hasChoosZb = ref([]);
const listBox = ref(null);
const page = ref(1);
const size = ref(10);
const total = ref(0);
const radioChecked = ref("");
const checkedLists = ref([]);
const loading = ref(false);
const finished = ref(false);
const selectObj = ref([]); //选中的数据
const tagCode = ref(""); //智能设备选中状态
const placeholder = ref(""); //占位字符
const showEmpty = ref(false);
const kwd = ref(""); //选择器关键字
const selectType = ref(""); //选择的类型
const znzbCode = ref(""); //智能装备类型筛选
const popupTitle = ref(""); //标题
const isRadio = ref(false); //是否是单选
const list = reactive({
  mulChooseList: []
});

watch(
  () => props.selectType,
  (newValue) => {
    checkedLists.value = props.checkedList;
    radioChecked.value = props.checked;
  },
  { immediate: true, deep: true }
);
onMounted(() => {
  _getSelectData(props.selectType);
  scroll();
});

//触底加载
function scroll() {
  let scrollTargetBox = listBox.value;
  if (!scrollTargetBox) return false;
  scrollTargetBox.onscroll = (e) => {
    var scrollHeight = scrollTargetBox.scrollHeight; //251
    var scrollTop = scrollTargetBox.scrollTop; //0-18
    var clientHeight = scrollTargetBox.clientHeight; //233
    if (scrollHeight - clientHeight == scrollTop) {
      //滚动条滚到最底部
      if (list.mulChooseList.length < total.value) {
        page.value++;
        _getSelectData(props.selectType);
      }
    }
  };
}

//获取数据
function _getSelectData(val) {
  let obj = {}; //亲求路径及参数
  switch (val) {
    case "xfzz":
    case "xfmj":
    case "xffj":
      popupTitle.value = "选择民警";
      placeholder.value = "请输入姓名";
      obj["url"] = "/mosty-jcgl/tbJcglXfll/getXfllList";
      obj["jllx"] = "01";
      if (val == 'xffj') {
        popupTitle.value = "选择辅警";
        obj["jllx"] = "02";
      }
      isRadio.value = false;
      if (val == "xfzz") isRadio.value = true;
      break;
    case "xfdw":
      popupTitle.value = "选择巡访单位";
      placeholder.value = "请输入单位名称";
      obj["url"] = "/mosty-jcgl/tbJcglXfDwgl";
      isRadio.value = false;
      break;
    case "xfnr":
      popupTitle.value = "选择巡访内容";
      placeholder.value = "请输入巡访内容";
      obj["url"] = "/mosty-jcgl/tbJcglXfNrmb";
      isRadio.value = true;
      break;
    case "cyry":
      popupTitle.value = "选择从业人员";
      placeholder.value = "选择从业人员";
      obj["url"] = "/mosty-jcgl/tbJcglXfCyry";
      isRadio.value = false;
      break;
  }
  if (Object.keys(obj).length > 0) _getBBData(obj, val);
}
//获取数据
function _getBBData(obj, type) {
  //url 请求地址，jllx 警力类型  有需要就传，scode 智能装备筛选条件  有需要就传
  let { url, jllx, xz } = obj;
  loading.value = true;
  let data = { keyword: kwd.value, jllx, pageCurrent: page.value, pageSize: size.value };
  if (type == 'xfnr') {
    data = { nr: kwd.value, pageCurrent: page.value, pageSize: size.value }
  }
  getBBData(url, data)
    .then((res) => {
      loading.value = false;
      total.value = res.total;
      if (jllx) {
        if (res && res.records && res.records.length > 0) {
          _setData(res.records, type);
        } else {
          showEmpty.value = true;
        }
      } else {
        if (res && res.length > 0 && !res.records) {
          _setData(res, type);
        } else if (res && res.records) {
          _setData(res.records, type);
        } else {
          showEmpty.value = true;
        }
      }
    })
    .catch((err) => {
      loading.value = false;
      showEmpty.value = true;
    });
}

//搜索关键词
function onUpdate(val) {
  page.value = 1;
  list.mulChooseList = [];
  _getSelectData(props.selectType);
}
//清空关键字
function onClear() {
  list.mulChooseList = [];
  _getSelectData(props.selectType);
}
//关闭弹窗
function onCancel() {
  emits("update:cancel", false);
}
//点击单选
function onRadionChange(val) {
  _backData(val);
}
//点击多选
function onCheckboxnChange(val) {
  _backData(val);
}

//确认选择
function onConfirm() {
  emits("update:confirm", selectObj.value);
  emits("update:cancel", false);
}
//处理返回父组件数据
function _backData(val) {
  if (typeof val == "string") {
    //单选数据
    let obj = list.mulChooseList.find((item) => {
      return item.key == val;
    });
    selectObj.value = [obj];
  } else {
    //多选数据
    let arr = [];
    for (let i = 0; i < val.length; i++) {
      for (let j = 0; j < list.mulChooseList.length; j++) {
        if (val[i] == list.mulChooseList[j].key) {
          arr.push(list.mulChooseList[j]);
        }
      }
    }
    selectObj.value = arr;
  }
}

//设置数据
function _setData(res, type) {
  for (let i = 0; i < res.length; i++) {
    switch (type) {
      case "xfzz":
      case "xfzy":
      case "xfmj":
        res[i].value = `${res[i].ssbm}-${res[i].xm}`;
        res[i].key = res[i].ryid;
        break;
      case "xffj":
        res[i].value = `${res[i].ssbm}-${res[i].xm}`;
        res[i].key = res[i].id;
        break;
      case "xfdw":
        res[i].value = `${res[i].dwmc}（电话：${res[i].lxdh}）`;
        res[i].key = res[i].id;
        break;
      case "xfnr":
        res[i].value = `${res[i].nr}`;
        res[i].key = res[i].id;
        break;
      case "cyry":
        res[i].value = `${res[i].xm}（${res[i].sfzh}）`;
        res[i].key = res[i].id;
        break;
    }
  }
  if (page.value == 1) {
    list.mulChooseList = res;
  } else {
    list.mulChooseList = list.mulChooseList.concat(res);
  }
  loading.value = false;
}
</script>
<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";

.popupTitle {
  text-align: center;
  background-color: rgb(11, 137, 247);
  height: 6vh;
  line-height: 6vh;
  color: #fff;
}

.popbtn-box {
  width: 100%;
  display: flex;
  justify-content: space-around;
  padding-top: 2vw;
}

.check-data-box {
  height: 100vw;
  overflow: auto;
}

::v-deep .van-stepper__input {
  width: 100px;
}

.zn_tag_select {
  padding: 2vw 3.5vw;
  display: flex;
  align-items: center;

  .squre {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 1px solid #cccccc;
    border-radius: 4px;
    margin-left: 10px;
    text-align: center;
    line-height: 20px;
  }

  .isActiveAll {
    background: #1989fa;
  }
}

::v-deep .van-cell {
  align-items: flex-start;
}

::v-deep .van-cell__title,
.van-cell__value {
  margin-right: 1vw;
}
</style>