<template>
  <oa-scroll
    customClass="xunjian-plan-container scroll-height"
    :refresherLoad="false"
    :refresherEnabled="false"
    :refresherEnabledTitle="false"
    :refresherDefaultStyle="'none'"
    :refresherThreshold="44"
    :refresherBackground="'#f5f6f7'"
    :data-theme="'theme-' + proxy.$settingStore.themeColor.name"
  >
    <template #default>
      <!-- 日历组件 -->
      <oaCalendar class="uni-calendar--hook" :selected="info.selected" :showMonth="false" @change="change" @monthSwitch="monthSwitch" :currentDate="currentDateList" />

      <!-- 分段器组件 -->
      <view class="app-subsection">
        <u-subsection :list="list" :current="tabPosition" inactiveColor="#303133" :activeColor="proxy.$settingStore.themeColor.color" @change="tabPositionChange" style="width: 100%"></u-subsection>
      </view>

      <!-- 内容 -->
      <oaTimeLine v-if="activities.length > 0" :fontColor="proxy.$settingStore.themeColor.color" :sort="activitiesSort" @activitiesSortChange="activitiesSortChange">
        <oaTimeLineItem
          v-for="(ac, index) in activities"
          :key="index"
          :titleValue="ac.planName"
          :timeValue="ac.timestamp"
          :iconColor="proxy.$settingStore.themeColor.color"
          v-show="tabPosition == 0"
        >
          <view style="display: flex" v-if="ac.planStatus == 1">
            <view>
              <view style="margin-bottom: 15px">巡检任务执行中，还需完成 {{ ac.undetectedSiteCount }}个 </view>
              <view style="padding: 0; font-size: 14px" :style="{ color: proxy.$settingStore.themeColor.color }" @click="reportClick(ac)"> 点击巡检 </view>
            </view>
            <view style="margin: auto"></view>
            <view style="display: flex">
              <c-progress-circle style="margin: auto" :progress="ac.completion / 100" :color="proxy.$settingStore.themeColor.color" size="100rpx" boderWidth="100rpx"></c-progress-circle>
            </view>
          </view>

          <view style="display: flex" v-if="ac.planStatus == 2">
            <view>
              <view style="margin-bottom: 15px">巡检任务结束</view>
              <view style="padding: 0; font-size: 14px" :style="{ color: proxy.$settingStore.themeColor.color }" @click="reportClick(ac)"> 点击查看 </view>
            </view>
            <view style="margin: auto"></view>
            <view style="display: flex">
              <c-progress-circle style="margin: auto" :progress="ac.completion / 100" :color="proxy.$settingStore.themeColor.color" size="100rpx" boderWidth="100rpx"></c-progress-circle>
            </view>
          </view>

          <view style="display: flex" v-if="ac.planStatus == 3">
            <view>
              <view style="margin-bottom: 15px">巡检任务结束</view>
              <view>
                <span style="margin-right: 20px">
                  合格：
                  <span style="color: #00cdac">
                    {{ ac.patrolledSiteCount }}
                  </span>
                </span>
                <span>
                  漏检：
                  <span style="color: #f07d28">
                    {{ ac.undetectedSiteCount }}
                  </span>
                </span>
              </view>
            </view>
            <view style="margin: auto"></view>
            <view style="display: flex">
              <c-progress-circle style="margin: auto" :progress="ac.completion / 100" :color="proxy.$settingStore.themeColor.color" size="100rpx" boderWidth="100rpx"></c-progress-circle>
            </view>
          </view>
        </oaTimeLineItem>

        <oaTimeLineItem
          v-for="(ac, index) in activities"
          :key="index"
          :titleValue="ac.siteName"
          :timeValue="ac.createTime"
          :iconColor="proxy.$settingStore.themeColor.color"
          v-show="tabPosition == 1"
        >
          <view style="display: flex">
            <view>
              <view>已检查{{ ac.contentCount }}项内容</view>
              <br />
              <view style="padding: 0; font-size: 14px" :style="{ color: proxy.$settingStore.themeColor.color }" @click="reportClick(ac)"> 点击查看 </view>
            </view>
            <view style="margin: auto"></view>
            <view style="display: flex; font-size: 15px; color: #30bb00">
              <view style="margin: auto">
                {{ ac.siteStatus == 0 ? "未定位" : "已定位" }}
              </view>
            </view>
          </view>
        </oaTimeLineItem>
      </oaTimeLine>

      <view id="planTimeline" style="text-align: center; color: #bdbdbd; font-size: 14px" v-else> 暂无数据 </view>

      <oaMovable v-if="scanArray.length <= 0" :themesColor="proxy.$settingStore.themeColor.color">
        <template #content>
          <view class="iconfont oaIcon-nfc menu-item-icon" @click="nfcClick()"></view>
          <view class="iconfont oaIcon-saoyisao menu-item-icon" @click="scanClick()"></view>
        </template>
      </oaMovable>

      <drawer v-if="scanArray.length > 0" :scanArray="scanArray" :scanBool="scanBool" @scanClose="scanClose"></drawer>
    </template>
  </oa-scroll>
