<!--
 * @Author: chris
 * @Date: 2025-08-22 10:10:51
 * @LastEditors: DESKTOP-P4Q6IC1\CHRIS_PC 510148846@qq.com
 * @LastEditTime: 2026-03-25 14:36:02
-->
<script setup>
import { useRoute } from 'vue-router'
import ScreenHeader from './components/ScreenHeader.vue'
import OrchardBriefInfo from './components/OrchardBriefInfo.vue'
import WeatherInfo from './components/WeatherInfo.vue';
import PestInfo from './components/PestInfo.vue';
import WarningInfo from './components/WarningInfo.vue';
import SoilInfo from './components/SoilInfo.vue';
import AerialPhoto from './components/AerialPhoto.vue';
import TimeBox from './components/TimeBox.vue';
import OrchardMap from './components/OrchardMap.vue';
import { BorderBox12, Loading as DvLoading } from '@kjgl77/datav-vue3'
import useDraw from '@/hooks/useDraw';
import mock from './mock';
import { getDeviceDataAnalysis } from '@/api/deviceData';
import { listDept } from '@/api/system/dept'
import { listDevice } from '@/api/device';
import { listNotify } from '@/api/pest/pushHistory';

const { proxy } = getCurrentInstance()
const route = useRoute()

const loading = ref(false)
const hoursRange = getDateRange(1)
const daysRange = getDateRange(7)
const deviceList = ref([])
const pestList = ref([])
const soilList = ref([])
const weatherList = ref([])
const baseInfo = ref({})
const notifyList = ref([])

const { screenRef, calcRate, windowDraw, unWindowDraw } = useDraw()

const orchardId = route.query.id || ''
getData()

onMounted(() => {
  calcRate()
  windowDraw()
})

onUnmounted(() => {
  unWindowDraw()
})

function getData() {
  loading.value = true
  Promise.all([
    getDevices(),
    getPestAnalysisData(),
    getSoilAnalysisData(),
    getWeatherAnalysisData(),
    getOrchardList(),
    getNotifyList()
  ]).then(res => {
    console.log('res', res)
    deviceList.value = res[0].rows
    pestList.value = res[1].rows
    soilList.value = res[2].rows
    weatherList.value = res[3].rows
    baseInfo.value = getOrchardInfo(res[4].data)
    notifyList.value = res[5].rows
  }).finally(() => {
    loading.value = false
  })
}

async function getDevices() {
  try {
    return await listDevice({
      deptId: orchardId
    })
  } catch (error) {
    proxy.$modal.msgError('获取设备数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get device data:', error)
    return error
  }
}

async function getPestAnalysisData () {
  try {
    return await getDeviceDataAnalysis({
      beginTime: hoursRange[0],
      endTime: hoursRange[1],
      type: 1,
      deptId: orchardId
    })
  } catch (error) {
    proxy.$modal.msgError('获取虫情数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get soil analysis data:', error)
    return error
  }
}

async function getSoilAnalysisData () {
  try {
    return await getDeviceDataAnalysis({
      beginTime: daysRange[0],
      endTime: daysRange[1],
      type: 2,
      deptId: orchardId
    })
  } catch (error) {
    proxy.$modal.msgError('获取土壤数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get soil analysis data:', error)
    return error
  }
}

async function getWeatherAnalysisData () {
  try {
    return await getDeviceDataAnalysis({
      beginTime: hoursRange[0],
      endTime: hoursRange[1],
      type: 3,
      deptId: orchardId
    })
  } catch (error) {
    proxy.$modal.msgError('获取气象数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get soil analysis data:', error)
    return error
  }
}

async function getOrchardList () {
  try {
    return await listDept()
  } catch (error) {
    proxy.$modal.msgError('获取果园信息失败: ' + (error.message || '未知错误'))
    console.error('Failed to get orchard info:', error)
    return error
  }
}

async function getNotifyList () {
  try {
    return await listNotify()
  } catch (error) {
    proxy.$modal.msgError('获取预警数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get notify data:', error)
    return error
  }
}

function getOrchardInfo (orchardList) {
  console.log('orchardList', orchardList)
  const orchard = orchardList.find(item => !item.parentId)
  return orchard || {}
}

// 获取最近n天的日期范围
function getDateRange (num) {
  const nowDate = new Date().toLocaleString().replace(/\//g, '-')
  const preDate = new Date(+new Date(nowDate) - num * 24 * 60 * 60 * 1000).toLocaleString().replace(/\//g, '-')
  return [preDate, nowDate]
}
</script>

<template>
  <div class="orchard-screen">
    <!-- 背景 -->
    <div class="bg" ref="screenRef">
      <!-- 加载动画 -->
      <dv-loading v-if="loading">
        <div color-white>
          正在加载...
        </div>
      </dv-loading>
      <div class="screen-body" v-else>
        <!-- 头部 -->
        <div class="screen-header">
          <ScreenHeader />
        </div>
        <TimeBox />
        <div class="screen-content">
          <!-- 内容-左 -->
          <div class="screen-content-left">
            <div class="content-left-top">
              <border-box-12>
                <orchard-brief-info :info="baseInfo"/>
              </border-box-12>
            </div>
            <div class="content-left-bottom">
              <border-box-12>
                <weather-info :weather-data="weatherList" />
              </border-box-12>
            </div>
          </div>
          <!-- 内容-右 -->
          <div class="screen-content-right">
            <div class="content-right-top">
              <border-box-12>
                <pest-info class="pest-info-module" :pest-data="pestList" />
                <warning-info :notify-data="notifyList" class="warning-info-module" />
              </border-box-12>
            </div>
            <div class="content-right-bottom">
              <border-box-12>
                <soil-info :soil-data="soilList" />
              </border-box-12>
              <border-box-12>
                <!-- <aerial-photo /> -->
                <orchard-map :deviceList="deviceList" />
              </border-box-12>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.orchard-screen {
  color: #d3d6dd;
  height: 100%;
  width: 100%;
  background-color: #000;
  overflow: hidden;
  .bg {
    width: 1920px;
    height: 1080px;
    padding: 14px;
    background-image: url('@/assets/images/screen/orchard-bg.png');
    background-size: cover;
    background-position: center center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transform-origin: left top;
    transition: all 0.5s ease;
    overflow: hidden;
  }
}

.screen-body {
  @apply h-full;
}

.screen-header {
  @apply w-full h-50px m-b-20px;
}

.screen-content {
  @apply flex h-[calc(100%-50px-20px)];
}

.screen-content-left {
  @apply w-25% h-full;

  .content-left-top {
    @apply h-32%;
  }

  .content-left-bottom {
    @apply h-68%;
  }
}

.screen-content-right {
  @apply flex-1 h-full;

  .content-right-top {
    @apply h-58%;

    :deep(.border-box-content) {
      @apply flex flex-col;
    }
  }

  .content-right-bottom {
    @apply flex h-42%;
    
    > :nth-child(1) {
      flex: 4;
    }

    > :nth-child(2) {
      flex: 5;
    }
  }
}

.pest-info-module {
  @apply h-75%;
}

.warning-info-module {
  @apply flex-1;
}
</style>
