<template>
  <div class="app-container">
    <el-form
      ref="form"
      label-position="right"
      size="small"
      label-width="100px"
      inline
    >
      <el-form-item label="日期选择" prop="timeType">
        <el-select
          v-model="timeType"
          clearable
          class="filter-item"
          style="width: 150px"
        >
          <el-option
            v-for="item in [
              { label: '周', id: 1 },
              { label: '月', id: 2 },
              { label: '年', id: 3 }
            ]"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="username">
        <el-date-picker
          v-if="timeType === 1"
          v-model="time"
          type="week"
          format="yyyy 第 WW 周"
          placeholder="选择周"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="{ firstDayOfWeek: 1 }"
        >
        </el-date-picker>
        <el-date-picker
          v-else-if="timeType === 2"
          v-model="time"
          type="month"
          placeholder="选择月"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
        <el-date-picker
          v-else-if="timeType === 3"
          v-model="time"
          type="year"
          placeholder="选择年"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="!time" @click="onSubmit"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <ul class="data-list">
      <li
        v-for="(item, index) in optArr"
        :key="index"
        :class="[optActive === item.key ? 'active' : '']"
        @click="setLineChart(item.key, index)"
      >
        <p v-if="item.key === 'finishReadRateMap'">
          {{ (item.num * 100).toFixed(2) }}%
        </p>
        <p v-else-if="item.key === 'orderAmountMap'">
          {{ (item.num / 100).toFixed(2) }}元
        </p>
        <p v-else-if="item.unit === 's'">{{ formatDuration(item.num) }}</p>
        <p v-else>{{ item.num }}</p>
        <h5>{{ item.label }}</h5>
      </li>
    </ul>
    <div id="line-chart" class="line-chart"></div>
    <div class="data-chart-wrap">
      <div class="title">
        <h2>营销产品转化漏斗</h2>
        <p>（统计配置了购物车的直播数据)</p>
      </div>
      <div class="data-chart-content">
        <div class="data-chart">
          <div class="data-item">
            <h3>累计观看直播用户</h3>
            <p>{{ funnelDataObj.totalReadUserCount || 0 }}</p>
            <div class="trapezoid-wrap trapezoid-wrap1">
              <div class="trapezoid trapezoid1"></div>
              <span>直播间用户</span>
            </div>
          </div>
          <div class="data-item">
            <h3>累计点击产品用户</h3>
            <p>{{ funnelDataObj.totalReadCartUserCount || 0 }}</p>
            <div class="trapezoid-wrap trapezoid-wrap2">
              <div class="trapezoid trapezoid2"></div>
              <span>访问产品</span>
            </div>
          </div>
          <div class="data-item flex">
            <div>
              <h3>下单用户数</h3>
              <p>{{ funnelDataObj.orderUserCount || 0 }}</p>
            </div>
            <div>
              <h3>下单订单数</h3>
              <p>{{ funnelDataObj.orderCount || 0 }}</p>
            </div>
            <div>
              <h3>订单金额</h3>
              <p>
                {{
                  funnelDataObj.orderAmount
                    ? (funnelDataObj.orderAmount / 100).toFixed(2)
                    : "0.00"
                }}
              </p>
            </div>
            <!-- <div>
              <h3>提佣订单数</h3>
              <p>{{ funnelDataObj.commOrderCount  || 0  }}</p>
            </div> -->
            <div class="trapezoid-wrap trapezoid-wrap3">
              <div class="trapezoid trapezoid3"></div>
              <span>下单</span>
            </div>
          </div>
          <div class="data-item flex">
            <div>
              <h3>成交用户数</h3>
              <p>{{ funnelDataObj.paidUserCount || 0 }}</p>
            </div>
            <div>
              <h3>成交订单数</h3>
              <p>{{ funnelDataObj.paidOrderCount || 0 }}</p>
            </div>
            <div>
              <h3>成交金额</h3>
              <p>
                {{
                  funnelDataObj.paidAmount
                    ? (funnelDataObj.paidAmount / 100).toFixed(2)
                    : "0.00"
                }}
              </p>
            </div>
            <!-- <div>
              <h3>提佣签约订单数</h3>
              <p>{{ funnelDataObj.count2PayTypeComm  || 0  }}</p>
            </div> -->
            <div class="trapezoid-wrap trapezoid-wrap4">
              <div class="trapezoid trapezoid4"></div>
              <span>签约</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="tabs-wrap">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane key="1" label="观看用户数榜单" name="1">
          <DataTableTg
            v-if="activeName === '1'"
            key="1"
            ref="tableRef1"
            :end-time="endTime1"
            :start-time="startTime1"
            :rank-type="1"
            :rankingType="rankingType"
            :timeType1="timeType1"
          />
        </el-tab-pane>
        <el-tab-pane key="2" label="观看时长榜单" name="2"
          ><DataTableTg
            v-if="activeName === '2'"
            key="2"
            ref="tableRef2"
            :end-time="endTime1"
            :start-time="startTime1"
            :rank-type="2"
            :rankingType="rankingType"
            :timeType1="timeType1"
        /></el-tab-pane>
        <el-tab-pane key="3" label="带货订单数榜单" name="3"
          ><DataTableTg
            v-if="activeName === '3'"
            key="3"
            ref="tableRef3"
            :end-time="endTime1"
            :start-time="startTime1"
            :rank-type="3"
            :rankingType="rankingType"
            :timeType1="timeType1"
        /></el-tab-pane>
        <el-tab-pane key="4" label="带货订单金额榜单" name="4"
          ><DataTableTg
            v-if="activeName === '4'"
            key="4"
            ref="tableRef4"
            :end-time="endTime1"
            :start-time="startTime1"
            :rank-type="4"
            :rankingType="rankingType"
            :timeType1="timeType1"
        /></el-tab-pane>
      </el-tabs>
      <el-form
        ref="form1"
        label-position="right"
        size="small"
        label-width="100px"
        inline
      >
        <el-form-item label="" prop="timeType1">
          <el-select
            v-model="timeType1"
            class="filter-item"
            style="width: 100px"
          >
            <el-option
              v-for="item in [
                { label: '总榜单', id: 1 },
                { label: '年榜', id: 2 },
                { label: '月', id: 3 },
                { label: '周', id: 4 },
                { label: '日', id: 5 }
              ]"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="username">
          <el-date-picker
            v-if="timeType1 === 2"
            v-model="time1"
            type="year"
            placeholder="选择年"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100px"
          >
          </el-date-picker>
          <el-date-picker
            v-else-if="timeType1 === 3"
            v-model="time1"
            type="month"
            placeholder="选择月"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100px"
          >
          </el-date-picker>
          <el-date-picker
            v-else-if="timeType1 === 4"
            v-model="time1"
            type="week"
            format="yyyy 第 WW 周"
            placeholder="选择周"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100px"
            :picker-options="{ firstDayOfWeek: 1 }"
          >
          </el-date-picker>
          <el-date-picker
            v-else-if="timeType1 === 5"
            v-model="time1"
            type="date"
            placeholder="选择日期"
            style="width: 100px"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onTableSubmit">查询</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import dayjs from "dayjs";
