<template>
  <scroll-view scroll-y>
    <view class="grayBackgroundColor">
      <view>
        <el-calendar
          id="calendar"
          ref="calendar"
          v-model="currentDatevalue"
          @touchstart="touchStart"
          @touchend="touchEnd"
        >
          <template #header="{ date }">
            <view style="display: flex; width: 100%">
              <view>{{ date }}</view>
              <view style="margin: auto"></view>
              <view style="display: flex">
                <view style="margin: 0px 10px">
                  <span style="margin-right: 5px">合格</span>
                  <span style="color: #00cdac">{{
                    JSON.stringify(currentDateList) === "{}"
                      ? 0
                      : currentDateList.patrolledCount
                  }}</span>
                </view>
                <view class="margin-left-xs">
                  <span style="margin-right: 5px">漏检</span>
                  <span style="color: #f07d28">{{
                    JSON.stringify(currentDateList) === "{}"
                      ? 0
                      : currentDateList.undetectedCount
                  }}</span>
                </view>
              </view>
            </view>
          </template>
          <template #dateCell="{ data }">
            <view @click="calendarClick(data)">
              <p :class="data.isSelected ? 'is-selected' : ''">
                {{ data.day.split("-").slice(2).join("-") }}
              </p>
              <view v-if="data.isSelected" class="filter"></view>
            </view>
          </template>
        </el-calendar>
      </view>
      <view>
        <view class="padding-sm" style="display: flex; margin: 10px">
          <el-radio-group
            v-model="tabPosition"
            style="margin: auto"
            @change="tabPositionChange()"
          >
            <el-radio-button label="task">巡检任务</el-radio-button>
            <el-radio-button label="record">巡检记录</el-radio-button>
          </el-radio-group>
        </view>
        <view>
          <el-timeline id="planTimeline" v-if="activities.length > 0">
            <view>
              <el-button
                type="primary"
                style="margin: 0px -7.5px"
                link
                @click="activitiesSortClick()"
              >
                排序
              </el-button>
            </view>
            <view v-if="tabPosition == 'task'">
              <el-timeline-item
                v-for="(activity, index) in activities"
                :key="index"
                :icon="activity.icon"
                :type="activity.type"
                :color="activity.color"
                :size="activity.size"
                :hollow="activity.hollow"
              >
                <view style="display: flex">
                  <view style="font-size: 15px"> {{ activity.planName }}</view>
                  <view style="margin: auto"> </view>
                  <view style="color: #b5b5b5"> {{ activity.timestamp }}</view>
                </view>
                <view
                  style="
                    margin-top: 15px;
                    padding: 15px;
                    background-color: #fff;
                    border-radius: 10px;
                  "
                >
                  <view style="display: flex" v-if="activity.planStatus == 2">
                    <view>
                      <view>巡检任务结束</view>
                      <br />
                      <view>
                        <el-button
                          type="primary"
                          link
                          style="padding: 0"
                          @click="reportClick(activity.id)"
                        >
                          点击查看
                        </el-button>
                      </view>
                    </view>
                    <view style="margin: auto"></view>
                    <view>
                      <el-progress
                        type="circle"
                        :percentage="activity.completion"
                        :width="50"
                      />
                    </view>
                  </view>
                  <view style="display: flex" v-if="activity.planStatus == 1">
                    <view>
                      <view
                        >巡检任务执行中，还需完成
                        {{ activity.undetectedSiteCount }}个
                      </view>
                      <br />
                      <view>
                        <el-button
                          type="primary"
                          link
                          style="padding: 0"
                          @click="reportClick(activity.id)"
                        >
                          点击巡检
                        </el-button>
                      </view>
                    </view>
                    <view style="margin: auto"></view>
                    <view>
                      <el-progress
                        type="circle"
                        :percentage="activity.completion"
                        :width="50"
                      />
                    </view>
                  </view>
                  <view style="display: flex" v-if="activity.planStatus == 3">
                    <view>
                      <view>巡检任务结束</view>
                      <br />
                      <view>
                        <span style="margin-right: 20px">
                          合格：
                          <span style="color: #00cdac">
                            {{ activity.patrolledSiteCount }}
                          </span>
                        </span>
                        <span>
                          漏检：
                          <span style="color: #f07d28">
                            {{ activity.undetectedSiteCount }}
                          </span>
                        </span>
                      </view>
                    </view>
                    <view style="margin: auto"></view>
                    <view>
                      <el-progress
                        type="circle"
                        :percentage="activity.completion"
                        :width="50"
                      />
                    </view>
                  </view>
                </view>
              </el-timeline-item>
            </view>

            <view v-if="tabPosition == 'record'">
              <el-timeline-item
                v-for="(activity, index) in activities"
                :key="index"
                :icon="activity.icon"
                :type="activity.type"
                :color="activity.color"
                :size="activity.size"
                :hollow="activity.hollow"
              >
                <view style="display: flex">
                  <view style="font-size: 15px"> {{ activity.siteName }}</view>
                  <view style="margin: auto"> </view>
                  <view style="color: #b5b5b5"> {{ activity.createTime }}</view>
                </view>
                <view
                  style="
                    margin-top: 15px;
                    padding: 15px;
                    background-color: #fff;
                    border-radius: 10px;
                  "
                >
                  <view>已检查{{ activity.contentCount }}项内容</view>
                  <view
                    :style="{
                      color:
                        activity.siteStatus == 0
                          ? '#f07d28'
                          : activity.siteStatus == 1
                          ? '#00cdac'
                          : '',
                      textAlign: 'right',
                    }"
                  >
                    {{
                      activity.siteStatus == 0
                        ? "未定位"
                        : activity.siteStatus == 1
                        ? "已定位"
                        : ""
                    }}
                  </view>
                  <view>
                    <el-button type="primary" link style="padding: 0">
                      点击查看
                    </el-button>
                  </view>
                </view>
              </el-timeline-item>
            </view>
          </el-timeline>
          <view
            id="planTimeline"
            style="text-align: center; color: #bdbdbd; font-size: 14px"
            v-else
          >
            暂无数据
          </view>
        </view>
      </view>
    </view>

    <img
      src="@/static/inspection/plan-scan.png"
      alt=""
      style="position: fixed; right: 0; bottom: 50px"
      @click="scanClick()"
    />
    <drawer
      v-if="scanArray.length > 0"
      :scanArray="scanArray"
      :scanBool="scanBool"
      @scanClose="scanClose"
    ></drawer>
  </scroll-view>
