<template>
  <div class="chartsContainer">
    <div class="chartsContainer-title">工作画像</div>
    <div class="chartsContainer-list">
      <div class="chartsContainer-content">
        <div class="chartsContainer-content-top">
          <div class="chartsContainer-content-name">通道开放趋势图</div>
        </div>
        <div class="chartsContainer-content-content" ref="channelChart" />
      </div>

      <div class="chartsContainer-content">
        <div class="chartsContainer-content-top">
          <div class="chartsContainer-content-name">查获趋势图</div>
        </div>
        <div class="chartsContainer-content-content" ref="seizure" />
      </div>

      <div class="chartsContainer-content">
        <div class="chartsContainer-content-top">
          <div class="chartsContainer-content-name">抽问抽答完成率趋势图</div>
        </div>
        <div class="chartsContainer-content-content" ref="levelRateChart" />
      </div>

      <div class="chartsContainer-content">
        <div class="chartsContainer-content-top">
          <div class="chartsContainer-content-name">查获审批时长统计</div>
        </div>
        <div class="chartsContainer-content-content">
          <el-table v-auto-scroll :data="tableData" border style="width: 100%" height="100%">
            <el-table-column prop="empty" label="指标" min-width="140" />
            <el-table-column prop="duration" label="时长" />
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getChannelOpenTrendChart, getDurationChart, getSeizureTrendChart, getStationLevelRate, getDepartmentLevelRate } from '@/api/item/items'
import { useTimeOut } from './useTimeOut';
import { useECharts } from '@/hooks/useEcharts.js';
import { ref, computed, reactive, inject } from 'vue'
const dataZoom = [
  {
    type: 'slider', // 滑动条型数据区域缩放组件
    show: true,
    xAxisIndex: [ 0 ],
    start: 0,
    end: 100,
    height: 20,
    bottom: 10,
    backgroundColor: '#f5f5f5',
    dataBackground: {
      lineStyle: {
        color: '#00BCD4',
        width: 1,
        opacity: 0.5
      },
      areaStyle: {
        color: 'rgba(0, 188, 212, 0.1)'
      }
    },
    fillerColor: 'rgba(0, 188, 212, 0.2)',
    borderColor: '#ddd',
    textStyle: {
      color: '#666'
    }
  },
  {
    type: 'inside', // 内置型数据区域缩放组件
    xAxisIndex: [ 0 ],
    start: 0,
    end: 100,
    zoomOnMouseWheel: true, // 支持鼠标滚轮缩放
    moveOnMouseMove: true, // 支持鼠标拖拽平移
    moveOnMouseWheel: false
  }
]
const provideParams = inject('provideParams')
const channelChart = ref(null)
const channelChartData = ref([])
const setChannelChartOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = `日期: ${params[ 0 ].name}<br/>`
        params.forEach(param => {
          let value = param.value
          if (param.seriesName === '开放时长') {
            value = `${param.value}小时`
          } else if (param.seriesName === '平均线') {
            value = `平均值: ${param.value}`
          }
          result += `${param.marker} ${param.seriesName}: ${value}<br/>`
        })
        return result
      }
    },
    legend: {
      data: [ '通道开放数', '开放时长', '平均线' ],
      left: 'center',
      textStyle: {
        fontSize: 12,
        color: '#fff'
      }
    },
    xAxis: {
      type: 'category',
      data: channelChartData.value.map(item => item.date),
      axisLabel: {
        rotate: 45, // 日期标签旋转45度，避免重叠
        fontSize: 12,
        color: '#fff'
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '通道数',
        position: 'left',
        min: 0,
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        axisLabel: {
          formatter: '{value}',
          color: "#fff"
        }
      },
      {
        type: 'value',
        name: '时长(小时)',
        position: 'right',
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        axisLabel: {
          formatter: '{value}',
          color: "#fff"
        }
      }
    ],
    grid: {
      left: '5%',
      right: '5%',
      top: '20%', // 增加顶部间距，降低y轴高度
      bottom: '15%', // 为缩放控件留出空间
      containLabel: true
    },
    dataZoom: dataZoom,
    series: [
      {
        name: '通道开放数',
        data: channelChartData.value.map(item => item.openCount || 0),
        type: 'line',
        smooth: true,
        yAxisIndex: 0,
        lineStyle: {
          color: '#4CAF50',
          width: 2
        },
        itemStyle: {
          color: '#4CAF50'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [ {
              offset: 0,
              color: 'rgba(76, 175, 80, 0.3)'
            }, {
              offset: 1,
              color: 'rgba(76, 175, 80, 0.1)'
            } ]
          }
        }
      },
      {
        name: '开放时长',
        data: channelChartData.value.map(item => item.openDuration || 0),
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        lineStyle: {
          color: '#2196F3',
          width: 2
        },
        itemStyle: {
          color: '#2196F3'
        }
      },
      {
        name: '平均线',
        data: channelChartData.value.map(item => item.avg), // 为每个数据点创建相同的平均值
        type: 'line',
        yAxisIndex: 0,
        lineStyle: {
          color: '#FF9800',
          width: 2,
          type: 'dashed' // 虚线表示平均线
        },
        itemStyle: {
          color: '#FF9800'
        },
        symbol: 'none', // 不显示数据点
        label: {
          show: true,
          position: 'end',
          formatter: `平均值: {c}`
        }
      }
    ]
  }
})
useECharts(channelChart, setChannelChartOptions);

