<template>
  <div class="page-container">
    <el-row :gutter="16" class="summary">
      <!-- 原有的统计卡片部分保持不变 -->
      <el-col v-loading="loading" :sm="3" :xs="12">
        <SummaryCard
          :value="device.total || 0"
          icon="fa-solid:project-diagram"
          icon-bg-color="text-blue-500"
          icon-color="bg-blue-100"
          :title="t('stat.deviceCount')"
        />
      </el-col>
      <el-col v-loading="loading" :sm="3" :xs="12">
        <SummaryCard
          :value="maintain.total || 0"
          icon="fa-solid:list"
          icon-bg-color="text-pink-500"
          icon-color="bg-blue-100"
          :title="t('stat.repairOrder')"
        />
      </el-col>
      <el-col v-loading="loading" :sm="3" :xs="12">
        <SummaryCard
          :value="fill.unfilledCount || 0"
          icon="fa-solid:times-circle"
          icon-bg-color="text-purple-500"
          icon-color="bg-purple-100"
          :title="t('stat.operationNotFilled')"
        />
      </el-col>
      <el-col v-loading="loading" :sm="3" :xs="12">
        <SummaryCard
          :value="fill.filledCount || 0"
          icon="fa-solid:award"
          icon-bg-color="text-purple-500"
          icon-color="bg-purple-100"
          :title="t('stat.operationFilled')"
        />
      </el-col>
      <el-col v-loading="loading" :sm="3" :xs="12">
        <SummaryCard
          :value="by.todo || 0"
          icon="fa-solid:times-circle"
          icon-bg-color="text-green-500"
          icon-color="bg-green-100"
          :title="t('stat.notMaintained')"
        />
      </el-col>
      <el-col v-loading="loading" :sm="3" :xs="12">
        <SummaryCard
          :value="by.finished || 0"
          icon="fa-solid:award"
          icon-bg-color="text-green-500"
          icon-color="bg-green-100"
          :title="t('stat.maintained')"
        />
      </el-col>
      <el-col v-loading="loading" :sm="3" :xs="12">
        <SummaryCard
          :value="inspect.todo || 0"
          icon="fa-solid:times-circle"
          icon-bg-color="text-yellow-500"
          icon-color="bg-yellow-100"
          :title="t('stat.notInspected')"
        />
      </el-col>
      <el-col v-loading="loading" :sm="3" :xs="12">
        <SummaryCard
          :value="inspect.finished || 0"
          icon="fa-solid:award"
          icon-bg-color="text-yellow-500"
          icon-color="bg-yellow-100"
          :title="t('stat.inspected')"
        />
      </el-col>
    </el-row>
    <el-row :gutter="16" class="mb-4">
      <!-- 设备状态统计和工单数量情况图表部分保持不变 -->
      <el-col :span="8">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="flex items-center">
              <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.deviceStatus')}}</span>
            </div>
          </template>
          <div ref="statusChartRef" class="h-[290px]"></div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.orderCount')}}</span>
            </div>
          </template>
          <div ref="qxRef" class="h-[290px]"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="16" class="mb-4">
      <!-- 备件更换情况部分保持不变 -->
      <el-col :span="8">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.sparePartsReplacement')}}</span>
            </div>
          </template>
          <!-- 添加两个卡片 -->
          <div class="flex justify-between mb-2">
            <el-card class="stat-card">
              <div class="flex flex-row justify-evenly">
                <div>
                  <Icon icon="fa-solid:award" size="30" color="blue" />
                </div>
                <div class="flex flex-col items-center">
                  <span class="text-sm " style="color: #101010">{{t('stat.spareCount')}}</span>
                  <span class="text-lg font-bold">{{ totalMaterialCount }}</span>
                </div>
              </div>
            </el-card>
            <el-card class="stat-card">
              <div class="flex flex-row justify-evenly">
                <div>
                  <Icon icon="fa-solid:yen-sign" size="30" color="orange" />
                </div>
                <div class="flex flex-col items-center">
                  <span class="text-sm " style="color: #101010">{{t('stat.spareAmount')}}</span>
                  <span class="text-lg font-bold">{{ totalMaterialCost }}</span>
                </div>
              </div>
            </el-card>
          </div>
          <div ref="sparePartRef" class="h-[330px]"></div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <div class="flex flex-col justify-between">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <div class="flex items-center justify-between">
                <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.maintenanceStatus')}}</span>
              </div>
            </template>
            <div class="flex mr-3">
              <div ref="maintenanceChartRef" class="h-[167px] w-2/5"></div>
              <div class="w-3/5 p-4 flex flex-col mt-5">
                <div class="flex justify-between">
                  <div class="flex flex-col items-center">
                    <Icon icon="fa-solid:list" size="30" color="#f1d209" />
                    <p style="font-size: 20px; margin-top: 5px;color: #91cc75">{{t('stat.totalOrder')}}</p>
                    <span style="font-size: 20px;color: white">{{ (by.finished?by.finished:0) + (by.todo?by.todo:0) }}</span>
                  </div>
                  <div class="flex flex-col items-center">
                    <Icon icon="fa-solid:check-circle" size="30" color="green" />
                    <p style="font-size: 20px; margin-top: 5px;color: #91cc75">{{t('stat.finishedOrder')}}</p>
                    <span style="font-size: 20px;color: white">{{ by.finished?by.finished:0 }}</span>
                  </div>
                  <div class="flex flex-col items-center">
                    <Icon icon="fa-solid:hourglass-half" size="30" color="#e14f0f" />
                    <p style="font-size: 20px; margin-top: 5px;color: #91cc75">{{t('stat.pendingOrder')}} </p>
                    <span style="font-size: 20px;color: white">{{ by.todo?by.todo:0 }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
          <el-card class="chart-card mt-2" shadow="never">
            <template #header>
              <div class="flex items-center justify-between">
                <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.inspectStatus')}}</span>
              </div>
            </template>
            <div class="flex mr-3">
              <div ref="inspectChartRef" class="h-[167px] w-2/5"></div>
              <div class="w-3/5 p-4 flex flex-col mt-5">
                <div class="flex justify-between">
                  <div class="flex flex-col items-center">
                    <Icon icon="fa-solid:list" size="30" color="#f1d209" />
                    <p style="font-size: 20px; margin-top: 5px;color: #91cc75">{{t('stat.totalOrder')}}</p>
                    <span style="font-size: 20px;color: white">{{ inspect.todo + inspect.finished }}</span>
                  </div>
                  <div class="flex flex-col items-center">
                    <Icon icon="fa-solid:check-circle" size="30" color="green" />
                    <p style="font-size: 20px; margin-top: 5px;color: #91cc75">{{t('stat.finishedOrder')}}</p>
                    <span style="font-size: 20px;color: white">{{ inspect.finished }}</span>
                  </div>
                  <div class="flex flex-col items-center">
                    <Icon icon="fa-solid:hourglass-half" size="30" color="#e14f0f" />
                    <p style="font-size: 20px; margin-top: 5px;color: #91cc75">{{t('stat.pendingOrder')}}</p>
                    <span style="font-size: 20px;color: white">{{ inspect.todo }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
import { MemberSummaryRespVO } from '@/api/mall/statistics/member'
import SummaryCard from '@/components/SummaryCard/index.vue'
import * as echarts from 'echarts/core'
import { BarChart, GaugeChart, LineChart, PieChart } from 'echarts/charts' // 显式导入柱状图模块
import {
  GridComponent,
  LegendComponent,
  TitleComponent,
  ToolboxComponent,
  TooltipComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { IotStatApi } from '@/api/pms/stat'
import { ref, onMounted, computed, watch, nextTick, reactive } from 'vue'
import {useLocaleStore} from "@/store/modules/locale";

/** 会员统计 */
defineOptions({ name: 'IotRdStat' })

echarts.use([
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout,
  TitleComponent,
  ToolboxComponent,
  GridComponent,
  LineChart,
  UniversalTransition,
  GaugeChart,
  BarChart
])

const loading = ref(true) // 加载中
const summary = ref<MemberSummaryRespVO>() // 会员统计数据
const statusChartRef = ref() // 设备数量统计的图表
const qxRef = ref(null)
let qxInstance = null
const sparePartRef = ref(null)
let sparePartInstance = null
const maintenanceChartRef = ref(null)
let maintenanceChartInstance = null
const inspectChartRef = ref(null)
let inspectChartInstance = null
const inspectionChartRef = ref(null)
let inspectionChartInstance = null
const { t } = useI18n() // 国际化
const maintenanceChartRef1 = ref(null)

const typeData = ref({})
const orderSevenData = ref({})
const device = ref({
  total: undefined,
  today: undefined
})
const maintain = ref({
  total: undefined,
  today: undefined
})
const by = ref({
  todo: undefined,
  finished: undefined
})
const fill = ref({
  filledCount: undefined,
  unfilledCount: undefined
})
const inspect = ref({
  finished: 0,
  todo: 0
})
const sparePartData = ref({
  xAxis: ['扳手', '水杯', '皮带', '螺丝'],
  series: [
    {
      name: '数量',
      type: 'bar',
      data: [10, 20, 15, 25],
      yAxisIndex: 0
    },
    {
      name: '金额',
      type: 'line',
      data: [100, 200, 150, 250],
      yAxisIndex: 1
    }
  ]
})
const sparePartDataEng = ref({
  xAxis: ['spanner', 'cup', 'belt', 'screw'],
  series: [
    {
      name: 'count',
      type: 'bar',
      data: [10, 20, 15, 25],
      yAxisIndex: 0
    },
    {
      name: 'amount',
      type: 'line',
      data: [100, 200, 150, 250],
      yAxisIndex: 1
    }
  ]
})
// 模拟巡检工单数据
const totalInspectionOrders = ref(80)
const completedInspectionOrders = ref(60)

// 计算物料消耗数量及费用
const totalMaterialCount = computed(() => {
  const quantitySeries = sparePartData.value.series.find((item) => item.name === '数量')
  return quantitySeries ? quantitySeries.data.reduce((sum, val) => sum + val, 0) : 0
})

const totalMaterialCost = computed(() => {
  const costSeries = sparePartData.value.series.find((item) => item.name === '金额')
  return costSeries ? costSeries.data.reduce((sum, val) => sum + val, 0) : 0
})

const getStats = () => {
  IotStatApi.getDeviceStatusCount('rd').then((res) => {
    typeData.value = res
    initDeviceStatusCharts()
  })
  IotStatApi.getOrderSeven('rd').then((res) => {
    orderSevenData.value = res
    initQxChart()
  })
  IotStatApi.getDeviceCount("rd").then((res) => {
    device.value = res
  })
  IotStatApi.getMaintainCount("rd").then((res) => {
    maintain.value = res
  })
  IotStatApi.getMaintenanceStatus("rd").then((res) => {
    by.value = res
    initMaintenanceChart()
  })
  const fillQueryParams = reactive({
    startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, // 设置默认开始时间为 7 天前
    endTime: Date.now(), // 设置默认结束时间为当前时间
    createTime: [],
    deptId: null, // 选中的部门ID
    status: null // 填写状态
  })
  IotStatApi.getInspectStatuss(fillQueryParams,'rd').then((res) => {
    inspect.value = res
    initInspectChart()
  })
  fillQueryParams.deptId = '163'
  IotStatApi.getDeptStatistics(fillQueryParams).then((res) => {
    fill.value = res.totalList[0] || []
  })
  const localeStore = useLocaleStore()
  const lang = localeStore.getCurrentLocale.lang
  if (lang==='zh-CN') {
    initSparePartChart('数量','金额', sparePartData)
  } else if (lang==='en') {
    initSparePartChart('count','amount', sparePartDataEng)
  }
  initInspectionChart()
}

const initQxChart = () => {
  if (!qxRef.value) return
  qxInstance = echarts.init(qxRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: orderSevenData.value.series.map((item) => item.name),
      top: 30,
      textStyle: {
        color:'#B6C8DA'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: orderSevenData.value.xAxis,
      axisLabel: {
        color: '#B6C8DA',
        formatter: (value) => value.split('-').join('/')
      },
      axisLine: {
        lineStyle: {
          color: '#B6C8DA' // X轴线白色半透明
        }
      },
    },
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          formatter: '{value}'
        },
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
        position: 'left' // 左侧 Y 轴
      },
      {
        type: 'value',
        axisLabel: {
          formatter: '{value}'
        },
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
        position: 'right', // 右侧 Y 轴
        splitLine: {
          show: false // 隐藏右侧 Y 轴的分割线
        }
      }
    ],
    series: orderSevenData.value.series.map((item, index) => {
      const yAxisIndex = index < 2 ? 0 : 1
      return {
        name: item.name,
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: ['#5470c6', '#f1d209', '#e14f0f', '#91cc75'][index]
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84,112,198,0.4)' },
            { offset: 1, color: 'rgba(84,112,198,0.1)' }
          ])
        },
        data: item.data,
        yAxisIndex: yAxisIndex // 指定使用的 Y 轴
      }
    })
  }

  qxInstance.setOption(option)
}