</template>

<script setup>
import drawer from "./components/drawer.vue";

import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref, onMounted, inject, shallowRef } from "vue";
const myRequest = inject("$myRequest");

import useXunJianStore from "@/store/modules/xunJian";
const settingsStore = useXunJianStore(); //全局变量值Store

import { MoreFilled } from "@element-plus/icons-vue";

function reportClick(id) {
  settingsStore.planSonId1 = id;
  uni.navigateTo({
    url: "/pages/xunJian/plan/components/report",
  });
}

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

  settingsStore.inspectionStatus = 1;
  let res = await myRequest({
    url: "/service-fire/appPatrolInspection/planList",
    header: {
      "Content-Type": "application/json;charset=utf-8",
    },
    method: "GET",
    data: {
      siteNubmber: "0000000000",
    },
  });

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

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

/**
 * @巡检任务
 * @巡检记录
 * @api接口请求
 */
const activities = ref([]);
async function activitiesApi() {
  activities.value = [];
  if (tabPosition.value == "task") {
    let res = await myRequest({
      url: "/service-fire/appPatrolInspection/patrolInspectionPlan",
      header: {
        "Content-Type": "application/json;charset=utf-8",
      },
      method: "GET",
      data: {
        currentDate: currentDate.value,
        sort: activitiesSort.value,
      },
    });

    if (res.data.status == "SUCCESS") {
      res.data.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 == "record") {
    let res = await myRequest({
      url: "/service-fire/appPatrolInspection/recordList",
      header: {
        "Content-Type": "application/json;charset=utf-8",
      },
      method: "GET",
      data: {
        currentDate: currentDate.value,
        sort: activitiesSort.value,
      },
    });

    if (res.data.status == "SUCCESS") {
      res.data.data.forEach((el) => {
        activities.value.push({
          siteName: el.siteName,
          contentCount: el.contentCount,
          createTime:
            el.createTime.split("T")[0] + " " + el.createTime.split("T")[1],
          siteStatus: el.siteStatus,
        });
      });
    } else {
    }
  }

  activities.value.forEach((el) => {
    el.size = "large";
    el.type = "primary";
    el.icon = shallowRef(MoreFilled);
  });
}

/**
 * @统计
 * @api接口请求
 */
const currentDate = ref(
  settingsStore.getDate().year +
    "-" +
    settingsStore.getDate().month +
    "-" +
    settingsStore.getDate().dates
); //统计时间数据存储
const currentDatevalue = ref(new Date());
const currentDateList = ref({}); //统计list数据存储
async function currentApi() {
  const res = await myRequest({
    url: "/service-fire/appPatrolInspection/appPlanStatistics",
    header: {
      "Content-Type": "application/json;charset=utf-8",
    },
    method: "GET",
    data: {
      currentDate: currentDate.value,
    },
  });

  if (res.data.status == "SUCCESS") {
    currentDateList.value = res.data.data;
  } else {
  }
}

/**
 * @排序按钮
 */
const activitiesSort = ref("ASC");
function activitiesSortClick() {
  if (activitiesSort.value == "ASC") {
    activitiesSort.value = "DESC";
  } else {
    activitiesSort.value = "ASC";
  }
  activitiesApi();
}

/**
 * @tabs切换change事件
 */
const tabPosition = ref(settingsStore.planTabs);
function tabPositionChange() {
  activitiesApi();
}

/**
 * @日期click事件
 */
const calendar = ref(); //获取日期refs元素
function calendarClick(data) {
  currentDate.value = data.day;
  currentApi();
  activitiesApi();
}

/**
 * @触摸开始
 **/
let touchStartX = 0; // 触屏起始点x
let touchStartY = 0; // 触屏起始点y
function touchStart(e) {
  console.log("触摸开始");
  touchStartX = e.touches[0].clientX;
  touchStartY = e.touches[0].clientY;
}

/**
 * @触摸结束
 **/
function touchEnd(e) {
  console.log("触摸结束");
  let deltaX = e.changedTouches[0].clientX - touchStartX;
  let deltaY = e.changedTouches[0].clientY - touchStartY;
  if (Math.abs(deltaX) > 50 && Math.abs(deltaX) > Math.abs(deltaY)) {
    if (deltaX >= 0) {
      console.log("左滑");

      calendar.value.selectDate("prev-month");
    } else {
      console.log("右滑");
      calendar.value.selectDate("next-month");
    }
  } else if (Math.abs(deltaY) > 50 && Math.abs(deltaX) < Math.abs(deltaY)) {
    if (deltaY < 0) {
      console.log("上滑");
    } else {
      console.log("下滑");
    }
  } else {
    console.log("可能是误触！");
  }
}

onLoad((options) => {
  currentApi();
  activitiesApi();
});

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

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

<style scoped>
uni-page-body,
uni-page-refresh,
.grayBackgroundColor {
  background: rgb(241, 241, 241);
}
</style>
