<template>
  <van-popup v-model:show="props.show" style="width: 90%">
    <div class="popupTitle">{{ popupTitle }}</div>
    <van-tabs v-model:active="active" color="#3e6ee8" @change="onActive">
      <van-tab title="全部" name="2"> </van-tab>
      <van-tab title="本部门" name="1"> </van-tab>
    </van-tabs>
    <van-search v-model="kwd" :placeholder="placeholder" @search="onUpdate" @clear="onClear" />
    <!-- 智能装备筛选条件 -->
    <div v-if="popupTitle === '选择智能装备'" class="zn_tag_select">
      <van-tag type="primary" :plain="tagCode == '' ? false : true" style="margin-right: 3vw"
        @click="onClickTag('')">全部</van-tag>
      <van-tag type="primary" :plain="tagCode == '86' ? false : true" style="margin-right: 3vw"
        @click="onClickTag('86')">对讲机</van-tag>
      <van-tag type="primary" :plain="tagCode == '80' ? false : true" @click="onClickTag('80')">执法记录仪</van-tag>
    </div>

    <div v-if="popupTitle === '选择警用器械'" class="zn_tag_select">
      全选 <span class="squre" @click="onClickTagJyqx" :class="isAllQx ? 'isActiveAll' : ''"> <van-icon v-if="isAllQx"
          color="#fff" name='success' /> </span>
    </div>

    <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" />
      <van-loading type="spinner" v-show="loadingShow" style="text-align: center;" />
    </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, nextTick } from "vue";
import { dateFormat, hintToast } from "../utils/tools";
const props = defineProps({
  selectType: String, //查询的类型  详情见watch 监听
  bclx: String, //勤务班次类型
  dwlx: String, // 快反点/检查站 类型 01快反点 02检查站
  show: Boolean, //是否显示
  checkedList: Array, //默认选中 多选
  checked: String, //单选
  xfqSx:String,//巡防区属性 01.基本巡区 02.叠加巡区 03.护校巡区")
});
const emits = defineEmits([
  "update:cancel",
  "update:confirm",
  "update:kwd",
  "update:tabs",
  "update:tag",
]);
const loadingShow=ref(false)
const hasChoosZb = ref([])
const isAllQx = ref(false)
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 selectedPageLast = ref([]) //上一次当前页面选中
const selectObj = ref([]); //选中的数据
const active = ref(0); //默认的TBS 选择
const tagCode = ref(""); //智能设备选中状态
const placeholder = ref(""); //占位字符
const showEmpty = ref(false);
const isUserDept = ref(2); //是否是用户本部门
const kwd = ref(""); //选择器关键字
const selectIndex = ref(1); //选择器组件KEY
const selectType = ref(""); //选择的类型
const znzbCode = ref(""); //智能装备类型筛选
const popupTitle = ref(""); //标题
const isRadio = ref(false); //是否是单选
const list = reactive({
  jzList: [],
  fzrList: [],
  fjList: [],
  zbList: [],
  jyqxList: [],
  clList: [],
  mulChooseList: [],
  xfqList: [],
  kfdList: [],
  bcList: [],
});
const isFirst = ref(true)
const listData = ref([]) //缓存列表数据
watch(
  () => props.selectType,
  (newValue) => {
    checkedLists.value = props.checkedList;
    selectedPageLast.value = props.checkedList
    radioChecked.value = props.checked;
  },
  { immediate: true, deep: true }
);
onMounted(() => {
  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 ==  Math.ceil(scrollTop)) {
      //滚动条滚到最底部
      if (list.mulChooseList.length < total.value) {
        loadingShow.value=true;
        page.value++;
        _getSelectData(props.selectType);
      }
    }
  };
}