const seizure = ref(null)
const seizureData = ref([])
const setSeizureOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const data = params[ 0 ]
        return `日期: ${data.name}<br/>查获数量: ${data.value}`
      }
    },
    xAxis: {
      type: 'category',
      data: seizureData.value.map(item => item.date),
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        color: '#fff',
        rotate: 45,
        fontSize: 12,
      }
    },
    yAxis: {
      name: '查获数量',
      type: 'value',
      min: 0,
      max: function () {
        // 计算最大值并向上取整到最近的整数，确保五等分
        const maxTotal = Math.max(...seizureData.value.map(item => item.total || 0), 5);
        return Math.ceil(maxTotal / 5) * 5;
      }(),
      interval: function () {
        // 固定为五等分
        const maxTotal = Math.max(...seizureData.value.map(item => item.total || 0), 5);
        return Math.ceil(maxTotal / 5);
      }(),
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: '#fff'
        }
      }
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '15%', // 为缩放控件留出空间
      containLabel: true
    },
    dataZoom: dataZoom,
    series: [ {
      name: '查获数量',
      type: 'line',
      smooth: true,
      data: seizureData.value.map(item => item.total || 0),
      lineStyle: {
        width: 3,
        color: '#D45046'
      },
      itemStyle: {
        color: '#D45046'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [ {
            offset: 0,
            color: 'rgba(255, 107, 107, 0.3)'
          }, {
            offset: 1,
            color: 'rgba(255, 107, 107, 0.1)'
          } ]
        }
      }
    } ]
  }
})
useECharts(seizure, setSeizureOptions);

const selectedLevelType = ref('station')
const levelRateChart = ref(null)
const levelRateChartData = ref([])
const setLevelRateChartOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const data = params[ 0 ]
        return `${data.name}<br/>已完成任务: ${data.value}`
      }
    },
    xAxis: {
      type: 'category',
      data: levelRateChartData.value.map(item => item.date),
      axisLabel: {
        color: '#fff',
        rotate: 45,
        fontSize: 12,
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      name: '已完成任务',
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: '#fff'
        }
      }
    },
    dataZoom: dataZoom,
    series: [ {
      name: '已完成任务',
      data: levelRateChartData.value.map(item => item.completedTasks),
      type: 'line',
      smooth: true,
      lineStyle: {
        color: '#1CA7C8',
        width: 3
      },
      itemStyle: {
        color: '#1CA7C8'
      },
      areaStyle: {
        color: 'rgba(0, 188, 212, 0.3)'
      }
    } ],
    grid: {
      left: '5%',
      right: '5%',
      bottom: '15%', // 增加底部空间给数据缩放组件
      containLabel: true
    }
  }
})
useECharts(levelRateChart, setLevelRateChartOptions);

