<script setup>
import { ref, reactive, onMounted } from "vue";
import TopNav from "@/components/topNav.vue";
import Tabs from "@/components/tabs.vue";
import Search from "@/components/search.vue";
import PatrolWrapper from "@/pages/patrolList/copmonents/patrolWrapper.vue";
import {fetchPatrolList} from "@/api/patrolList";
import {getDictListByCode} from "@/api/common";
import router from "@/router";
import SxPopup from "@/components/SxPopup.vue";
import SelectTime from "@/components/SelectTime.vue";
const tabsIndex = ref(1);
const showPopup = ref(false);
const timeShow = ref(false);
const finished = ref(false);
const loading = ref(false);
const rwlx=ref('1')
const loadingRefresh = ref(false);
const searchValue = ref("")
const tabs = ref([
  {
    name: "警情任务",
    value: "1",
  },
  {
    name: "自定义任务",
    value: "2",
  },
]);
const pageData = reactive({
  pageSize: 10,
  pageCurrent: 1,
  total: 0,
})

const data = reactive({
  list: [],
  dictList: [],
  startTime: ''
})

const onSearch = () => {
  loading.value = true;
  pageData.pageCurrent = 1;
  data.list = []
  getData()
}

const onRefresh = () => {
  tabsIndex.value++;
  loading.value = false;
  loadingRefresh.value = true;
  finished.value = false;
  pageData.pageCurrent = 1;
  data.list = []
  getData()
}

const onLoad = () => {
  if (data.list.length >= pageData?.total) {
    finished.value = true;
    return
  }

  pageData.pageCurrent++
  getData()
}

const handleClockInPage = (item) => {
  router.push({ path: '/clockInPage', query: { id: item.id, current: pageData.pageCurrent } });
}

const parseAndJoinLx = (jsonString, type = 'lx') => {
  if (!jsonString) return '';

  try {
    let data = jsonString;
    // 如果是字符串，尝试解析为JSON
    if (typeof jsonString === 'string') {
      data = JSON.parse(jsonString);
    }

    // 处理数组情况
    if (Array.isArray(data)) {
      return data.map(item => item?.[type]).filter(Boolean).join(",");
    }
    // 处理对象情况
    if (typeof data === 'object' && data !== null) {
      return data?.[type] || '';
    }
    return '';

  } catch (error) {
    console.warn('数据处理失败:', error);
    return '';
  }
};

const getData = async () => {
  const { total, ...ret }  = pageData
  loading.value = true;
  try {
    const res = await fetchPatrolList({ ...ret, fgMc: searchValue.value, rwRq: data.startTime,rwlx:rwlx.value })
    if (res?.records.length > 0) {
      data.list = data.list.concat(res?.records)?.map((item) => ({
        ...item,
        fgJqtjLx: parseAndJoinLx(item?.fgJqtjLx, 'lx'),
        fgYjdjLabel: data.dictList?.find(i => i.dm === item.fgYjdj)?.zdmc || item.fgYjdj
      })) || []

      pageData.total = res?.total
      loading.value = false;

    }
    loadingRefresh.value = false;

  } catch (error) {
    loading.value = false;
    loadingRefresh.value = false;
  }
}

const getDictList = async () => {
  const res = await getDictListByCode({ dictCode: 'D_ZDXL_FGXLRW_YJDJ' })
  if (res && res?.itemList?.length > 0) {
    data.dictList = res?.itemList
  }
}
//按类型查询
function onSelect(val) {
  data.list = [];
  pageData.pageCurrent = 1;
  switch (val) {
    case 0:
      rwlx.value="1"
      break;
    default:
      rwlx.value="2"
      break;
  }
  getData();
  finished.value = false;
}
const onSelectTime = (val) => {
  data.startTime = val;
  timeShow.value = false
}

const onClickTime = () => {
  timeShow.value = true;
}

const onConfirm = () => {
  pageData.pageCurrent = 1;
  data.list = []
  getData()
  showPopup.value = false;
}

const handleReset = () => {
  data.startTime = ""
  onConfirm()
}


onMounted(async () => {
  await getDictList()
  await getData()
})
</script>

<template>
  <div>
    <TopNav nav-title="巡逻列表" show-left />
    <van-sticky>
      <div class="sticky_box">
        <Tabs :list="tabs" @onYjjb="onSelect" :type="'car'" :key="tabsIndex"></Tabs>
        <search
          :isSx="true"
          placeholder="请输入方格名称进行查询"
          v-model="searchValue"
          @update:sx="showPopup = !showPopup"
          @update:modelValue="onSearch"
        />
      </div>
    </van-sticky>

    <sx-popup :showPopup="showPopup" :p_top="110" @update:close="showPopup = false"
              @update:onConfirm="onConfirm" @reset="handleReset">
      <div class="time_box">
        <van-field
          v-model="data.startTime"
          label-width="60px"
          placeholder="请选择时间"
          input-align="left"
          right-icon="arrow-down"
          readonly
          @click.stop="onClickTime"
        />
      </div>
    </sx-popup>

    <select-time v-if="timeShow" time-type="选择任务日期" @update:time="onSelectTime" @update:cancelTime="timeShow = false" />

    <div class="content">
      <van-pull-refresh v-model="loadingRefresh" @refresh="onRefresh">
        <van-list v-model:loading="loading" :finished="finished" finished-text="" @load="onLoad" offset="1" :immediate-check="false">
          <patrol-wrapper :list="data?.list" @click="handleClockInPage" />

          <van-empty description="暂无采集数据" image="default" v-if="data.list.length <= 0 && loadingRefresh === false" />
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style scoped lang="scss">
.time_box {
  padding: 0 3vw 3vw;
}

.header {
  margin-top: 13vw;
}

.content {
  margin-bottom: 16vw;
}
</style>