//tabs筛选
function onActive(val) {
  isUserDept.value = val;
  list.mulChooseList = [];
  page.value = 1;
  total.value = 0;
  selectedPageLast.value = []
  _getSelectData(props.selectType);
}
//获取数据
function _getSelectData(val) {
  let obj = {}; //亲求路径及参数
  switch (val) {
    case "xz":
      popupTitle.value = "选择巡组";
      placeholder.value = "请输入巡组名称";
      obj["url"] = "/mosty-qwzx/tbQwXfbb/selectJmxz";
      obj["xz"] = "xz";
      isRadio.value = false;
      break;
    case "kfd":
      popupTitle.value = "选择快反点";
      placeholder.value = "请输入快反点名称或部门名称";
      obj["url"] = "/mosty-jcgl/tpJcglKfd/getKfdList";
      isRadio.value = true;
      break;
    case "jcz":
      popupTitle.value = "选择警务站";
      placeholder.value = "请输入警务站名称或部门名称";
      obj["url"] = "/mosty-jcgl/tpJcglKfd/getKfdList";
      isRadio.value = true;
      break;
    case "xfq":
      popupTitle.value = "选择巡防区";
      placeholder.value = "请输入巡防区名称或部门名称";
      obj["url"] = "/mosty-jcgl/tbJcglXfqy/getXfqList";
      isRadio.value = false;
      break;
    case "qwbc":
      popupTitle.value = "选择班次";
      placeholder.value = "请输入班次名称或部门名称";
      obj["url"] = "/mosty-qwzx/tbQwQwbc/getBcList";
      isRadio.value = true;
      break;
    case "fzr":
    case "mj":
    case "zbld":
    case "zhz":
    case "zzzhz":
    case "fz":
      popupTitle.value = "选择民警";
      placeholder.value = "请输入姓名或部门名称";
      obj["url"] = "/mosty-jcgl/tbJcglXfll/getXfllList";
      obj["jllx"] = "01";
      isRadio.value = false;
      if (val == "fzr" || val == "zbld" || val == "zhz" || val == "zzzhz" || val == "fz") {
        isRadio.value = true;
      }
      break;
    case "fj":
      popupTitle.value = "选择辅警";
      placeholder.value = "请输入姓名或部门名称";
      obj["url"] = "/mosty-jcgl/tbJcglXfll/getXfllList";
      obj["jllx"] = "02";
      isRadio.value = false;
      break;
    case "zn":
      popupTitle.value = "选择智能装备";
      placeholder.value = "请输入设备名称或部门名称";
      obj["url"] = "/mosty-jcgl/tpjcglZnzb/getZnzbList";
      obj["scode"] = tagCode.value;
      isRadio.value = false;
      break;
    case "jy":
      popupTitle.value = "选择警用器械";
      placeholder.value = "请输入器械名称";
      obj["url"] = "/mosty-jcgl/tpJcglJyqx/getJyqxList";
      isRadio.value = false;
      break;
    case "cl":
      popupTitle.value = "选择巡防车辆";
      placeholder.value = "请输入车牌号或部门名称";
      obj["url"] = "/mosty-jcgl/tpJcglXfcl/selectXfclList";
      break;
    case "jz":
      popupTitle.value = "选择警组";
      placeholder.value = "请输入警组名称或部门名称";
      obj["url"] = "/mosty-jcgl/tbJcglJz/selectJzList";
      isRadio.value = true;
  }
  if (Object.keys(obj).length > 0) _getBBData(obj, val);
}
//获取数据
function _getBBData(obj, type) {
  //url 请求地址，jllx 警力类型  有需要就传，scode 智能装备筛选条件  有需要就传
  let { url, jllx, scode, xz } = obj;
  loading.value = true;
  let data = {
    type: isUserDept.value,
    keyword: kwd.value,
    bclx: props.bclx,
    dwlx: props.dwlx,
    xfqSx: props.xfqSx,
    jllx,
    scode,
    pageCurrent: page.value,
    pageSize: size.value,
  };
  getBBData(url, data).then((res) => {
    loadingShow.value=false;
    loading.value = false;
    total.value = res.total;
    if (jllx || xz) {
      if (res && res.records && res.records.length > 0) {
        _setData(res.records, type);
      } else {
        showEmpty.value = true;
      }
    } else {
      if (res && res.length > 0) {
        _setData(res, type);
      } else if (res && res.records) {
        _setData(res.records, type);
      } else {
        showEmpty.value = true;
      }
    }
    let dataLen = list.mulChooseList.length
    if (props.checkedList.length == dataLen && dataLen != 0 && popupTitle.value == '选择警用器械') {
      isAllQx.value = true
    } else {
      isAllQx.value = false
    }
  })
    .catch((err) => {
      loading.value = false;
      showEmpty.value = true;
    });
}
//智能装备选择
function onClickTag(code) {
  list.mulChooseList = [];
  page.value = 1;
  total.value = 0;
  if (tagCode.value && tagCode.value == code) {
    tagCode.value = "";
  } else {
    tagCode.value = code;
  }
  _getSelectData(props.selectType);
}
//搜索关键词
function onUpdate(val) {
  page.value = 1;
  list.mulChooseList = [];
  selectedPageLast.value = []
  _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);
  let dataLen = list.mulChooseList.length
  if (checkedLists.value.length == dataLen && dataLen != 0 && popupTitle.value == '选择警用器械') {
    isAllQx.value = true
  } else {
    isAllQx.value = false
  }

  if (popupTitle.value === '选择智能装备') {
    let arr = []
    list.mulChooseList.forEach(item => {
      val.forEach(itChid => {
        if (item.id == itChid) arr.push(item)
      })
    })
    hasChoosZb.value = [...hasChoosZb.value, ...arr]
  }
}
function onClickTagJyqx() {
  isAllQx.value = !isAllQx.value
  if (isAllQx.value) {
    checkedLists.value = list.mulChooseList.map(item => { return item.id })
  } else {
    checkedLists.value = []
  }
  _backData(checkedLists.value);
}
//确认选择
function onConfirm() {
  if (popupTitle.value === '选择智能装备') {
    //  去重
    let list = []
    for (let j = 0; j < checkedLists.value.length; j++) {
      let item = checkedLists.value[j]
      for (let i = 0; i < hasChoosZb.value.length; i++) {
        let itemchid = hasChoosZb.value[i]
        if (item == itemchid.id) {
          list.push(itemchid)
          break;
        }
      }
    }
    emits("update:confirm", list);
  } else {
    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 = [];
    let lastChoose = selectedPageLast.value //上一次选中
    if (lastChoose.length > 0) {
      lastChoose.forEach(it => { //上一次
        if (!val.includes(it)) {
          selectObj.value = selectObj.value.filter(item => { return item.key != it }) // 在上一次情况下删除
        }
        val.forEach(id => { //现在选中的
          if (!lastChoose.includes(id)) arr.push(findItem(id)) //在上一次的情况下新增
        })
      })
    } else {
      val.forEach(id => { arr.push(findItem(id)) })
    }
    selectObj.value = selectObj.value.concat(arr)
    selectedPageLast.value = JSON.parse(JSON.stringify(val)); //缓存当前页面数据
    let listVrr = []
    selectObj.value.forEach(item => { if (!listVrr.includes(item) && item) listVrr.push(item) }) //去重
    selectObj.value = listVrr;
  }
}

