<template>
  <scroll-view class="scroll-height" :scroll-y="true" :data-theme="'theme-' + proxy.$settingStore.themeColor.name">
    <view class="xunjian-plan-container">
      <!-- 日历组件 -->
      <oa-calendar 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>

      <!-- 内容 -->
      <oa-timeLine v-if="activities.length > 0" :fontColor="proxy.$settingStore.themeColor.color" :sort="activitiesSort" @activitiesSortChange="activitiesSortChange">
        <oa-timeLine-item
          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>
        </oa-timeLine-item>

        <oa-timeLine-item
          v-for="(ac, index) in activities"
          :key="index"
          :titleValue="ac.areaName"
          :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>
        </oa-timeLine-item>
      </oa-timeLine>

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

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

    <drawer v-if="scanArray.length > 0" :scanArray="scanArray" :scanBool="scanBool" @scanClose="scanClose"></drawer>
  </scroll-view>
</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 { useStores, commonStores, xunJianStores } from "@/store/modules/index";
import { recordList, recordOption, planList, patrolInspectionPlan, appPlanStatistics } from "@/api/business/mhxf/xunJian/plan.js";
import drawer from "./components/drawer.vue"; // 引入组件
import oaMovable from "@/components/oa-movable/index.vue"; // 引入组件

const commonStore = commonStores(); //全局公共Store
const xunJianStore = xunJianStores(); //全局变量值Store

const { proxy } = getCurrentInstance();

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/mhxf/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/mhxf/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;

  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",
        });
      }
    } else {
    }
  });
}

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

/**
 * @巡检任务
 * @巡检记录
 * @api接口请求
 */
const activities = ref([]);
function activitiesApi() {
  activities.value = [];
  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 == null || el.startTime == "" ? "" : el.startTime.split(":")[0] + ":" + el.startTime.split(":")[1] + "~") +
              (el.endTime == null || el.endTime == "" ? "" : el.endTime.split(":")[0] + ":" + el.endTime.split(":")[1]),

            planStatus: el.planStatus,
            completion: el.completion,
            patrolledSiteCount: el.patrolledSiteCount,
            undetectedSiteCount: el.undetectedSiteCount,
          });
        });
      } else {
      }
    });
  } 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 {
      }
    });
  }
}

/**
 * @统计
 * @api接口请求
 */
const currentDate = ref(commonStore.getDate().year + "-" + commonStore.getDate().month + "-" + commonStore.getDate().dates); //统计时间数据存储
const currentDatevalue = ref(new Date());
const currentDateList = ref({}); //统计list数据存储
function currentApi() {
  appPlanStatistics({
    currentDate: currentDate.value,
  }).then((res) => {
    if (res.status == "SUCCESS") {
      currentDateList.value = res.data;
    } else {
    }
  });
}

/**
 * @排序按钮
 */
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) => {
  currentApi();
  activitiesApi();

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

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

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

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

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

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

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