<template>
  <div class="w-full h-full" v-loading="loading">
    <div class="c-title flex justify-between">
      <span>目标完成情况</span>
      <div>
        <el-select
          size="mini"
          style="width: 100px; margin-right: 10px"
          v-model="queryParams.type"
          @change="dateTypeChange"
          placeholder="请选择时间纬度"
        >
          <el-option label="按年展示" value="reportYear"></el-option>
          <el-option label="按月展示" value="reportDate"></el-option>
        </el-select>

        <el-date-picker
          v-if="queryParams.type == 'reportYear'"
          style="width: 90px"
          size="mini"
          v-model="queryParams.reportYear"
          type="year"
          format="yyyy"
          value-format="yyyy"
          placeholder="选择年"
          :clearable="false"
          @change="getList"
        >
        </el-date-picker>
        <el-select
          v-else
          size="mini"
          style="width: 90px"
          v-model="queryParams.month"
          @change="initEcharts"
          placeholder="选择月"
        >
          <el-option
            v-for="(it, i) in 12"
            :key="i + 1"
            :label="`${i + 1}月`"
            :value="i + 1 < 10 ? '0' + (i + 1) : i + 1"
          ></el-option>
        </el-select>
        <el-select
          size="mini"
          style="width: 100px; margin-left: 10px"
          v-model="zdlx"
          @change="initEcharts"
          placeholder="请选择"
        >
          <el-option
            v-for="(ite, i) in yearTypeList"
            :key="i"
            :label="ite.label"
            :value="ite.key"
          ></el-option>
        </el-select>
      </div>
    </div>
    <div
      ref="barChart"
      id="barChart"
      :style="{ height: height, width: width }"
    ></div>
    <!-- <div
      v-else
      ref="stopTargetLineRef"
      id="stopTimeMonth"
      :style="{ height: height, width: width }"
    ></div> -->
  </div>
</template>

