<template>
  <div class="flex flex-col">
    <modulen :loading="loading" :error="error" class="flex-grow h-1/2">
      <template #title>故障分析指标</template>
      <template #end>
        <dateSwitcher :selectTime="3" @change="getChartDataByBtnOne"></dateSwitcher>
      </template>
      <template v-if="!loading">
        <div class="number-wrapper">
          <div class="number-box" v-for="(item, index) in numList.dataList" :key="index">
            <div class="top">
              <img class="number-img" src="@/views/electromechanicalMange/assets/top-round.png" alt="" />
              <span class="text">
                {{ item.amount }}<span>{{ item.unit }}</span>
              </span>
            </div>
            <div class="bottom">
              <Light>
                <template #title>
                  <span class="text-light">{{ item.lable }}</span>
                </template>
              </Light>
            </div>
          </div>
        </div>
      </template>
    </modulen>
    <modulen :loading="loading" :error="error" class="flex-grow h-1/2">
      <template #title>任务执行情况</template>
      <template #end>
        <dateSwitcher :selectTime="3" @change="getChartDataByBtnTwo"></dateSwitcher>
      </template>
      <template v-if="!loading">
        <div class="charts">
          <div id="chart" class="ePieRadar"> </div>
          <div class="chartNumber" v-for="(item, index) in taskLine.dataList" :key="index"
            :class="`chart` + (index + 1)">
            <img :src="item.src" alt="">
            <div>
              <div class="status">{{item.text}}</div>
              <span class="value">{{item.value}}</span>
            </div>
          </div>
        </div>
      </template>
    </modulen>
    <modulen :loading="loading" :error="error" class="flex-grow h-1/2">
      <template #title>工单完成分析</template>
      <template #end>
        <dateSwitcher :selectTime="3" @change="getChartDataByBtnThree"></dateSwitcher>
      </template>
      <template v-if="!loading">
        <eBarOrder class="eBarOrder" :chartData="faultOption" />
      </template>
    </modulen>
  </div>
</template>
<script lang="ts" setup>
import { computed, watch, nextTick, reactive, ref } from "vue";
import {
  faultRate,
  maintTaskLine,
  faultSatisfied,
} from "@/api/ele-control-cabin";
import Light from "./light.vue";
import ePieRadar from "../Echarts/ePieRadar.vue";
import eBarOrder from "../Echarts/eBarOrder.vue";
import imageInner from "@/views/electromechanicalMange/assets/chart-inner.png";
import dateSwitcher from './switcher.vue'
import chartsPerson from '@/views/electromechanicalMange/assets/chartsPerson.png'
import * as echarts from 'echarts'

import accept from '../images/accept.png'
import done from '../images/done.png'
import process from '../images/process.png'
import audit from '../images/audit.png'

import { useStore } from "vuex";
import { key } from "@/store";
const store = useStore(key);
const chartsOption = reactive({});
const faultOption = reactive({});
const taskLine = reactive({
  dataList: [
    { "value": "0", "text": "审批中", src: audit },
    { "value": "0", "text": "处理中", src: process },
    { "value": "0", "text": "验收中", src: accept },
    { "value": "0", "text": "已完成", src: done },
    { "value": "0", "text": "已撤回", src: audit },
    
  ]
})
interface dataItem {
  amount: number | string;
  lable: string;
  unit: string;
}
const numList = reactive({
  dataList: [] as dataItem[],
});
numList.dataList = [
  {
    amount: 0,
    lable: "故障超期数量",
    unit: "个",
  },
  {
    amount: 0,
    lable: "机电任务排除时效满足率",
    unit: "%",
  },
  {
    amount: 0,
    lable: "机电故障误报率",
    unit: "%",
  },
  {
    amount: 0,
    lable: "故障平均响应效率",
    unit: "小时",
  },
  {
    amount: 0,
    lable: "故障平均排除效率",
    unit: "天",
  },
  {
    amount: 0,
    lable: "故障处置率",
    unit: "%",
  },
];
const refresh = computed(() => store.state.ele?.refresh);
const year = computed(() => store.state.ele?.currentTime);
const orgCode = computed(() => store.state.ele?.orgCode);
const orgType = computed(() => store.state.ele?.orgType);
const pOrg = computed(() => store.state.ele?.pOrg);
watch([refresh], () => {
  initData(year.value);
});
// 初始化
const initData = (year: any) => {
  getfaultRate(year);
  maintTaskData(year);
  getfaultSatisfied(year);
};
const getChartDataByBtnOne = (params: any) => {
  getfaultRate(params);
};
const getChartDataByBtnTwo = (params: any) => {
  maintTaskData(params);
};
const getChartDataByBtnThree = (params: any) => {
  getfaultSatisfied(params);
};