import { setLineOptions } from "./config";
import { tgList } from "@/api/adviser";
import { liveFunnelStatistic, liveOperationStatistic } from "@/api/index";
import { mapGetters } from "vuex";
import DataTableTg from "./components/DataTableTg.vue";
import "dayjs/locale/zh-cn";
var weekday = require("dayjs/plugin/weekday");
dayjs.extend(weekday);
dayjs.locale("zh-cn");
export default {
  components: { DataTableTg },
  activated() {},
  data() {
    return {
      tgId: "",
      tgList: [],
      timeType: 1,
      timeType1: 1,
      startTime: "",
      startTime1: "",
      endTime: "",
      endTime1: "",
      time: "",
      time1: "",
      optActive: "",
      activeName: "1",
      rankingType: "", // 榜单类型
      optArr: [
        {
          num: 0,
          label: "直播数",
          key: "videoCountMap",
          unit: ""
        },
        {
          num: 0,
          label: "直播时长",
          key: "videoHourMap",
          unit: "s"
        },
        {
          num: 0,
          label: "观看人次",
          key: "readCountMap",
          unit: ""
        },
        {
          num: 0,
          label: "观看人数",
          key: "readUserCountMap",
          unit: ""
        },
        {
          num: 0,
          label: "观看时长",
          key: "readHoursMap",
          unit: "s"
        },
        {
          num: 0,
          label: "人均观看时长",
          key: "avgReadHoursMap",
          unit: "s"
        },
        {
          num: 0,
          label: "完播率",
          key: "finishReadRateMap",
          unit: "%"
        },
        {
          num: 0,
          label: "参与互动人数",
          key: "joinUserCountMap",
          unit: ""
        },
        {
          num: 0,
          label: "点击产品数",
          key: "browseProCountMap",
          unit: ""
        },
        {
          num: 0,
          label: "下单未支付数",
          key: "orderButNotPayCountMap",
          unit: ""
        },
        {
          num: 0,
          label: "直播成交订单数",
          key: "orderCountMap",
          unit: ""
        },
        {
          num: 0,
          label: "直播成交金额",
          key: "orderAmountMap",
          unit: "分"
        }
      ],
      optDataObj: {},
      funnelDataObj: {}, // 漏斗数据
      lineChart: null
    };
  },
  computed: {
    ...mapGetters(["user"])
  },
  watch: {
    timeType(value) {
      this.time = this.startTime = this.endTime = "";
    },
    timeType1(value) {
      this.time1 = this.startTime1 = this.endTime1 = "";
    },
    time(value) {
      this.startTime = value;
      if (value === null) {
        return (this.endTime = null);
      }
      if (this.startTime) {
        this.startTime = dayjs(this.startTime).format("YYYY-MM-DD HH:mm:ss");
      }
      switch (this.timeType) {
        case 1:
          this.startTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
          this.endTime = dayjs(value)
            .add(7, "day")
            .format("YYYY-MM-DD HH:mm:ss");
          break;
        case 2:
          this.endTime = dayjs(value)
            .add(1, "month")
            .format("YYYY-MM-DD HH:mm:ss");
          break;
        case 3:
          this.endTime = dayjs(value)
            .add(1, "year")
            .format("YYYY-MM-DD HH:mm:ss");
          break;
        default:
          break;
      }
    },
    time1(value) {
      this.startTime1 = value;
      if (value === null || value === "") {
        return (this.endTime1 = null);
      }
      if (this.startTime1 !== null) {
        this.startTime1 = dayjs(this.startTime1).format("YYYY-MM-DD HH:mm:ss");
      }
      if (this.timeType1 == 2) {
        this.endTime1 = dayjs(value)
          .add(1, "year")
          .format("YYYY-MM-DD HH:mm:ss");
      } else if (this.timeType1 == 3) {
        this.endTime1 = dayjs(value)
          .add(1, "month")
          .format("YYYY-MM-DD HH:mm:ss");
      } else if (this.timeType1 == 4) {
        this.startTime1 = dayjs(value)
          .subtract(1, "day")
          .format("YYYY-MM-DD HH:mm:ss");
        this.endTime1 = dayjs(value)
          .add(6, "day")
          .format("YYYY-MM-DD HH:mm:ss");
      } else if (this.timeType1 == 5) {
        this.endTime1 = dayjs(value)
          .add(1, "day")
          .format("YYYY-MM-DD HH:mm:ss");
      }
      // switch (this.timeType1 !== 1) {
      //   case 2:
      //     this.endTime1 = dayjs(value)
      //       .add(1, 'year')
      //       .format('YYYY-MM-DD HH:mm:ss')
      //     break
      //   case 3:
      //     this.endTime1 = dayjs(value)
      //       .add(1, 'month')
      //       .format('YYYY-MM-DD HH:mm:ss')
      //     break
      //   case 4:
      //     this.startTime1 = dayjs(value).subtract(1, 'day')
      //       .format('YYYY-MM-DD HH:mm:ss')
      //     this.endTime1 = dayjs(value)
      //       .add(6, 'day')
      //       .format('YYYY-MM-DD HH:mm:ss')
      //     break
      //   case 5:
      //     this.endTime1 = dayjs(value)
      //       .add(1, 'day')
      //       .format('YYYY-MM-DD HH:mm:ss')
      //     break
      //   default:
      //     break
      // }
    },
    activeName(value) {
      if (value) {
        this.timeType1 = 1;
      }
    }
  },
  created() {
    this.time = `${dayjs()
      .weekday(0)
      .format("YYYY-MM-DD")} 00:00:00`;
  },
  mounted() {
    this.$nextTick(() => {
      this.onSubmit();
    });
  },

  methods: {
    async getTgList(name) {
      const ret = await tgList({
        current: 1,
        name,
        showName: "",
        size: 100000,
        staffNo: "",
        status: 3
      });
      if (ret.code === 0) {
        this.tgList = ret.data.list;
      }
    },
    async getLiveOperationStatistic() {
      let ret = await liveOperationStatistic({
        advisorId:
          this.$store.state.user.user.advisorInfo &&
          this.$store.state.user.user.advisorInfo.id,
        endTime: this.endTime,
        searchType: this.timeType ? this.timeType : 3,
        startTime: this.startTime,
        userType: 1
      });
      if (ret.code === 0 && ret.data) {
        this.optDataObj = ret.data;
        let readHoursMap = 0;
        let readUserCountMap = 0;
        this.optArr.forEach(item => {
          item.num = 0;
          if (item.key === "finishReadRateMap") {
            item.num = this.optDataObj.totalFinishRate;
          } else if (item.key === "avgReadHoursMap") {
            item.num = readUserCountMap ? readHoursMap / readUserCountMap : 0;
          } else {
            for (const key in this.optDataObj[item.key] || {}) {
              item.num += this.optDataObj[item.key][key];
            }
          }
          if (item.key === "readHoursMap") {
            readHoursMap = item.num;
          } else if (item.key === "readUserCountMap") {
            readUserCountMap = item.num;
          }
        });

        this.setLineChart("videoCountMap", 0);
      } else if (ret.code === 0) {
        this.lineChart && this.lineChart.clear();
        this.optArr.forEach(item => {
          item.num = 0;
        });
      }
    },
    async getLiveFunnelStatistic() {
      const data = {
        type: 1,
        advisorId: this.user.advisorInfo && this.user.advisorInfo.id,
        startTime: this.startTime,
        endTime: this.endTime,
        userType: 1
      };
      const ret = await liveFunnelStatistic(data);
      if (ret.code === 0 && ret.data) {
        this.funnelDataObj = ret.data;
      }
    },
    setLineChart(key, index) {
      this.optActive = key;
      this.lineChart = echarts.init(document.getElementById("line-chart"));
      const xData = [];
      const seriesData = [];
      for (const subKey in this.optDataObj[key]) {
        if (this.timeType === 3) {
          xData.push(`${dayjs(subKey).format("MM")}月`);
        } else {
          xData.push(`${dayjs(subKey).format("YYYY-MM-DD")}`);
        }

        seriesData.push(this.optDataObj[key][subKey]);
      }
      this.lineChart.setOption(
        setLineOptions({ xData, seriesData, unit: this.optArr[index].unit })
      );
    },
    onSubmit() {
      this.getTgList();
      if (!this.endTime || !this.startTime) {
        this.startTime = "1999-01-01 00:00:00";
        this.endTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
      }
      this.getLiveFunnelStatistic();
      this.getLiveOperationStatistic();
    },
    onTableSubmit() {
      this.$nextTick(() => {
        this.$refs[`tableRef${this.activeName}`].pageChange(
          1,
          this.startTime1,
          this.endTime1
        );
      });
    },
    handleExport() {
      this.$nextTick(() => {
        this.$refs[`tableRef${this.activeName}`].handleExport();
      });
    },
    formatDuration(seconds) {
      var hours = Math.floor(seconds / 3600);
      var minutes = Math.floor((seconds % 3600) / 60);
      var secs = Math.floor(seconds % 60);

      return hours + "时" + minutes + "分" + secs + "秒";
    }
  }
};
</script>

