<template >
  <el-card>
    <div slot="header" class="clearfix">
      <searchHeader
        :dates="mdate"
        :title="'经营数据'"
        @changeValue="changeValue"
        :isShowQuert="true"
      />
    </div>
    <statistic :col="5" class="statistic" :cols="0">
      <statistic-item
        v-for="(item, key) in items"
        :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>
        <span>
          <count-to :endVal="item.percent" :decimals="2" />元
        </span>
      </statistic-item>
    </statistic>
    <!-- 按月/按天 -->

    <div class="wrap">
      <div class="chioseBox">
        <el-radio-group v-model="timer" size="mini">
          <el-radio-button label="day">按天</el-radio-button>
          <el-radio-button label="month">按月</el-radio-button>
        </el-radio-group>
      </div>
      <!--   v-if="timer == 'day'"    DD-->
      <ve-line
        :data="timer == 'day' ? chartData : chartDataForMoth"
        height="350px"
        :data-empty="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>
  </el-card>
</template>
<script>
import "echarts/lib/component/dataZoom";
import countTo from "vue-count-to";
import veLine from "v-charts/lib/line.common";
import searchHeader from "./modals/searchHeader";
import { getIndex } from "../api";
import { getTimes } from "@/utils";
import { descs, chioseNum } from "../constant";

export default {
  props: ["data", "search"],
  components: {
    "ve-line": veLine,
    "count-to": countTo,
    searchHeader,
  },
  computed: {
    legend() {
      return {
        left: "10px",
      };
    },
    items() {
      return {
        FINANCE_AMOUNT: this.data["FINANCE_AMOUNT"] || {},
        FINANCE_BALANCE_AMOUNT: this.data["FINANCE_BALANCE_AMOUNT"] || {},
        FINANCE_PAY: this.data["FINANCE_PAY"] || {},
      };
    },
    chartExtend() {
      return {
        series: {
          smooth: false,
        },
        yAxis: {
          //纵轴标尺固定
          minInterval:1,
          type: "value",
          scale: true,
          min: 0,
          axisLabel: {
            formatter: "{value}元",
          },
        },
        tooltip: {
          formatter: (item) => {
            return [
              item[0].axisValueLabel,
              ...item.map((d) => {
                return `<br/>${d.marker}${
                  d.seriesName
                }: ${this.$helpers.numeral(d.value[1]).format("0,0.00")}元`;
              }),
            ].join("");
          },
        },
      };
    },
    dataZoom() {
      return [
        {
          type: "slider",
          start: 50,
          end: 100,
          filterMode: "empty",
        },
      ];
    },
    chartData() {
      const values = Object.values(this.items);
      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;
        }
      }
      return {
        columns: ["日期", ...values.map((item) => item.title)],
        rows: Object.values(months),
        loading: true,
      };
    },
    chartDataForMoth() {
      const values = Object.values(this.items);
      console.log(values);
      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(row.percent);
            } else {
              months[key][item.title] = row.percent;
            }
          }
        }
      }

      return {
        columns: ["月份", ...values.map((item) => item.title)],
        rows: Object.values(months),
        loading: true,
      };
    },

    dataEmpty() {
      return !this.chartData.rows.length;
    },
  },
  data() {
    return {
      active: "SHOULD_INCOME_MONEY",
      timer: "day",
      mdate: this.search?.dates,
      loading: false,
    };
  },
  created() {
    console.log(this.search?.dates);
  },
  methods: {
    changeValue(date) {
      // 请求更改数据
      this.mdate = date;
      this.isDayOrMoth(date);
      this.FetchDetail();
    },
    async FetchDetail() {
      this.loading = true;
      const data = this.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",
        });
        for (const item of res.data) {
          // 再循环一遍
          for (const key in this.items) {
            // console.log(key);
            if (item.dataType == key) {
              data[item.dataType] = {
                ...item,
                desc: descs[item.dataType],
              };
            }
          }
        }
      } catch (error) {
        console.log(error);
      }
      console.log(data);
      this.dataInfo = data;
      this.loading = false;
      this.$emit("resetDate", data);
    },

    isDayOrMoth(arr) {
      console.log(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");
      }
    },
  },
};
</script>
<style lang="less" scoped>
// .statistic{
//   /deep/ .statistic-content{
//     cursor: pointer;
//     &.active > span{
//       color: #14928a !important;
//     }
//   }
// }
.chioseBox {
  position: absolute;
  right: 20px;
  z-index: 1000;
}
.wrap {
  position: relative;
}
</style>
