<template>
  <div>
    <div class="dashboard-container">
      <el-row :gutter="24">
        <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">
          <vab-query-form style="float: right;">
            <vab-query-form-right-panel :span="24">
              <el-form :inline="true" :model="queryForm" @submit.prevent>
                <el-form-item class="ml10">
                  <ms-date-range-picker
                    v-model="order_time_range"
                    @update:modelValue="order_time_range = $event"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    icon="el-icon-search"
                    type="primary"
                    @click="fetchData"
                  >
                    {{ t('查询') }}
                  </el-button>
                </el-form-item>
              </el-form>
            </vab-query-form-right-panel>
          </vab-query-form>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <top-num
            background="white"
            :bottom-text="t('订单金额')"
            :count-config="orderAmountConfig"
            icon="money-cny-circle-line"
            :title="t('订单金额')"
            :unit-text="t('个')"
          />
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <top-num
            background="white"
            :bottom-text="t('订单数量')"
            :count-config="orderNumConfig"
            icon="numbers-line"
            :title="t('订单数量')"
            :unit-text="t('单')"
          />
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <top-num
            background="white"
            :bottom-text="t('退款金额')"
            :count-config="refundAmountConfig"
            icon="refund-2-line"
            :title="t('退款金额')"
            :unit-text="t('人')"
          />
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <top-num
            background="white"
            :bottom-text="t('退款单数')"
            :count-config="refundNumConfig"
            icon="refund-line"
            :title="t('退款单数')"
            :unit-text="t('个')"
          />
        </el-col>
      </el-row>

    </div>


    <el-row :gutter="24">
      <el-col :span="24">
        <div class="grid-content bg-purple">
          <el-card v-loading="loading" class="box-card">
            <template #header>
              <vab-icon icon="money-dollar-box-line" />
              {{ t('订单销售金额对比图') }}
              <el-radio-group
                v-model="saleTime"
                class="radio-inline"
                size="small"
                style="float: right"
                @change="getSaleOrderAmountFunEvt"
              >
                <el-radio-button
                  :label="7"
                >{{ t('7天') }}</el-radio-button>
                <el-radio-button
                  :label="30"
                >{{ t('30天') }}</el-radio-button>
                <el-radio-button
                  :label="90"
                >{{ t('3个月') }}</el-radio-button>
                <el-radio-button
                  :label="180"
                >{{ t('半年') }}</el-radio-button>
              </el-radio-group>
            </template>
            <ms-chart
              :init-options="initOptions"
              :option="polylineOptionMake"
              style="width: 100%"
              theme="ms-echarts-theme"
            />
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { translateTitle as t } from '@/utils/i18n'
import TopNum from '@/components/MsWidget/TopNum'
import MsDateRangePicker from '@/components/MsDateRangePicker'
import MsChart from '@/extra/VabChart'

import {
  getSaleOrderAmount,
  getOrderAmount,
  getOrderNum,
  getOrderNumTimeline,
} from '@/api/analytics/order'

import {
  getReturnAmount,
  getReturnNum,
  getReturnAmountTimeline,
  getReturnNumTimeline
} from '@/api/analytics/return'


import moment from "dayjs";
import { formatTimeLine, formatTimeLineRange } from "@/utils";

