<template>
  <div>
    <TopNav navTitle="待办" :showRight="false" :showLeft="false" />
    <van-sticky>
      <div class="sticky_box">
        <Tabs :list="tabs" @onYjjb="onSelect" :type="'car'" :checked="tabsKey" :key="tabsIndex"></Tabs>
        <Search v-model="kwd" :isSx="true" @update:sx="showPopup = !showPopup" placeholder="请输入关键字"
          @update:modelValue="onClickSearch"></Search>
      </div>
    </van-sticky>
    <SxPopup :showPopup="showPopup" :list="queryData.sxList" :p_top="145" @update:close="showPopup = false"
      @update:onConfirm="onConfirm" />
    <van-pull-refresh v-model="loadingPull" @refresh="onRefresh">
      <van-list :finished="finished" finished-text=" " @load="onLoad" offset="1" :immediate-check="false">
        <div class="rw_list_box" v-for="item in rwObj.rwList" :key="item.id" @click="
          onLookRw(
            item.id,
            item.rwxl,
            item.rwlx,
            item.ywid,
            item.rwzt,
            item.grrwzt,
            item.rwid
          )
          ">
          <SwiperCell :item="item" @click:Transmit="onClickTransmit" @click:onDown="onClickDown"
            :dict="{ D_BZ_GRRWZT }"></SwiperCell>
        </div>
      </van-list>
      <van-loading style="text-align: center" v-if="listLoading">加载中...</van-loading>
      <van-empty description="暂无任务信息" v-if="showEmpty" />
    </van-pull-refresh>
    <!-- 底部tas -->
    <BottomTabs type="rw" />
    <div style="height: 15.8666vw"></div>
    <!-- 转发人数据 -->
    <van-popup v-model:show="showfzrPicker" position="bottom">
      <van-search v-model="list.phone" placeholder="请输入电话号码" @update:model-value="getLdList()" />
      <van-picker :columns="list.fzrList" @confirm="onfzrConfirm" @cancel="showfzrPicker = false"
        :columns-field-names="customfzrFieldNamed" />
    </van-popup>
  </div>
</template>

<script>
export default {
  name: "rw",
};
</script>
<script setup>
import { ref, onMounted, reactive, watch } from "vue";
import SxPopup from "../../components/SxPopup.vue";
import SwiperCell from "../../components/swiperCell.vue";
import Tabs from "../../components/tabs.vue";
import BottomTabs from "../../components/bottomTabs.vue";
import TopNav from "../../components/topNav.vue";
import { getMyTaskList, getMyTaskTotal, upGrzt } from "../../api/rwzx.js";
import router from "../../router/index.js";
import { sysUser } from "../../api/patrolBasicInfo.js";
import { Dialog } from "vant";
import { setTimeQuantum } from "../../utils/tools";
import Search from "../../components/search.vue";
import { transmitTask } from "../../api/yyzxApi.js";
import { getDictList, setDict } from "../../utils/dict";
import { useRoute, onBeforeRouteLeave } from "vue-router";

const { D_BZ_GRRWZT, D_BZ_RWXL } = getDictList("D_BZ_GRRWZT", "D_BZ_RWXL"); //字典信息
const showfzrPicker = ref(false); //是否显示转发人弹窗
const showPopup = ref(false);
//搜索配置
const queryData = reactive({
  sxList: [setTimeQuantum()],
});
const list = reactive({
  phone: "", //转发人手机号
  fzrList: [], //转发人数据
});
const tabsIndex = ref(1);
//指定picker选择器字段
const customfzrFieldNamed = {
  text: "userName",
};
const tabs = ref([
  {
    name: "全部",
    count: 0,
    value: "all",
  },
]);
watch(
  () => D_BZ_RWXL.value,
  () => {
    tabs.value.push(
      ...D_BZ_RWXL.value.map((item) => {
        return {
          name: item.text,
          count: 0,
          value: item.value,
        };
      })
    );
    _getMyTaskTotal();
  },
  {
    deep: true,
  }
);
const themeType = ref(getStorage("themeSetting"));
const active = ref(1);
const kwd = ref(""); //搜索关键字
const pageSize = ref(10);
const pageCurrent = ref(1);
const tabsKey = ref(0);
const userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
const rwObj = reactive({
  rwList: [], //任务数据
  rwTotal: {}, //任务统计
});
const rwjxzt = ref(""); //查询类型
const listLoading = ref(false);
const loadingPull = ref(false);
const finished = ref(false);
const total = ref(0);
const rwId = ref(""); //操作的任务ID
const showEmpty = ref(false);