</template>

<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import { onLoad, onShow, onLaunch, onUnload } from "@dcloudio/uni-app";
import { ref, onMounted, reactive, computed, getCurrentInstance, toRefs, inject, shallowRef, defineAsyncComponent } from "vue";
/*----------------------------------接口引入-----------------------------------*/
import { recordList, recordOption, planList, patrolInspectionPlan, appPlanStatistics } from "@/api/business/zhaf/xunJian/plan.js";
/*----------------------------------组件引入-----------------------------------*/
import drawer from "./components/drawer.vue"; // 引入组件
import oaMovable from "../../oa-movable/index.vue"; // 引入组件
import oaTimeLine from "../../oa-timeLine/index"
import oaTimeLineItem from "../../oa-timeLine-item/index"
/*----------------------------------store引入-----------------------------------*/
import { useStores, commonStores, xunJianStores } from "@/store/modules/index";
/*----------------------------------公共方法引入-----------------------------------*/
/*----------------------------------公共变量-----------------------------------*/
const { proxy } = getCurrentInstance();
const xunJianStore = xunJianStores(); //全局变量值Store
/*----------------------------------变量声明-----------------------------------*/
const info = ref({
  lunar: true,
  range: true,
  insert: false,
  selected: [],
});

/**
 * @日期change事件
 */
function change(e) {
  // console.log("change 返回:", e);
  currentDate.value = e.fulldate;
  currentApi();
  activitiesApi();
}

/**
 * @月份切换事件
 */
function monthSwitch(e) {
  // console.log("monthSwitchs 返回:", e);
}

/**
 * @点击巡检
 * @点击事件
 */
function reportClick(obj) {
  xunJianStore.inspectionStatus = null;

  if (tabPosition.value == 0) {
    xunJianStore.planSonId = obj.id;
    uni.navigateTo({
      url: "/pages/business/zhaf/xunJian/plan/components/report",
    });
  } else if (tabPosition.value == 1) {
    xunJianStore.siteId = obj.siteId;
    xunJianStore.planSonId = obj.planSonId;
    xunJianStore.inspectionStatus = 2;

    uni.navigateTo({
      url: "/pages/business/zhaf/xunJian/plan/components/siteDetails",
    });
  }
}

/**
 * @NFC
 */
function nfcClick() {
  proxy.$nfc.initNFC();
}

/**
 * @扫一扫
 * @点击事件
 */
const scanArray = ref([]);
const scanBool = ref(false);
function scanClick() {
  uni.scanCode({
    autoZoom: false,
    success: async (e) => {
      uni.showToast({
        title: "扫码成功",
        icon: "none",
      });
      planListApi(e.result);
    },
    fail: (err) => {
      uni.showToast({
        title: "扫码失败",
        icon: "none",
      });
      console.log("扫码失败", err);
    },
    complete: () => {
      console.log("扫码结束");
    },
  });
}

/**
 * @点位查询
 * @接口查询
 */
function planListApi(value) {
  xunJianStore.inspectionStatus = 1;

  if (!proxy.$common.isNetwork()) {
    return false;
  }

  planList({
    siteNubmber: value,
  })
    .then((res) => {
      if (res.status == "SUCCESS") {
        if (res.data.length > 0) {
          scanArray.value = res.data;
          scanBool.value = true;
        } else {
          uni.showToast({
            title: "此点位下暂无数据，请切换点位重试！",
            icon: "none",
          });
        }
      }
    })
    .catch((err) => {
      proxy.$modal.msg(err);
    });
}

