<template>
  <div class="g-p20 main">
    <base-head ref="headRef" :titles="['报警统计', '工作循环']" bottom="15" @onTabChange="onTabChange"></base-head>
    <div v-show="pitchTab === '报警统计'" v-loading="loading">
      <div class="middle">
        <div class="g-p20 middle__first">
          <div class="g-title ft14 g-fx-j">
            报警比例
            <div>
              <el-radio-group v-model="radio" @change="change" size="small" fill="#597FDA ">
                <el-radio-button label="年" />
                <el-radio-button label="月" />
                <el-radio-button label="日" />
                <el-radio-button label="周" />
              </el-radio-group>
            </div>
          </div>
          <div class="pie" ref="pieRef"></div>
        </div>
        <div class="g-p20 middle__second">
          <div class="g-title ft14 g-fx-j">
            年度报警
            <span class="police">
              / 报警次数 <span>{{ YNum }}</span></span
            >
            <!-- <div class="date-picker">
              <el-icon class="icon"><ArrowLeftBold /></el-icon>
              <el-date-picker
                :clearable="false"
                style="width: 105px; background: #efefef; border-radius: 5px"
                v-model="year"
                type="year"
              />
              <el-icon class="icon"><ArrowRightBold /></el-icon>
            </div> -->
          </div>
          <div class="line-chart" ref="barRef"></div>
        </div>
      </div>
      <div class="footer g-p20">
        <div class="g-title ft14 g-fx-j">
          月度报警
          <span class="police">
            / 报警次数 <span>{{ MNum }}</span></span
          >
          <!-- <div class="date-picker">
            <el-icon class="icon"><ArrowLeftBold /></el-icon>
            <el-date-picker
              :clearable="false"
              style="width: 80px; background: #efefef; border-radius: 5px"
              v-model="year"
              format="M月"
              type="month"
            />
            <el-icon class="icon"><ArrowRightBold /></el-icon>
          </div> -->
        </div>
        <div class="line-chart-1" ref="lineRef"></div>
      </div>
    </div>
    <div v-show="pitchTab === '工作循环'" class="g-p20 g-card" v-loading="loadingWork">
      <el-date-picker
        @change="onWorkTimeChange"
        style="width: 140px; background: #efefef; border-radius: 5px"
        v-model="year2"
        format="YYYY-MM-DD"
        type="date"
      />
      <div v-show="workCirculationTable.data.length !== 0">
        <div class="work-chart" ref="barWorkRef"></div>
        <div class="work-chart-box">
          <div class="work-table">
            <div
              class="work-table__item g-fx"
              :class="{ 'item-active': pitchItem == index }"
              @click="onPitchItem(item, index)"
              v-for="(item, index) in workCirculationTable.data"
            >
              <div class="start" v-for="(el, i) in tableInfo">
                <div class="start__text">
                  {{ el.label }} <span>&nbsp; {{ item[el.value] }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-empty v-show="workCirculationTable.data.length === 0" description="暂无数据" />
    </div>
  </div>
</template>

<script setup name="统计分析" lang="ts">
  import {
    getAlertReportForCustom,
    getAlertReportForMonth,
    getAlertReportForYear,
    getDutyCycleLineChart,
    getDutyCycleReport
  } from '@/api'
  import { useSidebarStore } from '@/store/sidebar'
  import dayjs from 'dayjs'
  import * as echarts from 'echarts'
  import { ElMessage } from 'element-plus'
  const pieRef: any = ref(null)
  const lineRef: any = ref(null)
  const barRef: any = ref(null)
  const barWorkRef: any = ref(null)
  const pitchTab = ref('报警统计')
  const radio = ref('年')
  const loading = ref(false)
  let pieChart: any = ref({})
  let lineChart: any = ref({})
  let barChart: any = ref({})
  let barWorkChart: any = ref(null)
  const pitchItem = ref(0)
  const tableInfo = [
    {
      label: '开始',
      value: 'beginTimeFormat'
    },
    {
      label: '结束',
      value: 'endTimeFormat'
    },
    {
      label: '重量',
      value: 'formatWeight'
    },
    {
      label: '耗时',
      value: 'durationFormat'
    }
  ]
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 1
        },

        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          }
        },
        labelLine: {
          show: true
        },
        data: [
          { value: 1048, name: 'Search Engine' },
          { value: 735, name: 'Direct' },
          { value: 580, name: 'Email' },
          { value: 484, name: 'Union Ads' },
          { value: 300, name: 'Video Ads' }
        ]
      }
    ]
  }
  const option1 = {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    tooltip: {
      trigger: 'item'
    },
    grid: {
      show: false,
      top: '10%',
      right: '5%',
      bottom: '15%',
      left: '5%'
    },
    series: [
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: 'bar',
        barWidth: 15,
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ]
  }
  let option2 = {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    tooltip: {
      trigger: 'item'
    },
    grid: {
      show: false,
      top: '10%',
      right: '5%',
      bottom: '15%',
      left: '5%'
    },
    series: [
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: 'line',
        barWidth: 15,
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ]
  }
  let option3 = {
    tooltip: {
      trigger: 'item'
    },
    dataZoom: [{ end: 100, minValueSpan: 40, start: 0, type: 'slider' }],
    grid: {
      containLabel: true,
      bottom: '17%',
      left: '3%',
      right: '10%',
      top: '20%'
    },
    series: [
      {
        smooth: true,
        itemStyle: { normal: { lineStyle: { color: '#577BD3' } } },
        tooltip: { formatter: '{a} <br/>{c}T<br/>时间：{b}', trigger: 'axis' },
        markLine: {
          data: [
            {
              label: { formatter: '{b}', position: 'end' },
              lineStyle: { color: '#ff9933' },
              name: '预警',
              yAxis: '18.0'
            },
            {
              label: { formatter: '{b}', position: 'end' },
              lineStyle: { color: '#cc0033' },
              name: '超载',
              yAxis: '21.0'
            },
            {
              label: { formatter: '{b}', position: 'end' },
              lineStyle: { color: '#577BD3' },
              name: '开始',
              xAxis: '13:36:14'
            },
            {
              label: { formatter: '{b}', position: 'end' },
              lineStyle: { color: '#FE5656' },
              name: '结束',
              xAxis: '13:36:24'
            }
          ]
        },
        name: '载荷',
        showSymbol: false,
        type: 'line',
        data: []
      }
    ],
    title: {
      text: '工作循环',
      textStyle: { color: '#000000', fontSize: 15 },
      left: '2%',
      top: '5%'
    },
    visualMap: [
      {
        pieces: [
          { color: '#204884', gt: '0', lte: '18.0' },
          { color: '#ff9933', gt: '18.0', lte: '21.0' },
          { color: '#cc0033', gt: '21.0' }
        ],
        right: 10,
        show: false,
        top: 10
      }
    ],
    xAxis: [
      {
        axisLabel: { color: '#AAAAAA' },
        axisLine: { lineStyle: { color: '#efefef' } },
        axisTick: { alignWithLabel: false, show: false },
        type: 'category',
        data: []
      }
    ],
    yAxis: [
      {
        axisLabel: { color: '#AAAAAA', formatter: '{value}T' },
        splitLine: { lineStyle: { color: '#efefef' } },
        type: 'value'
      }
    ]
  }

  let MNum = ref(0)
  let YNum = ref(0)
  onMounted(async () => {
    try {
      loading.value = true
      await barData.getData()
      await YData.getData()
      await MData.getData()
      // 月度报警
      option2.xAxis.data = MData.data.map((item: { key: any }) => item.key)
      option2.series[0].data = MData.data.map((item: any) => item.value)
      //年度报警
      option1.xAxis.data = YData.data.map((item: { key: any }) => item.key)
      option1.series[0].data = YData.data.map((item: any) => item.value)
      //月度总数
      MNum.value = MData.data.reduce((prev: any, next: any) => {
        prev = +next.value + prev
        return prev
      }, 0)
      // 年度总数
      YNum.value = YData.data.reduce((prev: any, next: any) => {
        prev = +next.value + prev
        return prev
      }, 0)
      option.series[0].data = barData.data.datas
      init1()
    } finally {
      loading.value = false
    }
  })
  // 报警统计
  const init1 = () => {
    pieChart.value = echarts.init(pieRef.value)
    lineChart.value = echarts.init(lineRef.value)
    barChart.value = echarts.init(barRef.value)
    pieChart.value.setOption(option)
    lineChart.value.setOption(option2)
    barChart.value.setOption(option1)
  }
  // 工作循环2
  const init2 = () => {
    barWorkChart.value = echarts.init(barWorkRef.value)
    barWorkChart.value.setOption(option3)
  }
  const headRef: any = ref('headRef')
  const onTabChange = async (v: string) => {
    pitchTab.value = v
    if (v === '报警统计') {
      init1()
    } else {
      await getWorkCirculationTable()
    }
  }
  const setOption3 = () => {
    if (workCirculation.data.visualMap.length) {
      option3.series[0].markLine.data = workCirculation?.data?.mark
      option3.series[0].data = workCirculation?.data?.values
      option3.visualMap = workCirculation?.data?.visualMap
      option3.xAxis[0].data = workCirculation?.data?.times
    } else {
      option3.series[0].markLine.data = []
      option3.series[0].data = []
      option3.visualMap = []
      option3.xAxis[0].data = []
      barWorkChart.value = null
    }
    if (barWorkChart.value) {
      barWorkChart.value.setOption(option3)
    } else {
      init2()
    }
  }
  const onPitchItem = async (v: any, i: number) => {
    pitchItem.value = i

    dutyCycleId.value = v.id
    await workCirculation.getData()

    setOption3()
  }
  /*** 工作循环月度筛选 */
  const year2 = ref()
  const onWorkTimeChange = () => {
    const start = dayjs(year2.value).format('YYYY-MM-DD') + ' 00:00:00'
    const end = dayjs(year2.value).format('YYYY-MM-DD') + ' 23:59:59'
    getWorkCirculationTable(start, end)
    workCirculation.getData()
  }
  const type = '4'
  const filterFields: any = {
    年: 'year',
    月: 'month',
    日: 'day',
    周: 'week'
  }
  const barData = useRequest(() => {
    let startTime
    const obj: any = {
      年: () => {
        startTime = dayjs().format('YYYY') + '-01-01'
      },
      月: () => {
        startTime = dayjs().format('YYYY-MM') + '-01'
      },
      日: () => {
        startTime = dayjs().format('YYYY-MM-DD') + ' 00:00:00'
      },
      周: () => {
        startTime = dayjs().endOf('week').subtract(7, 'day').format('YYYY-MM-DD')
      }
    }
    obj[radio.value]()

    return getAlertReportForCustom({
      deviceId: useQuery('id'),
      startTime,
      endTime: dayjs().format('YYYY-MM-DD') + ' 23:59:59'
    })
  }, false)

  const dutyCycleId = ref('')
  const YData = useRequest(() => getAlertReportForYear({ deviceId: useQuery('id'), type }), false)
  const MData = useRequest(() => getAlertReportForMonth({ deviceId: useQuery('id'), type }), false)
  const workCirculation = useRequest(() => getDutyCycleLineChart({ dutyCycleId: dutyCycleId.value }), false)

  let workCirculationTable: any = reactive({ data: [] })
  const loadingWork = ref(false)
  const getWorkCirculationTable = async (startTime?: any, endTime?: any) => {
    try {
      loadingWork.value = true
      const data: any = await getDutyCycleReport({
        deviceId: useQuery('id'),
        startTime,
        endTime
      })
      workCirculationTable.data = data
      if (data.length === 0) return
      dutyCycleId.value = workCirculationTable?.data?.[0]?.id
      year2.value = workCirculationTable?.data?.[0].beginTime
      await workCirculation.getData()
      setOption3()
    } finally {
      loadingWork.value = false
    }
  }
  // watchEffect(() => {
  //   if (useQuery('id')) {
  //     barData?.getData()
  //   }
  // })
  const change = async () => {
    await barData?.getData()

    option.series[0].data = barData.data.datas
    pieChart.value.setOption(option)
  }