//搜索框背景颜色
const searchBack = ref({});
onMounted(() => {
  if (useRoute().query.tabsType) {
    tabsKey.value = useRoute().query.tabsType;

    rwjxzt.value = "05";
  }
  // rwjxzt.value
  _getMyTaskList();
  // _getMyTaskTotal();
  getLdList();
});
//下拉刷新
function onRefresh() {
  tabs.value[0].count = 0;
  rwObj.rwList = [];
  pageCurrent.value = 1;
  kwd.value = "";
  tabsIndex.value++;
  finished.value = false;
  _getMyTaskList();
  _getMyTaskTotal();
}
//判断任务是暂停和关闭
function _setRwNotify(rwzt) {
  if (rwzt == 1) {
    hintToast("任务已关闭！！！");
    return false;
  }
  if (rwzt == 2) {
    hintToast("任务已暂停！！！");
    return false;
  }
  return true;
}
//点击转发按钮打开人员选择器
function onClickTransmit(val) {
  if (!_setRwNotify(val.rwzt)) {
    return;
  }
  rwId.value = val.id;
  showfzrPicker.value = true;
}
//驳回任务
function onClickDown(val) {
  if (!_setRwNotify(val.rwzt)) {
    return;
  }
  Dialog.confirm({
    title: "提示",
    message: "是否确认驳回该条任务信息！",
    confirmButtonColor: "#3e6ee8",
  }).then((res) => {
    _setTransmitTask(rwId.value, 4);
  });
}
//确认转发任务
function onfzrConfirm(val) {
  Dialog.confirm({
    title: "提示",
    message: "是否确认转发任务!",
    confirmButtonColor: "#3e6ee8",
  }).then((res) => {
    _setTransmitTask(rwId.value, 3, val.id);
  });
}
/**
 * 设置任务状态
 * @export
 * @param {*} rwid
 * @param {*} rwzt 1 进行中  2 已完成  3 已转发  4 已驳回
 * @param {*} zfjsrid 转发人ID
 */
function _setTransmitTask(rwid, rwzt, zfjsrid) {
  let data = { rwid, rwzt, zfjsrid };
  try {
    let location = JSON.parse(bridge.getLocation());
    data.jd = location.app_x;
    data.wd = location.app_y;
  } catch (error) { }
  transmitTask(data).then((res) => {
    showfzrPicker.value = false;
    if (rwzt != 1) {
      hintToast("成功");
    }
    _getMyTaskList();
  });
}
// 查询转发人数据
function getLdList() {
  sysUser({
    current: 1,
    size: 50,
    phone: list.phone,
  }).then((res) => {
    list.fzrList = res.records;
  });
}
//查看任务详情
function onLookRw(id, rwxl, rwlx, ywid, rwzt, grrwzt, rwid) {
  if (!_setRwNotify(rwzt)) {
    return;
  }
  if (grrwzt === "0") {
    upGrzt({ rwid: rwid, rwzt: "1" });
  }
  //通知任务
  if (rwlx == 1) {
    router.push(`/rw/views/rwDetail?id=${rwid}`);
    return;
  }
  //值班任务
  if (rwxl == "04") {
    router.push("/yyzx/views/addZbbb");
    return;
  }
  //巡防任务
  if (rwxl == "03") {
    router.push("/yyzx/xfbb/addXfbb");
    return;
  }
  //指令任务
  if (rwxl == "05") {
    router.push(`/yyzx/zlzx/zlDetail?id=${ywid}`);
    return;
  }
  //实有人口任务
  if (rwxl == "01") {
    router.push(`/rw/views/syrkRwDetail?id=${rwid}`);
    return;
  }
}
function onConfirm(val) {
  rwObj.rwList = [];
  timeObj.kssj = val.startTime;
  timeObj.jssj = val.endTime;
  _getMyTaskList();
  showPopup.value = false;
}
//关键字搜索
function onClickSearch(e) {
  rwObj.rwList = [];
  pageCurrent.value = 1;
  _getMyTaskList();
}
//按类型查询
function onSelect(val) {
  rwObj.rwList = [];
  pageCurrent.value = 1;
  switch (val) {
    case 0:
      rwjxzt.value = "";
      break;
    default:
      rwjxzt.value = tabs.value[val].value;
      break;
  }
  _getMyTaskList();
}
//获取任务统计
function _getMyTaskTotal() {
  getMyTaskTotal({ sfzh: userInfo.idEntityCard }).then((res) => {
    if (res) {
      res.forEach((e) => {
        tabs.value[0].count += e.count;
      });
      tabs.value.forEach((v) => {
        const tjarr = res.filter((item) => item.rwxl === v.value);
        if (tjarr.length > 0) {
          v.count = tjarr[0].count;
        }
      });
    }
  });
}
//触底加载
function onLoad() {
  if (pageCurrent.value >= total.value) {
    finished.value = true;
    return;
  }
  pageCurrent.value += 1;
  _getMyTaskList();
}
const timeObj = reactive({
  kssj: "",
  jssj: "",
});
//获取任务列表
function _getMyTaskList() {
  listLoading.value = true;
  showEmpty.value = false;
  let data = {
    pageSize: pageSize.value,
    pageCurrent: pageCurrent.value,
    jsrsfzh: userInfo.idEntityCard,
    rwnr: kwd.value,
    // grrwzt: rwjxzt.value,
    rwxl: rwjxzt.value,
    kssj: timeObj.kssj,
    jssj: timeObj.jssj,
  };
  getMyTaskList(data)
    .then((res) => {
      total.value = res.pages;
      listLoading.value = false;
      loadingPull.value = false;
      if (res.records.length > 0) {
        res.records.forEach((item) => {
          rwObj.rwList.push(item);
        });
      } else {
        showEmpty.value = true;
      }
    })
    .catch((err) => {
      listLoading.value = false;
      showEmpty.value = true;
    });
}
</script>

<style lang="scss" scoped>
@import "../../assets/styles/mixin.scss";

.rw_list_box {
  padding: 3vw 0;
  margin: 0 3vw;
  @include font_size($font_medium_s);
  @include font_color($font-color-theme);
  @include item_bottom_color($bottom-border-top-clore-theme);
}
</style>