// 故障分析
const getfaultRate = (year: any) => {
  if (!orgCode.value) {
    return;
  }
  faultRate({
    year: year,
    ...orgCode.value
  }).then(({ code, msg, data }) => {
    if (code === 0) {
      if (data) {
        let rateList = ["rate1", "rate2", "rate3", "rate4", "rate5", "rate6"];
        rateList.map((item, index) => {
          const target = numList.dataList[index]
          if (item === "rate4") {
            target.amount = (data[item] / 60).toFixed(1) || 0;
          } else if (item === "rate5") {
            target.amount = (data[item] / 24 / 60).toFixed(1) || 0;
          } else if (item === "rate1") {
            target.amount = data[item].toFixed(1) || 0;
          } else {
            target.amount = (data[item] * 100).toFixed(1) || 0;
          }
        });
      } else {
        numList.dataList = [
          {
            amount: 0,
            lable: "故障超期数量",
            unit: "个",
          },
          {
            amount: 0,
            lable: "机电任务排除时效满足率",
            unit: "%",
          },
          {
            amount: 0,
            lable: "机电故障误报率",
            unit: "%",
          },
          {
            amount: 0,
            lable: "故障平均响应效率",
            unit: "小时",
          },
          {
            amount: 0,
            lable: "故障平均排除效率",
            unit: "天",
          },
          {
            amount: 0,
            lable: "故障处置率",
            unit: "%",
          },
        ];
      }
    }
  });
};
// 任务执行情况
const maintTaskData = (year: any) => {
  if (!orgCode.value) {
    return;
  }
  maintTaskLine({
    year: year,
    ...orgCode.value
  }).then(({ code, msg, data }) => {
    if (code === 0) {
      data && data.forEach(el => {
        taskLine.dataList.forEach(item => {
          if (el.text === item.text) {
            item.value = el.value
          }
        })
      })
      nextTick(() => {
        drawChart()
      })
    }
  });
};
const handleEchart = (arr: any) => {
  let maxArr: any = [];
  arr.forEach((item: any) => {
    maxArr.push(item.value);
  });
  let MaxArrp = Math.max(...maxArr);
  let radar: any = [];
  let series: any = [];
  arr.forEach((item: any) => {
    radar.push({ name: item.text, max: MaxArrp });
    series.push(item.value);
  });
  return {
    series,
    radar,
  };
};
const getfaultSatisfied = (year: any) => {
  let params = {};
  if (orgType.value) {
    params = pOrg.value;
  } else {
    params = orgCode.value;
  }
  faultSatisfied({
    year: year,
    ...params,
  }).then(({ code, msg, data }) => {
    if (code === 0) {
      if (data) {
        Object.assign(faultOption, handleProject(data));
      }
    }
  });
};
const handleProject = (data: any) => {
  let name: any = [];
  let num1: any = [];
  let num2: any = [];
  let num3: any = [];
  let num4: any = [];
  data.forEach((it: any) => {
    name.push(it.name);
    num1.push(it.num1);
    num2.push(it.num2);
    num3.push(it.num3);
    num4.push(it.num4);
  });
  return {
    name,
    num1,
    num2,
    num3,
    num4,
  };
};
const drawChart = () => {
  // 基于准备好的dom，初始化echarts实例
  console.log(echarts)
  let myChart = echarts.init(document.getElementById('chart'))
  const total = taskLine.dataList.reduce((pre, cur) => pre + parseInt(cur.value), 0)
  console.log(total)
  const chartData = taskLine.dataList.map(item => {
    return {
      itemStyle: {
        borderColor: "#0c1622",
        borderRadius: 500,
        borderWidth: 4,
      },
      name: item.text,
      value: parseInt(item.value)
    }
  })
  document.getElementById('chart').setAttribute('_echarts_instance_', '')
  // 绘制图表
  myChart.setOption(
    {
      title: {
        text: `${total}`,
        subtext: '数量',
        left: 145,
        top: 150,
        textAlign: 'center',
        textStyle: {
          color: '#F0F2F5',
          fontSize: 22
        },
        subtextStyle: {
          color: '#F0F2F5',
          fontSize: 12
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      graphic: {
        elements: [
          {
            type: 'image',
            z: 3,
            style: {
              image: chartsPerson,
              width: 100,
              height:100,
            },
            left: '100',
            top: '120'
          }
        ]
      },
      series: [
        {
          type: 'pie',
          radius: ['65%', '80%'],
          width: 150,
          center: ['150px', '170px'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          itemStyle: {
            normal: {
              color: function (colors) {
                var colorList = [
                  '#727FF7',
                  '#C372F7',
                  '#D26254',
                  '#2D85F8',
                ];
                return colorList[colors.dataIndex];
              }
            },
          },
          labelLine: {
            show: false
          },
          data: chartData
        }
      ]
    })
  console.log({
    title: {
      text: `${total}`,
      subtext: '数量',
      left: 195,
      top: 130,
      textAlign: 'center',
      textStyle: {
        color: '#F0F2F5',
        fontSize: 22
      },
      subtextStyle: {
        color: '#F0F2F5',
        fontSize: 12
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    graphic: {
      elements: [
        {
          type: 'image',
          z: 3,
          style: {
            image: chartsPerson,
            width: 100
          },
          left: '100',
          top: '60'
        }
      ]
    },
    series: [
      {
        type: 'pie',
        radius: ['65%', '80%'],
        center: ['200px', '170px'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        itemStyle: {
          normal: {
            color: function (colors) {
              var colorList = [
                '#727FF7',
                '#C372F7',
                '#D26254',
                '#2D85F8',
              ];
              return colorList[colors.dataIndex];
            }
          },
        },
        labelLine: {
          show: false
        },
        data: chartData
      }
    ]
  })

}
</script>

  
<style lang="scss" scoped>
@import "~/styles/viewport-convert.scss";
#chart{
  position: relative;
  left: 40px;
}
.eBarOrder {
  width: 100%;
  height: 28vh;
}

.charts {
  position: relative;
  width: 100%;

  .chart1 {
    left: 170px;
    top: 40px
  }

  .chart2 {
    left: 270px;
    top: 100px
  }

  .chart3 {
    left: 260px;
    top: 180px
  }

  .chart5 {
    left: 200px;
    top: 250px
  }
.chart4 {
    left: 8px;
    top: 138px;
  }
  .chartNumber {
    position: absolute;
    display: flex;

    img {
      height: 49px;
      width: 57px;
    }

    .status {
      font-size: 16px;
      font-family: Adobe Heiti Std;
      font-weight: normal;
      color: #778FA4;
    }

    .value {
      font-size: 21px;
      font-family: Myriad Pro;
      font-weight: 400;
      color: #FFFFFF;
    }
  }
}

.ePieRadar {
  width: 100%;
  height: vh(350);
}

.number-wrapper {
  display: grid;
  width: 100%;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr;

  .number-box {
    width: 52%;
    margin: 0 auto;
    text-align: center;

    .top {
      position: relative;
    }

    .text {
      position: absolute;
      top: 10px;
      right: 0;
      left: 0;
      font-size: 16px;
      color: #1afcff;

      span {
        font-size: 14px;
      }
    }
  }
}

.bottom {
  width: 180%;
  margin-top: -10px;
  margin-left: -26px;
}

.number-img {
  width: 100%;
}

.text-light {
  position: absolute;
  right: 0;
  left: 0;
  font-size: 11px;
}
</style>