</script>

<style lang="less" scoped>
  .main {
    min-height: calc(100vh - 100px);
    margin-bottom: 20px;
  }

  .g-title {
    position: relative;
  }

  .ft14 {
    font-size: 14px;
  }

  .line-chart {
    width: 100%;
    height: calc(100% - 40px);
  }

  .line-chart-1 {
    height: 340px;
    width: 100%;
  }

  .middle {
    height: 380px;
    display: flex;
    justify-content: space-between;

    &__first {
      background-color: #fff;
      min-width: 600px;
      height: 100%;
      width: 35%;
      border-radius: 10px;
      margin-right: 15px;

      .pie {
        width: 100%;
        height: calc(100% - 40px);
      }
    }

    &__second {
      background-color: #fff;
      min-width: 600px;
      height: 100%;
      width: 64%;
      border-radius: 10px;
      box-sizing: border-box;
    }
  }

  .work-chart-box {
    max-height: calc(100vh - 600px);
    min-height: 300px;
    padding: 20px 0;
    overflow-y: auto;
  }

  .work-chart {
    width: calc(100vw - 280px);
    height: 300px;
  }

  .work-table {
    min-height: 55px;
    background: #ffffff;
    border: 2px solid #c8cfdf;
    border-radius: 5px;
    margin-top: 30px;

    &__item {
      height: 60px;
      line-height: 60px;
      padding: 0 20px;
      cursor: pointer;
      border-bottom: 1px solid #c8cfdf;

      div {
        flex: 1;
        justify-content: center;
        margin: 0 auto;
      }

      div:nth-child(1),
      div:nth-child(2) {
        width: 260px;
        flex-shrink: 0;
        flex-grow: 0;
        text-align: left;
      }

      &:last-child {
        border: none;
      }
    }

    .item-active {
      background-color: #ecf5ff;
    }

    .start {
      color: #999;
      font-size: 14px;

      &__text {
        text-align: center;
      }
    }
  }

  .police {
    position: absolute;
    top: 0px;
    left: 65px;
    color: #999;
    font-weight: 400;

    span {
      color: #000;
      font-weight: bold;
    }
  }

  .footer {
    margin-top: 15px;
    position: relative;
    background-color: #fff;
    min-height: 380px;
    border-radius: 10px;
  }

  :deep(.date-picker) {
    display: flex;
    align-items: center;

    .icon {
      margin: 0 8px;
      color: #ccc;
    }

    .el-input__wrapper {
      background-color: #eee;
    }

    .el-input__inner {
      text-align: center;
      padding-right: 5px;
      color: #999;
    }
  }
</style>