<style scoped lang="scss">
.box {
  padding: 20px;
}
.mb10 {
  margin-bottom: 10px;
}
.flex-box {
  display: inline-flex;
  flex-direction: row;
  &_item {
    display: inline-flex;
    flex-direction: column;
    margin-right: 10px;
    cursor: pointer;
    background-color: rgb(255, 255, 255);
    align-self: center;
    div {
      padding: 5px 0;
      display: inline-flex;
      align-self: center;
    }
  }
}
.charts-box {
  padding: 20px;
  width: 60%;
}
.data-list {
  padding: 0;
  display: flex;
  list-style: none;
  li {
    position: relative;
    flex: 1;
    text-align: center;
    cursor: pointer;
    &.active::after {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      display: block;
      content: "";
      height: 2px;
      width: 20px;
      background-color: #409eff;
    }
    h5 {
      margin: 0 0 10px 0;
    }
  }
}
.line-chart {
  height: 400px;
}
.data-chart-wrap {
  margin-bottom: 50px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 40px;
    h2 {
      margin: 0;
      font-size: 24px;
    }
    p {
      margin: 0;
    }
  }
  .data-chart {
    & > div:nth-child(1) {
      background: #edf4fe;
    }
    & > div:nth-child(2) {
      background: #edd9ff;
    }
    & > div:nth-child(3) {
      background: #f3fcf9;
    }
    & > div:nth-child(4) {
      background: #fbf1ec;
    }

    .data-item {
      position: relative;
      padding: 10px 30px 10px;
      margin-bottom: 10px;
      &.flex {
        display: flex;
        & > div {
          margin-right: 50px;
        }
      }
      h3 {
        margin: 0;
        line-height: 40px;
        font-size: 20px;
      }
      p {
        margin: 0;
        font-weight: 900;
        font-size: 20px;
        line-height: 40px;
      }
    }
    .trapezoid-wrap {
      position: absolute;
      top: 0;
      bottom: 0;
      text-align: center;
      span {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translateX(-50%) translateY(-50%);
        color: #fff;
        font-size: 18px;
      }
      &.trapezoid-wrap1 {
        right: 80px;
      }
      &.trapezoid-wrap2 {
        right: 130px;
      }
      &.trapezoid-wrap3 {
        right: 130px;
      }
      &.trapezoid-wrap4 {
        right: 180px;
      }
    }
    .trapezoid1 {
      border-top: 100px solid #5a8af6;
      border-left: 45px solid transparent;
      border-right: 45px solid transparent;
      width: 440px;
      line-height: 100px;
    }
    .trapezoid2 {
      border-top: 100px solid #64cbba;
      border-left: 45px solid transparent;
      border-right: 45px solid transparent;
      width: 340px;
      line-height: 100px;
    }
    .trapezoid3 {
      border-top: 100px solid #f5c277;
      border-left: 45px solid transparent;
      border-right: 45px solid transparent;
      width: 240px;
      line-height: 100px;
    }
    .trapezoid4 {
      border-top: 100px solid #f77736;
      border-left: 35px solid transparent;
      border-right: 35px solid transparent;
      width: 140px;
      line-height: 100px;
    }
  }
}
.tabs-wrap {
  position: relative;
  .el-form {
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