const findItem = (id) => {
  let obj = listData.value.find(v => { return v.key == id })
  return obj
}

//设置数据
function _setData(res, type) {
  for (let i = 0; i < res.length; i++) {
    switch (type) {
      case "qwbc":
        res[i].value = `${res[i].ssbm}-${res[i].bcmc}`;
        res[i].key = res[i].id;
        break;
      case "xfq":
        res[i].value = `${res[i].ssbm}-${res[i].xfqMc}`;
        res[i].key = res[i].id;
        break;
      case "kfd":
        res[i].value = `${res[i].ssbm}-${res[i].kfdMc}`;
        res[i].key = res[i].kfdId;
        break;
      case "jcz":
        res[i].value = `${res[i].ssbm}-${res[i].kfdMc}`;
        res[i].key = res[i].kfdId;
        break;
      case "jz":
        res[i].value = `${res[i].ssbm}-${res[i].jzMc}`;
        res[i].key = res[i].id;
        break;
      case "fzr":
      case "mj":
      case "zbld":
      case "zhz":
      case "zzzhz":
      case "fz":
        // res[i].value = `${res[i].ssbm}-${res[i].xm}`;
        res[i].value = `${res[i].xm}`;
        res[i].key = res[i].ryid;
        break;
      case "fj":
        // res[i].value = `${res[i].ssbm}-${res[i].xm}`;
        res[i].value = `${res[i].xm}`;
        res[i].key = res[i].id;
        break;
      case "cl":
        res[i].value = `${res[i].ssbm}-${res[i].cph}`;
        res[i].key = res[i].cid;
        break;
      case "zn":
        res[i].value = `${res[i].ssbm}-${res[i].sbmc}`;
        res[i].key = res[i].id;
        break;
      case "jy":
        res[i].value = `${res[i].ssbm}-${res[i].qxMc}`;
        res[i].key = res[i].id;
        break;
      case "xz":
        res[i].value = `${res[i].jzMc || res[i].fzrXm + "组"}`;
        res[i].key = res[i].id;
        break;
    }
  }
  listData.value = listData.value.concat(res)
  if ((page.value == 1)) {
    list.mulChooseList = res;
  } else {
    list.mulChooseList = list.mulChooseList.concat(res);
  }
  if (isFirst.value) {
    let arr = []
    selectedPageLast.value.forEach(id => {
      arr.push(findItem(id))
    })
    selectObj.value = arr;
    isFirst.value = false
  }

  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>