const initSparePartChart = (count:any,amount:any, spare:{}) => {
  if (!sparePartRef.value) return
  sparePartInstance = echarts.init(sparePartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: [count, amount],
      textStyle:{
        color: '#fff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: spare.value.xAxis,
      axisLabel: {
        color: '#B6C8DA',
      },
      axisLine: {
        lineStyle: {
          color: '#B6C8DA' // X轴线白色半透明
        }
      },
    },
    yAxis: [
      {
        type: 'value',
        name: count,
        position: 'left',
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
      },
      {
        type: 'value',
        name: amount,
        position: 'right',
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: spare.value.series.map((item, index) => ({
      name: item.name,
      type: item.type,
      data: item.data,
      yAxisIndex: item.yAxisIndex,
      itemStyle: {
        color: ['#6084fb', '#5aef13'][index]
      }
    }))
  }

  sparePartInstance.setOption(option)
}

const initInspectChart = () => {
  if (!inspectChartRef.value) return
  inspectChartInstance = echarts.init(inspectChartRef.value)
  const completionRate =
    (inspect.value.finished / (inspect.value.finished + inspect.value.todo)) * 100
  debugger
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal', // 水平排列图例项
      bottom: '0%', // 放置在底部
      icon: 'circle',
      textStyle: {
        color: '#B6C8DA'
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        label: {
          show: false,
          position: 'outside'
        },
        emphasis: {
          label: {
            color: '#B6C8DA',
            show: true,
            fontSize: 15,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        // itemStyle: {
        //   color: ['#e4a317', '#5aef13']
        // },
        data: [
          { name: '完成率', value: completionRate.toFixed(2) },
          { name: '未完成率', value: 100 - completionRate.toFixed(2) }
        ]
      }
    ]
  }
  inspectChartInstance.setOption(option)
}

const initMaintenanceChart = () => {
  if (!maintenanceChartRef.value) return
  maintenanceChartInstance = echarts.init(maintenanceChartRef.value)
  const completionRate = (by.value.finished / (by.value.finished + by.value.todo)) * 100
  debugger
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal', // 水平排列图例项
      bottom: '0%', // 放置在底部
      icon: 'circle',
      textStyle: {
        color: '#B6C8DA'
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        label: {
          show: false,
          position: 'outside'
        },
        emphasis: {
          label: {
            color:'#B6C8DA',
            show: true,
            fontSize: 15,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: [
          { name: '完成率', value: completionRate.toFixed(2) },
          { name: '未完成率', value: 100 - completionRate.toFixed(2) }
        ]
      }
    ]
  }
  maintenanceChartInstance.setOption(option)
}

const initInspectionChart = () => {
  if (!inspectionChartRef.value) return
  inspectionChartInstance = echarts.init(inspectionChartRef.value)
  const completionRate = (completedInspectionOrders.value / totalInspectionOrders.value) * 100
  const option = {
    series: [
      {
        type: 'pie',
        radius: ['50%', '80%'],
        data: [
          { value: completionRate, name: '完成率' },
          { value: 100 - completionRate, name: '未完成率' }
        ]
      }
    ]
  }
  inspectionChartInstance.setOption(option)
}

/** 初始化图表 */
const initDeviceStatusCharts = () => {
  // 设备数量统计
  echarts.init(statusChartRef.value).setOption({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal', // 水平排列图例项
      bottom: '0%', // 放置在底部
      icon: 'circle',
      textStyle: {
        color: '#B6C8DA'
      }
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['50%', '80%'],
        avoidLabelOverlap: false,
        center: ['50%', '44%'],
        label: {
          show: false,
          position: 'outside'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 15,
            fontWeight: 'bold',
            color: 'white'
          }
        },
        labelLine: {
          show: false
        },
        data: typeData.value
      }
    ]
  })
}

/** 初始化 **/
onMounted(async () => {
  loading.value = true
  await Promise.all([getStats()])
  loading.value = false
})
</script>
<style lang="scss" scoped>
.summary {
  .el-col {
    margin-bottom: 1rem;
  }
}
.stat-card {
  width: 48%;
}
.page-container {
  background-color: #3a6fa3;
  min-height: 100vh;
  padding: 20px;
}

.summary {
  margin-bottom: 20px;
}

::v-deep .chart-card {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.5);
  transition: all 0.3s ease;
  border: none;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  }
}

// 安全生产天数卡片样式
.safety-days-card {
  .safety-days-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 150px;
    position: relative;

    .days-number {
      font-size: 58px;
      font-weight: bold;
      color: darkorange;
      line-height: 1;
      transition: all 0.3s ease;
    }

    .days-number:hover {
      transform: scale(1.05);
    }

    .days-label {
      font-size: 20px;
      color: white;
      margin-top: 8px;
    }

    .safety-desc {
      font-size: 14px;
      color: #999;
      position: absolute;
      bottom: 10px;
      text-align: center;
      width: 90%;
    }
  }
}

@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
}
::v-deep .el-card__header {
  border-bottom: none !important;
  padding-bottom: 0;
}
</style>