/**
 * @抽屉emit
 * @关闭事件
 */
function scanClose(flag) {
  scanBool.value = flag;
  scanArray.value = [];
}

/**
 * @巡检任务
 * @巡检记录
 * @api接口请求
 */
const activities = ref([]);
function activitiesApi() {
  activities.value = [];

  if (!proxy.$common.isNetwork()) {
    return false;
  }

  if (tabPosition.value == 0) {
    patrolInspectionPlan({
      currentDate: currentDate.value,
      sort: activitiesSort.value,
    })
      .then((res) => {
        if (res.status == "SUCCESS") {
          res.data.forEach((el) => {
            activities.value.push({
              id: el.id,
              planName: el.planName,
              timestamp: (el.startTime ? el.startTime.split(":")[0] + ":" + el.startTime.split(":")[1] + "~" : "") + (el.endTime ? el.endTime.split(":")[0] + ":" + el.endTime.split(":")[1] : ""),
              planStatus: el.planStatus,
              completion: el.completion,
              patrolledSiteCount: el.patrolledSiteCount,
              undetectedSiteCount: el.undetectedSiteCount,
            });
          });
        } else {
        }
      })
      .catch((err) => {
        proxy.$modal.msg(err);
      });
  } else if (tabPosition.value == 1) {
    recordList({
      currentDate: currentDate.value,
      sort: activitiesSort.value,
    })
      .then((res) => {
        if (res.status == "SUCCESS") {
          res.data.forEach((el) => {
            activities.value.push({
              siteId: el.siteId,
              planSonId: el.planSonId,
              areaName: el.areaName,
              siteName: el.siteName,
              contentCount: el.contentCount,
              createTime: el.createTime ? el.createTime.replace("T", " ") : el.createTime,
              siteStatus: el.siteStatus,
            });
          });
        } else {
        }
      })
      .catch((err) => {
        proxy.$modal.msg(err);
      });
  }
}

/**
 * @统计
 * @api接口请求
 */
const currentDate = ref(proxy.$time.getDate().year + "-" + proxy.$time.getDate().month + "-" + proxy.$time.getDate().dates); //统计时间数据存储
const currentDatevalue = ref(new Date());
const currentDateList = ref({}); //统计list数据存储
function currentApi() {
  if (!proxy.$common.isNetwork()) {
    return false;
  }

  appPlanStatistics({
    currentDate: currentDate.value,
  })
    .then((res) => {
      if (res.status == "SUCCESS") {
        currentDateList.value = res.data;
      } else {
      }
    })
    .catch((err) => {
      proxy.$modal.msg(err);
    });
}

/**
 * @排序按钮
 */
const activitiesSort = ref("DESC");
function activitiesSortChange(val) {
  activitiesSort.value = val;
  activitiesApi();
}

/**
 * @tabs切换change事件
 */
const list = ref(["巡检任务", "巡检记录"]);
const tabPosition = ref(xunJianStore.planTabs);
function tabPositionChange(index) {
  tabPosition.value = index;
  activitiesApi();
}

onLoad((options) => {
  if (options.planTabs) {
    xunJianStore.planTabs = parseInt(options.planTabs);
    tabPosition.value = parseInt(options.planTabs);
  }

  currentApi();
  activitiesApi();
  xunJianStore.planForSubmit(); //调用巡检计划循环提交

  // 从详情页返回该页面的获取数据
  uni.$on("planSelect", () => {
    scanArray.value = [];
    currentApi();
    activitiesApi();
  });
});

onShow(() => {
  //调用系统主题颜色
  proxy.$settingStore.systemThemeColor([1]);

  uni.$on("NFC_readID", function (value) {
    planListApi(value);
  });
});

onUnload(() => {
  uni.$off("NFC_readID"); //将值删除监听器
});

onMounted(() => {});
</script>

<style lang="scss" scoped>
.is-selected {
  color: #1989fa;
}

.xunjian-plan-container {
  .app-subsection {
    display: flex;
    margin: 10px;
    padding: 10px 5rem;
  }
}
</style>