export default {
  name: 'OverviewTrade',
  components: { MsChart, TopNum, MsDateRangePicker },
  data() {
    return {
      saleTime: 7,
      orderAmountConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 2,
        prefix: '￥',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      refundAmountConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '￥',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      orderNumConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      refundNumConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      data: {
        order_num: 0,
        favorable_order_num: 0,
        user_reg_yestoday: [
          {
            num: 0,
          },
          {
            num: 0,
          },
        ],
        user_payment_yestoday: [
          {
            num: 0,
          },
          {
            num: 0,
          },
        ],
      },
      polylineOptionMake: {
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['订单数量', '成交金额', '退单数量', '退单金额'],
        },
        grid: {
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '订单数量',
            type: 'line',
            data: [],
          },
          {
            name: '成交金额',
            type: 'line',
            data: [],
          },
          {
            name: '退单数量',
            type: 'line',
            data: [],
          },
          {
            name: '退单金额',
            type: 'line',
            data: [],
          },
        ],
      },
      columnLoading: false,
      polylineLoading: false,
      loading: false,
      initOptions: {
        renderer: 'svg',
      },
      itemList: [],
      listLoading: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: '',
      order_time_range: ["", ""],
      userList: [],
      queryForm: {
        orderIsPaid : 3013, //交易模块，只计算支付订单
        stime: "",
        etime: ""
      },
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    t,
    goToPath(path, query) {
      this.$router.push({ path: path, query: query });
    },
    queryData() {
      this.fetchData();
    },
    fetchData() {
      console.info(JSON.stringify(this.queryForm))
      if (this.order_time_range.length > 0) {
        if (this.order_time_range[0]) {
          this.queryForm.stime = this.order_time_range[0].getTime();
        }
        if (this.order_time_range[1]) {
          this.queryForm.etime = this.order_time_range[1].getTime();
        }
      } else {
        this.queryForm.stime = null
        this.queryForm.etime = null
      }
      const params = this.queryForm;
      this.getOrderAmountFun(params);
      this.getReturnAmountFun(params);
      this.getOrderNumFun(params);
      this.getReturnNumFun(params);

      let days = 30;
      if (this.queryForm.stime && this.queryForm.etime) {

        days = (this.queryForm.etime - this.queryForm.stime) / (1000 * 3600 * 24);
        const timeRange = {
          days: days,
          stime: this.queryForm.stime,
          etime: this.queryForm.etime
        };
        this.saleTime = days;
        this.getSaleOrderAmountFunRange(timeRange);
      } else {
        this.getSaleOrderAmountFun(days);
      }
      //listOrderItemNumFun()
    },
    async getSaleOrderAmountFunRange(timeRange) {
      this.loading = true;
      const params = { stime: timeRange.stime, etime: timeRange.etime };
      const { data } = await getSaleOrderAmount(params);
      formatTimeLineRange(data, timeRange.days, timeRange.etime);
      const { data: dataNum } = await getOrderNumTimeline(params);
      formatTimeLineRange(dataNum, timeRange.days, timeRange.etime);
      const { data: returnAmount } = await getReturnAmountTimeline(params);
      formatTimeLineRange(returnAmount, timeRange.days, timeRange.etime);
      const { data: returnNum } = await getReturnNumTimeline(params);
      formatTimeLineRange(returnNum, timeRange.days, timeRange.etime);
      this.polylineOptionMake.xAxis.data = data.map((item) => item.time);
      this.polylineOptionMake.series[0].data = dataNum.map((item) => item.num);
      this.polylineOptionMake.series[1].data = data.map((item) => item.num);
      this.polylineOptionMake.series[2].data = returnNum.map((item) => item.num);
      this.polylineOptionMake.series[3].data = returnAmount.map((item) => item.num);
      this.loading = false;
    },
    async getOrderAmountFun(params) {
      const { data } = await getOrderAmount(params);
      data.today = data.current;
      data.yestoday = data.pre;
      this.orderAmountConfig = Object.assign(this.orderAmountConfig, data);
    },
    async getReturnAmountFun(params) {
      const { data } = await getReturnAmount(params);
      data.today = data.current;
      data.yestoday = data.pre;
      this.refundAmountConfig = Object.assign(this.refundAmountConfig, data);
    },
    async getOrderNumFun(params) {
      const { data } = await getOrderNum(params);
      data.today = data.current;
      data.yestoday = data.pre;
      this.orderNumConfig = Object.assign(this.orderNumConfig, data);
    },
    async getReturnNumFun(params) {
      const { data } = await getReturnNum(params);
      data.today = data.current;
      data.yestoday = data.pre;
      this.refundNumConfig = Object.assign(this.refundNumConfig, data);
    },
    async getSaleOrderAmountFunEvt() {
      await this.getSaleOrderAmountFun(parseInt(this.saleTime));
    },
    async getSaleOrderAmountFun(days) {
      this.loading = true;
      const start = new Date(moment(moment().subtract(days - 1, "days").format("YYYY-MM-DD")));
      const end = new Date();
      const params = { stime: start.getTime(), etime: end.getTime() };
      const { data } = await getSaleOrderAmount(params);
      formatTimeLine(data, days);
      const { data: dataNum } = await getOrderNumTimeline(params);
      formatTimeLine(dataNum, days);
      const { data: returnAmount } = await getReturnAmountTimeline(params);
      formatTimeLine(returnAmount, days);
      const { data: returnNum } = await getReturnNumTimeline(params);
      formatTimeLine(returnNum, days);
      this.polylineOptionMake.xAxis.data = data.map((item) => item.time);
      this.polylineOptionMake.series[0].data = dataNum.map((item) => item.num);
      this.polylineOptionMake.series[1].data = data.map((item) => item.num);
      this.polylineOptionMake.series[2].data = returnNum.map((item) => item.num);
      this.polylineOptionMake.series[3].data = returnAmount.map((item) => item.num);
      this.loading = false;
    },
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 0 !important;
  background: $base-color-background !important;

  :deep() {
    .el-card {
      height: 300px;

      [class*='-echart'] {
        width: 100%;
        height: 200px;
      }
    }
  }
}

.xe-icon {
  width: 80px;
  padding: 10px;

  .i-wh-workbench {
    display: block;
    color: #fff;
    text-align: center;
    font-size: 25px;
    line-height: 50px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-clip: padding-box;
  }
}

.xe-info {
}

.xe-num {
  display: block;
  font-size: 20px;
  font-weight: 400;
  color: #3e3f3f;
  text-align: left;
}

.xe-label {
  text-align: left;
  display: block;
  font-style: normal;
  font-size: 10px;
  text-transform: uppercase;
  color: #979898;
}

.xe-todo {
  text-align: right;
  display: block;
  font-style: normal;
  font-size: 10px;
  text-transform: uppercase;
  color: #979898;
  margin-top: 5px;
}

.el-row {
  margin-bottom: 0px;
}

:deep(.product-list) {
  .el-card__header {
    padding-bottom: 0 !important;
  }
}


.ml10 {
  margin-left: 10px;
}

</style>