//获取抽问抽答完成率
const getLevelRateData = (paramsObj) => {
  let params = {
    startDate: paramsObj.startDate,
    endDate: paramsObj.endDate,
    deptId: paramsObj.inspectDepartmentId
  }
  selectedLevelType.value = paramsObj.inspectDepartmentId && String(paramsObj.inspectDepartmentId) !== 'ALL' ? '' : 'station' 
  let api = selectedLevelType.value == 'station' ? getStationLevelRate : getDepartmentLevelRate
  if (selectedLevelType.value == 'station') {
    delete params.deptId
    params.siteId = 100
  }
  api(params).then(res => {
    levelRateChartData.value = res.data || []
  })
}

const tableData = ref([])
useTimeOut(() => {
  provideParams.value.deptId && getChannelOpenTrendChart({
    startTime: provideParams.value.startDate,
    endTime: provideParams.value.endDate,
    deptId: provideParams.value.deptId === 'ALL' ? '' : provideParams.value.deptId
  }).then(res => {
    channelChartData.value = (res.trend || []).map(item => {
      return {
        ...item,
        avg: res.avg || 0
      }
    })
  })
  provideParams.value.deptId && getSeizureTrendChart({
    startTime: provideParams.value.startDate,
    endTime: provideParams.value.endDate,
    deptId: provideParams.value.deptId === 'ALL' ? '' : provideParams.value.deptId
  }).then(res => {
    seizureData.value = res.data || []
  })
  provideParams.value.deptId && getLevelRateData(provideParams.value)
  provideParams.value.deptId && getDurationChart({
    startTime: provideParams.value.startDate,
    endTime: provideParams.value.endDate,
    deptId: provideParams.value.deptId === 'ALL' ? '' : provideParams.value.deptId
  }).then(res => {
    const data = res.data || {}
    tableData.value = [
      { empty: '平均审批时长', duration: data.averageDurationText || '-' },
      { empty: '最长审批时常', duration: data.maxDurationText || '-' },
      { empty: '最短审批时常', duration: data.minDurationText || '-' }
    ]
  })
}, [provideParams])



</script>

<style lang="scss" scoped>
.chartsContainer {
  width: 100%;
  height: 100%;
  position: relative;
  background: linear-gradient(to bottom, rgba(8, 97, 117, 0) 0%, #13a2d6 200%);
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .chartsContainer-title {
    height: 42px;
    width: 100%;
    background: linear-gradient(to right, #004387 0%, #090B18 100%);
    border-left: 1px solid #1892CE;
    line-height: 42px;
    color: #fff;
    font-weight: 900;
    font-size: 20px;
    text-indent: 1em;
  }

  .chartsContainer-list {
    padding: 20px 15px 10px;
    box-sizing: border-box;
    display: flex;
    column-gap: 20px;
    flex: 1;
    overflow: hidden;
  }

  .chartsContainer-content {
    display: flex;
    flex-direction: column;
    row-gap: 10px;
    flex: 1;
    overflow: hidden;

    .chartsContainer-content-top {
      display: flex;
      align-items: center;
      color: #78DEF5;

      .chartsContainer-content-name {
        color: #fff;
        font-weight: bold;
        font-size: 16px;
        display: flex;
        align-items: center;

        &::before {
          content: '';
          display: inline-block;
          border-left: 9px solid #1CB6FF;
          border-top: 8px solid transparent;
          border-right: 9px solid transparent;
          border-bottom: 8px solid transparent;
        }
      }
    }

    .chartsContainer-content-describe {
      color: #78DEF5;
      font-size: 12px;
      font-weight: bold;
      display: flex;
      align-items: center;
    }

    .chartsContainer-content-content {
      flex: 1;
      width: 100%;
      --el-bg-color: transparent;
      --el-fill-color-blank: transparent;
      --el-border-color-lighter: #1887A6;
      --el-text-color-regular: #fff;
      --el-fill-color-light: #5e93a1;

      :deep(.el-table) {
        .el-table__header-wrapper th {
          background-color: #1CA7C8 !important;
          color: #fff;
        }

        .cell {
          font-weight: bold;
        }
      }
    }
  }
}
</style>