<template>
  <div>
    <div
      class="wall"
      style="height: 68px"
      v-if="JSON.stringify(items) == '{}'"
    ></div>
    <statistic :col="3" class="statistic" :cols="12" v-else>
      <statistic-item @click="active = 0">
        <span>
          {{ items["TOTAL_AMOUNT"].title + "(元)" }}
          <el-tooltip
            v-if="items['TOTAL_AMOUNT'].desc"
            :content="items['TOTAL_AMOUNT'].desc"
            :open-delay="0.3"
            placement="top"
          >
            <i
              style="margin-left: 5px; cursor: pointer"
              class="el-icon-warning-outline"
            />
          </el-tooltip>
        </span>
        <!--  12345678901.23 -->
        <span>
          <count-to
            :endVal="items['TOTAL_AMOUNT'].percent"
            :decimals="2"
            :class="'blod'"
        /></span>
      </statistic-item>
      <template v-for="(item, key) in items">
        <statistic-item
          v-if="item.dataType != 'TOTAL_AMOUNT'"
          :key="key"
          :class="{ active: active === key }"
          @click="active = key"
        >
          <span>
            {{ item.title + "(元)" }}
            <el-tooltip
              v-if="item.desc"
              :content="item.desc"
              :open-delay="0.3"
              placement="top"
            >
              <i
                style="margin-left: 5px; cursor: pointer"
                class="el-icon-warning-outline"
              />
            </el-tooltip>
          </span>
          <!--  12345678901.23 -->
          <span>
            <count-to
              :endVal="item.percent"
              :decimals="2"
              :class="item.dataType == 'TOTAL_AMOUNT' ? 'blod' : ''"
          /></span>
        </statistic-item>
      </template>

      <statistic-item></statistic-item>
    </statistic>

    <div class="statisticWrap" v-if="JSON.stringify(items2) !== '{}'">
      <statistic :col="5" class="statistic" :cols="0" :isNoLine="true">
        <statistic-item
          v-for="(item, key) in items2"
          :key="key"
          :class="{ active: active === key }"
          @click="active = key"
        >
          <template v-if="item.dataType != 'OTHER_AMOUNT'">
            <span>
              {{ item.title + "(元)" }}
              <!-- {{ item.dataType == 'OTHER_AMOUNT' ? 'other' : null }} -->
              <el-tooltip
                v-if="item.desc"
                :content="item.desc"
                :open-delay="0.3"
                placement="top"
              >
                <i
                  style="margin-left: 5px; cursor: pointer"
                  class="el-icon-warning-outline"
                />
              </el-tooltip>
            </span>
            <!--  12345678901.23 -->
            <span> <count-to :endVal="item.percent" :decimals="2" /></span>
          </template>
          <el-popover placement="top" width="400" v-else trigger="hover">
            <descriptions
              :column="1"
              v-if="(item.indexMonthDataDetail || []).length > 0"
            >
              <template
                v-for="(item, index) in item.indexMonthDataDetail || []"
              >
                <descriptions-item
                  :key="index"
                  :label="orderType[item.orderType]"
                  >{{ item.totalNum | moneyFormat }}元
                </descriptions-item>
              </template>
            </descriptions>
            <div slot="reference">
              <span>
                {{ item.title + "(元)" }}
                <el-tooltip
                  v-if="item.desc"
                  :content="item.desc"
                  :open-delay="0.3"
                  placement="top"
                >
                  <i
                    style="margin-left: 5px; cursor: pointer"
                    class="el-icon-warning-outline"
                  />
                </el-tooltip>
              </span>
              <span
                style="
                  font-size: 18px;
                  display: block;
                  color: rgba(0, 0, 0, 0.85);
                "
              >
                <count-to :endVal="item.percent" :decimals="2"
              /></span>
            </div>
          </el-popover>
        </statistic-item>
      </statistic>
    </div>

    <!-- 按月/按天 -->

    <div class="wrap">
      <div class="chioseBox">
        <el-radio-group v-model="timer">
          <el-radio-button label="day">按天</el-radio-button>
          <el-radio-button label="month">按月</el-radio-button>
        </el-radio-group>
      </div>
      <ve-line
        :loading="dataLoading"
        :data="timer == 'day' ? chartData : chartDataForMoth"
        height="350px"
        :data-empty="!dataLoading && dataEmpty"
        :extend="chartExtend"
        :legend="legend"
      />
      <!-- <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,
        },

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

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

          formatter: (item) => {
            return [
              item[0].axisValueLabel,
              ...item.map(
                (d) => `<br/>${d.marker}${d.seriesName}: ${d.value[1]} 元`
              ),
            ].join("");
          },
        },
      };
    },
    dataZoom() {
      return [
        {
          type: "slider",
          start: 50,
          end: 100,
          filterMode: "empty",
        },
      ];
    },
    chartData() {
      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-DD");
          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);
            }
          }
        }
      }
      // console.log(values);
      this.dataLoading = false;
      return {
        columns: [
          "日期",
          "总收入",
          "现金收入",
          "余额收入",
          // "财务支出",
          "报名缴费收入",
          "网管课收入",
          "其他收入",
          "乐团续费收入",
          "VIP课收入",
        ],
        rows: Object.values(months),
        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);
            }
          }
        }
      }
      this.dataLoading = false;
      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",
      dataLoading: true
    };
  },
  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>
::v-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(17% - 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(17% - 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>
