<template>
  <div class="check-body">
    <div class="site-content">
      <div class="site-row">
        <div class="site-progress" :style="`width: ${currentProgress}%`"></div>
        <div class="site-label">
          <div class="site-node" v-for="(item,index) in checkList" :key="item.ccId">
            <div :class="['site',index<=cIndex && cIndex!=null?'normal':'un-info ']"/>
            <div :class="['site-name',{'active-site-name':index<=cIndex && cIndex!=null}]">{{ item.className }}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="site-content mt10">
      <div class="check-status">
        <el-button type="primary" :loading="cLoading" @click="onNowCheck"
                   style="padding:16px 22px;">
          立即巡检
        </el-button>
        <span class="check-progress" v-if="cLoading">
            <span class="t-span">巡检进度:</span>
            <el-progress type="circle" :percentage="currentProgress" width="50" stroke-width="4" :color="colors">
              <template #default="{ percentage }">
                <span class="percentage-value">{{ percentage }}%</span>
              </template>
            </el-progress>
        </span>
        <span class="check-progress" v-else>
            <span class="t-span" style="font-size: 14px;font-weight: 400;text-align: center;width: 100%;"
                  v-show="nowCheck.checkResult">
              {{ nowCheck.checkResult }}
            </span>
        </span>
        <span>
          <span v-show="checkTime" class="check-time">
            <span v-if="checkFlag" style="margin-right: 10px">
              <el-button size="small" @click="handleDialog('setting')" icon="Setting">巡检记录配置</el-button>
              <el-button size="small" @click="handleDialog('report')" icon="Document">
                巡查报告查看
              </el-button>
            </span>
            <span class="t-span">巡检时间:</span>
            <span class="check-time">{{ checkTime }}</span>
          </span>
        </span>
      </div>

      <el-table :data="listData" style="width: 100%" border class="mt20" :span-method="spanMethod">
        <el-table-column prop="className" label="分类" width="180" align="center"/>
        <el-table-column prop="checkName" label="巡检项"/>
        <el-table-column label="巡检结果" width="160" align="center">
          <template #default="{row}">
            <span v-if="checkTime">
              <span v-if="row.resultL">
                {{ row.resultL }}
              </span>
              <el-icon size="25" color="#388e3c" class="rotate" v-else><Loading/></el-icon>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" width="160">
          <template #default="{row}">
            <span v-if="checkTime">
              <span v-if="row.resultR" :style="`color:${row.resultR === '正常'||row.resultR === '是'?'#1ab43f':'#e43'}`">
                {{ row.resultR }}
              </span>
              <el-icon size="25" color="#388e3c" class="rotate" v-else><Loading/></el-icon>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog v-model="isComponent.visible" width="1000" :title="isComponent.title" style="margin-top:2vh!important">
      <component :is="isComponent.component" :crId="nowCheck.crId" :spanMethod="spanMethod"/>
    </el-dialog>

  </div>
</template>
<script setup lang="ts">
import {chkcCheck, chkcResult, listChkc} from "@/api/check/chkc"
import {onMounted} from "vue";
import {Loading} from "@element-plus/icons-vue";
import nCheckList from "./widget/nCheckList.vue"
import nReportList from "./widget/nReportList.vue"

const checkList = ref([])
const listData = ref([])
const currentProgress = ref(0)
const cIndex = ref(null)
const cLoading = ref(false)
const checkTime = ref(null)
const nowCheck = ref({})
const checkFlag = ref(false)
const isComponent = ref({
  visible: false,
  title: "",
  component: nReportList
})

const colors = [
  {color: '#bbdefb', percentage: 20},
  {color: '#90caf9', percentage: 40},
  {color: '#64b5f6', percentage: 60},
  {color: '#2196f3', percentage: 80},
  {color: '#1e88e5', percentage: 100},
]

const initData = async () => {
  await chkcResult(0)
  getListChkc().then()
}

onMounted(() => {
  if (localStorage.getItem("listData")) {
    return restoreCache()
  }
  initData()
})

const handleDialog = (action) => {
  if (action === 'report') {
    isComponent.value = {
      visible: true,
      title: "巡检报告查看",
      component: nReportList
    }
  } else {
    isComponent.value = {
      visible: true,
      title: "巡检记录配置",
      component: nCheckList
    }
  }
}

const restoreCache = () => {
  chkcResult(0)
  listData.value = JSON.parse(localStorage.getItem("listData"))
  nowCheck.value = JSON.parse(localStorage.getItem("nowCheck"))
  checkList.value = uniqueByKey(listData.value, 'className')
  checkFlag.value = true
  // cIndex.value = listData.value.length - 1
  checkTime.value = nowCheck.value.checkTime
  currentProgress.value = 100
}

const spanMethod = ({row, column, rowIndex}) => {
  if (column.property === "className") {
    const currentClass = listData.value[rowIndex].className;
    const prevClass = listData.value[rowIndex - 1]?.className;
    if (currentClass !== prevClass) {
      let rowspan = 1;
      for (let i = rowIndex + 1; i < listData.value.length; i++) {
        if (listData.value[i].className === currentClass) {
          rowspan++;
        } else {
          break;
        }
      }
      return {rowspan, colspan: 1};
    } else {
      return {rowspan: 0, colspan: 0};
    }
  }
}

const uniqueByKey = (array, key) => {
  const map = new Map();
  array.forEach(item => map.set(item[key], item));
  return Array.from(map.values());
}

const getListChkc = async () => {
  const {rows} = await listChkc({pageSize: 100})
  listData.value = rows
  checkList.value = uniqueByKey(rows, 'className')
}

const padZero = (number) => {
  return (number < 10 ? "0" : "") + number;
}

const getRandomInt = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const onNowCheck = async () => {
  const {data} = await chkcCheck()
  nowCheck.value = data
  checkTime.value = data.checkTime;
  handleCheck(0)
}

const handleCheck = (i) => {
  if (!cLoading.value) {
    getListChkc();
    cLoading.value = true;
    cIndex.value = null;
    currentProgress.value = 0;
    checkFlag.value = false;
    if (localStorage.getItem("listData")) {
      localStorage.removeItem("listData")
      localStorage.removeItem("nowCheck")
    }
  }

  const randomStep = getRandomInt(1, 4);
  const index = Math.min(i + randomStep, listData.value.length - 1);

  if (i < listData.value.length) {
    setTimeout(() => {
      currentProgress.value = Number(((index + 1) / listData.value.length * 100).toFixed(1));

      for (let j = i; j <= index; j++) {
        const item = listData.value[j];
        const detail = nowCheck.value.detailList.find(cItem => cItem.ccId === item.ccId);

        if (detail) {
          const {resultL, resultR, remark} = detail;
          listData.value[j] = {...item, resultL, resultR, remark};
        }
      }
      handleCheck(index + 1);
    }, getRandomInt(1000, 4000));
  } else {
    cLoading.value = false;
    currentProgress.value = 100;
    checkFlag.value = true
    localStorage.setItem("nowCheck", JSON.stringify(nowCheck.value))
    localStorage.setItem("listData", JSON.stringify(listData.value))
  }
}


</script>
<style scoped lang="scss">
@import "./css/style.scss";
</style>