<script>
import moment from "moment/moment";
import * as echarts from "echarts";
import TargetLine from "../monthLine.vue";
import { stopActualList } from "@/api/powerdistribution/power-outage-control";
export default {
  components: { TargetLine },
  props: {
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "200px",
    },
  },
  data() {
    return {
      // 查询参数
      queryParams: {
        type: "reportYear",
        pageNum: 1,
        pageSize: 10,
        reportDate: null,
        month: `0${new Date().getMonth() + 1}`,
        reportYear: moment(new Date()).format("yyyy"),
      },
      zdlx: 1,
      dataList: [],
      loading: false,
      yearTypeList: [
        {
          label: "总目标",
          key: 1,
          value: {
            0: "stopTimeTotal",
            1: "stopTotalActual",
            2: "stopTotalRatio",
          },
          value2: { 0: "stopTimeMonth", 1: "stopMonth" },
        },
        {
          label: "计划停电目标",
          key: 2,
          value: {
            0: "planStopTimeTotal",
            1: "planStopTotalActual",
            2: "planStopTotalRatio",
          },
          value2: { 0: "planStopTimeMonth", 1: "planStopMonth" },
        },
        {
          label: "故障停电目标",
          key: 3,
          value: {
            0: "errorStopTimeTotal",
            1: "errorStopTotalActual",
            2: "errorStopTotalRatio",
          },
          value2: { 0: "errorStopTimeMonth", 1: "errorStopMonth" },
        },
      ],
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    dateTypeChange(e) {
      this.queryParams.type = e;
      this.dataList = [];
      if (e == "reportDate") {
        this.queryParams.reportYear = moment(new Date()).format("yyyy");
      } else {
        this.queryParams.month = `0${new Date().getMonth() + 1}`;
      }
      this.getList();
    },
    dateLxChange(e) {
      this.zdlx = e;
      if (this.queryParams.type == "reportYear") {
        this.initEcharts();
      } else {
        this.initEcharts2();
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      stopActualList(this.queryParams).then((response) => {
        this.dataList = response.rows.filter(
          (ite) => ite.companyName != "总计"
        );
        // this.cpList = this.dataList.map((ite) => ite.companyName);
        // this.currentCompany = this.cpList ? this.cpList[0] : "";
        this.loading = false;
        // if (this.queryParams.type == "reportYear") {
        this.initEcharts();
        // } else {
        //   this.initEcharts2();
        // }
      });
    },
    initEcharts() {
      let myChart = echarts.getInstanceByDom(
        document.getElementById("barChart")
      );
      if (myChart == null) {
        myChart = echarts.init(document.getElementById("barChart"));
      }
      const yAxisData = this.dataList.map((ite) => ite.companyName);
      let targetData = [];
      let actualData = [];
      let ratioData = [];
      if (this.queryParams.type == "reportYear") {
        const zdlx = this.yearTypeList.find(
          (ite) => ite.key == this.zdlx
        ).value;
        targetData = this.dataList.map((ite) => ite[zdlx[0]] || 0);
        actualData = this.dataList.map((ite) => ite[zdlx[1]] || 0);
        ratioData = this.dataList.map((ite) => ite[zdlx[2]] || "0%");
      } else {
        const zdlx = this.yearTypeList.find(
          (ite) => ite.key == this.zdlx
        ).value2;
        targetData = this.dataList.map(
          (ite) => ite[`${zdlx[0]}${this.queryParams.month}`] || 0
        );
        actualData = this.dataList.map(
          (ite) => ite[`${zdlx[1]}${this.queryParams.month}Actual`] || 0
        );
        ratioData = this.dataList.map(
          (ite) => ite[`${zdlx[2]}${this.queryParams.month}Ratio`] || "0%"
        );
      }

      // 指定图表的配置项和数据
      var option = {
        title: {
          show: this.dataList.length == 0,
          textStyle: {
            color: "#fff",
            // fontSize: 20,
          },
          text: "暂无数据",
          left: "center",
          top: "center",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params) {
            // params 是一个数组，数组中包含每个系列的数据信息
            let result = "";
            params.forEach(function (item) {
              // item 是每一个系列的数据
              const seriesName = item.seriesName; // 系列名称
              const value = item.value; // 数据值
              const marker = item.marker; // 标志图形
              result += `${marker}${seriesName}: ${value}<br/>`;
            });
            result += `${params[0].marker}执行率: ${
              ratioData[params[0].dataIndex]
            }`;
            return result;
          },
        },
        color: ["#00a4ff", "#0052F1"],
        textStyle: {
          color: "#fff",
        },
        legend: {
          top: "10",
          textStyle: {
            color: "#fff",
          },
        },
        grid: {
          left: "2%", //图表距离容器左侧多少距离
          right: "2%", //图表距离容器右侧侧多少距离
          bottom: "5%", //图表距离容器上面多少距离
          top: "10%", //图表距离容器下面多少距离
          containLabel: true,
        },
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.01],
          splitLine: {
            show: true,
            lineStyle: {
              color: ["#02367c"], // 设置 Y 轴分割线颜色为深灰色
            },
          },
        },
        yAxis: {
          type: "category",
          data: yAxisData,
        },
        series: [
          {
            name: "目标值",
            type: "bar",
            data: targetData,
            barMinHeight: 10,
            barMaxWidth: 15,
            label: {
              show: true,
              position: "right",
              fontSize: 14,
              color: "#fff",
            },
          },
          {
            name: "实际值",
            type: "bar",
            data: actualData,
            barMinHeight: 10,
            barMaxWidth: 15,
            label: {
              show: true,
              position: "right",
              fontSize: 14,
              color: "#fff",
            },
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.clear();
      myChart.setOption(option, true);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    initEcharts2() {
      let data = [];
      let legend = [];
      let series = [];
      data = this.dataList.filter(
        (ite) => ite.companyName == this.currentCompany
      );
      console.log(data, "data");

      const zdlx = this.yearTypeList.find((ite) => ite.key == this.zdlx).value2;
      data.forEach((e, i) => {
        legend.push(e.companyName);
        series.push(
          {
            name: `${e.companyName}目标值`,
            type: "line",
            stack: "Total",
            data: Array(12)
              .fill(0)
              .map((ite, i) => {
                return (
                  e[`${zdlx[0]}${i + 1 < 10 ? "0" + (i + 1) : i + 1}`] || 0
                );
              }),
          },
          {
            name: `${e.companyName}实际值`,
            type: "line",
            stack: "Total",
            data: Array(12)
              .fill(0)
              .map((ite, i) => {
                return (
                  e[`${zdlx[1]}${i + 1 < 10 ? "0" + (i + 1) : i + 1}Actual`] ||
                  0
                );
              }),
          }
        );
      });
      let myChart = echarts.getInstanceByDom(
        document.getElementById("stopTimeMonth")
      );
      if (myChart == null) {
        myChart = echarts.init(document.getElementById("stopTimeMonth"));
      }
      // 指定图表的配置项和数据
      var option = {
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            // params 是一个数组，数组中包含每个系列的数据信息
            let result = "";
            params.forEach(function (item, i) {
              // item 是每一个系列的数据
              const seriesName = item.seriesName; // 系列名称
              const value = item.value; // 数据值
              const marker = item.marker; // 标志图形
              result += `${marker}${seriesName}: ${value}<br/>`;
            });
            const ii = params[0].dataIndex;
            result += `${params[0].marker}执行率: ${
              data[0][`${zdlx[1]}${ii + 1 < 10 ? "0" + (ii + 1) : ii + 1}Ratio`]
            }<br/>`;
            return result;
          },
        },
        textStyle: {
          color: "#fff",
        },

        legend: {
          data: legend,
          type: "scroll",
          top: "8%",
          textStyle: {
            color: "#fff",
          },
        },
        grid: {
          left: "1%",
          right: "3%",
          bottom: "2%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: Array(12)
            .fill(0)
            .map((it, i) => `${i + 1}月`),
        },
        yAxis: {
          type: "value",
        },
        series: series,
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.clear();
      myChart.setOption(option, true);
      setTimeout(() => {
        myChart.resize();
      }, 100);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.c-title {
  border-left: 4px solid #00a4ff;
  padding-left: 10px;
  color: #00a4ff;
}
</style>
