<template>
  <div>
    <div
      class="wall"
      style="height: 68px"
      v-if="JSON.stringify(items) == '{}'"
    ></div>
    <!-- 按月/按天 -->
    <div class="wrap">
      <!--   v-if="timer == 'day'"     :settings="chartSettings"   DD-->
      <ve-histogram
        :data="chartData"
        height="524px"
        :data-empty="dataEmpty"
        :extend="chartExtend"
        :legend="legend"
        :data-zoom="dataZoom"
      />
      <!-- <ve-line
      v-else
        :data-zoom="dataZoom"
        :settings="{
          area: true,
        }"
        :data="chartDataForMoth"
        height="350px"
        :data-empty="dataEmpty"
        :data-zoom="dataZoom"
        :extend="chartExtend"
        :legend="legend"
      /> -->
    </div>
  </div>
</template>

<script>
import "echarts/lib/component/dataZoom";
import countTo from "vue-count-to";
// import veLine from "v-charts/lib/line.common";
import histogram from "v-charts/lib/histogram.common";
import searchHeader from "./searchHeader";
import { getIndex } from "../../api";
import { getTimes } from "@/utils";
import { descs, chioseNum } from "../../constant";
import { orderType } from "@/constant";

export default {
  props: ["data", "search"],
  components: {
    // "ve-line": veLine,
    "count-to": countTo,
    "ve-histogram": histogram,
    searchHeader,
  },
  computed: {
    legend() {
      return {
        left: "10px",
      };
    },
    items() {
      let obj = {};
      let arr = [
        "TOTAL_AMOUNT",
        // "FINANCE_AMOUNT",
        // "FINANCE_BALANCE_AMOUNT",
        // "FINANCE_PAY",
      ];
      arr.forEach((str) => {
        if (this.data[str]) {
          obj[str] = this.data[str];
        }
      });
      // console.log(obj);
      return obj;
    },
    items2() {
      let obj = {};
      let arr = [
        "APPLY_AMOUNT",
        "RENEW_AMOUNT",
        "VIP_AMOUNT",
        "PRACTICE_AMOUNT",
        "OTHER_AMOUNT",
      ];
      arr.forEach((str) => {
        if (this.data[str]) {
          obj[str] = this.data[str];
        }
      });
      return obj;
    },
    chartExtend() {
      return {
        series: {
          smooth: false,
          barwidth: 80,
          label: {
            show: true,
            position: "top",
            color: "#000",
            formatter: function (value) {
              var val = value.data;
              return val + "%";
            },
          },
        },
        markerPoint: {
          data: { name: "百分比" },
        },

        yAxis: {
          //纵轴标尺固定
          minInterval: 1,
          type: "value",
          scale: true,
          min: 0,
          axisLabel: {
            formatter: "{value}%",
          },
        },

        xAxis: {
          interval: 0,
          axisLabel: {
            show: true, // 是否显示刻度标签，默认显示
            interval: 0, // 坐标轴刻度标签的显示间隔，在类目轴中有效；默认会采用标签不重叠的策略间隔显示标签；可以设置成0强制显示所有标签；如果设置为1，表示『隔一个标签显示一个标签』，如果值为2，表示隔两个标签显示一个标签，以此类推。
            inside: false, // 刻度标签是否朝内，默认朝外
            margin: 6, // 刻度标签与轴线之间的距离
            formatter: function (value) {
              return value.split("").join("\n");
            },
          },
        },

        tooltip: {
          axisPointer: {
            type: "shadow",
            shadowStyle: {
              color: "rgba(150,150,150,0.2)",
            },
          },

          formatter: (item) => {
            // console.log(item);
            // console.log(this.values, item[0].axisValue, "organ");
            let arr = [
              { name: "总收入", dot: "元" },
              { name: "总收入占比", dot: "%" },
              { name: "报名缴费收入", dot: "元" },
              { name: "乐团续费收入", dot: "元" },
              { name: "VIP课收入", dot: "元" },
              { name: "网管课收入", dot: "元" },
              { name: "其他收入", dot: "元" },
            ];
            return [
              item[0].axisValueLabel,
              ...arr.map(
                (d) =>
                  `<br/>${d.name}:${this.values[item[0].axisValue][d.name]}${
                    d.dot
                  }`
              ),
            ].join("");
          },
        },
      };
    },
    dataZoom() {
      return [
        {
          show: true,
          type: "slider",
          start: 0,
          end: 20,
          filterMode: "empty",
        },
      ];
    },
    chartData() {
      //
      const values = Object.values({ ...this.items, ...this.items2 });
      const organ = {};
      const organNameList = [];
      // 计算总的百分比
      for (const row of values[0].organIndexMonthData || []) {
        const key = row.organName;
        organ[key] = {
          分部: row.organName,
        };
        for (const item of values) {
          if (item.title == row.title) {
            organ[key][item.title] = row.percent;
          }

          if (item.title == "总收入" && row.title == "总收入") {
            organ[key]["总收入占比"] = (
              (row.percent / item.percent) *
              100
            ).toFixed(2);
          }
        }
      }
      for (const item of values) {
        for (const row of item.organIndexMonthData || []) {
          if (item.title == row.title) {
            organ[row.organName][row.title] = row.percent;
          }
        }
      }

      // const months = {};
      // for (const item of values) {
      //   for (const row of item.indexMonthData || []) {
      //     const key = this.$helpers.dayjs(row.month).format("YYYY-MM-DD");
      //     if (!months[key]) {
      //       months[key] = {
      //         日期: key,
      //       };
      //     }
      //     months[key][item.title] = row.percent;
      //   }
      // }
      console.log(organ);
      this.values = organ;
      // console.log(values);
      // return;
      return {
        columns: ["分部", "总收入占比"],
        rows: Object.values(organ),
        loading: true,
      };
    },
    chartDataForMoth() {
      const values = Object.values({ ...this.items, ...this.items2 });
      const months = {};
      for (const item of values) {
        for (const row of item.indexMonthData || []) {
          const key = this.$helpers.dayjs(row.month).format("YYYY-MM");

          if (!months[key]) {
            months[key] = {
              月份: key,
            };
            months[key][item.title] = row.percent;
          } else {
            if (months[key][item.title]) {
              months[key][item.title] = (
                parseFloat(months[key][item.title]) + parseFloat(row.percent)
              ).toFixed(2);
            } else {
              months[key][item.title] = parseFloat(row.percent).toFixed(2);
            }
          }
        }
      }
      return {
        columns: [
          "月份",
          "总收入",
          "现金收入",
          "余额收入",
          "财务支出",
          "报名缴费收入",
          "网管课收入",
          "其他收入",
          "乐团续费收入",
          "VIP课收入",
        ],
        rows: Object.values(months),
        loading: true,
      };
    },
    dataEmpty() {
      return !this.chartData.rows.length;
    },
  },
  data() {
    // this.chartSettings = {
    //   stack: { 总收入: [`现金收入`, `余额收入`] },
    // };
    return {
      orderType,
      active: "SHOULD_INCOME_MONEY",
      mdate: [],
      loading: false,
      endDate: "",
      show: true,
      activeName: "first",
      timer: "day",
      values: "",
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // this.$refs.searchHeader.initStatue("month");
      this.mdate = this.getInitDate();
      this.endDate = this.$helpers.dayjs(new Date()).format("YYYY-MM-DD");
      this.isDayOrMoth(this.mdate);
      // // this.$refs.searchHeader.initStatue()
      // this.changeValue(this.mdate);
    },
    // changeValue(date) {
    //   // 请求更改数据
    //   this.mdate = date;
    //   this.isDayOrMoth(date);
    //   this.FetchDetail();
    // },
    // async FetchDetail() {
    //   this.loading = true;
    //   let data = [];
    //   try {
    //     const { dates, ...rest } = this.search;
    //     const res = await getIndex({
    //       ...rest,
    //       ...getTimes(this.mdate, ["startDate", "endDate"]),
    //       //
    //       dataTypes:
    //         "FINANCE_AMOUNT,FINANCE_BALANCE_AMOUNT,FINANCE_PAY,TOTAL_AMOUNT",
    //     });
    //     for (const item of res.data) {
    //       // 再循环一遍
    //       for (const key in { ...this.items, ...this.items2 }) {
    //         // console.log(key);
    //         if (item.dataType == key) {
    //           data[item.dataType] = {
    //             ...item,
    //             desc: descs[item.dataType],
    //           };
    //         }
    //       }
    //     }
    //   } catch (error) {
    //     console.log(error);
    //   }
    //   this.loading = false;
    //   this.$emit("resetDate", data);
    // },

    isDayOrMoth(arr) {
      if (!arr || arr.length < 1) {
        this.timer = "day";
      } else {
        const count = this.$helpers
          .dayjs(arr[0])
          .diff(this.$helpers.dayjs(arr[1]), "day");
        Math.abs(count) > chioseNum
          ? (this.timer = "month")
          : (this.timer = "day");
      }
    },
    getInitDate() {
      const end = this.$helpers.dayjs(new Date()).format("YYYY-MM-DD");
      const start = this.$helpers
        .dayjs(new Date())
        .set("date", 1)
        .format("YYYY-MM-DD");
      return [start, end];
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.description-title {
  margin-bottom: 0;
}
#management .statistic .statistic-content > span {
  &:first-child {
    font-size: 14px !important;
  }
  font-size: 18px !important;
}
.chioseBox {
  position: absolute;
  right: 20px;
  z-index: 1000;
}
.wrap {
  position: relative;
}
.blod {
  font-weight: bold;
  color: var(--color-primary);
  font-size: 22px !important;
}
// .chioseBox {
//   position: absolute;
//   right: 20px;
//   z-index: 1000;
// }
// .wrap {
//   position: relative;
// }
.statisticWrap {
  // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  border: 1px solid #ebeef5;
  padding-top: 10px;
  margin-bottom: 10px;
  position: relative;
  &:after {
    top: -16px;
    margin-left: calc(10% - 14px);
    border-top-width: 0;
    border-color: transparent;
    border-bottom-color: #fff;
    content: " ";
    border-width: 8px;
    position: absolute;
    display: block;
    width: 0;
    height: 0;

    border-style: solid;
    z-index: 101;
  }
  &:before {
    top: -20px;
    margin-left: calc(10% - 16px);

    border-top-width: 0;
    border-color: transparent;
    border-bottom-color: #ebeef5;
    content: " ";
    border-width: 10px;
    position: absolute;
    display: block;
    width: 0;
    height: 0;

    border-style: solid;
    z-index: 100;
  }
}
</style>
