<template>
  <div class="pages">
    <!-- 头 -->
    <div class="app-top">
      <div class="app-titel" style="margin-top: 10px">
        <div class="div-lab">
          <div class="titel-text">筛选日期：</div>
          <div style="margin-left: 14px">
            <el-button
              :class="{ 'el-button--primary': params.dateType == 1 }"
              @click="tabtimetap(1)"
              >近七天</el-button
            >
            <el-button
              :class="{ 'el-button--primary': params.dateType == 3 }"
              @click="tabtimetap(3)"
              >近15天</el-button
            >
            <el-button
              :class="{ 'el-button--primary': params.dateType == 2 }"
              @click="tabtimetap(2)"
              >近30天</el-button
            >
          </div>
          <div style="margin-left: 26px">
            <el-date-picker
              @change="confirmtime()"
              v-model="customtime"
              :clearable="false"
              type="daterange"
              range-separator="-"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </div>
        </div>

        <div class="div-lab" v-if="params.orgType != 3">
          <div class="label">项目名称：</div>
          <el-select
            class="div-inp"
            v-model="params.houseId"
            filterable
            clearable
            @change="houseChange"
            placeholder="请选择项目"
          >
            <el-option
              v-for="item in houseList"
              :key="item.id"
              :label="item.propertyName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>

        <div
          class="div-lab"
          style="padding: 0 20px 0 0; flex-grow: 1; justify-content: flex-end"
        >
          <div style="margin-left: 5px">
            <el-button @click="screen" type="primary">搜索</el-button>
          </div>
          <div style="margin-left: 20px">
            <el-button @click="empty" type="text">清空</el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="app-box-er">
      <div class="title">
        <div class="lefts">消费趋势</div>
        <el-select
          v-model="echarValue1"
          @change="echarValue1Change"
          style="width: 100px; margin-left: 10px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>

      <template v-if="echarValue1 == 0">
        <div class="tabcard">
          <el-card
            shadow="hover"
            v-for="(data, index) in showList"
            :key="index"
            :class="{ tophovese: selectShowIndex == index }"
          >
            <div @click="selectShowList(index)">
              <div class="text1">
                {{ data.title }}
              </div>
              <div class="text2">
                {{ data.value }}
              </div>
              <div class="text3">
                <span>对比时段 {{ data.value1 || 0 }}</span>
                <span class="textUp" v-if="data.value2 > 0">
                  +{{ data.value2 || 0 }}
                  <i class="up"></i>
                </span>
                <span class="textDown" v-if="data.value2 < 0">
                  -{{ data.value2 || 0 }}
                  <i class="down"></i>
                </span>
              </div>
            </div>
          </el-card>
        </div>
        <div id="main"></div>
      </template>

      <div v-else>
        <el-table
          :header-cell-style="{ background: '#F5F7FA', color: '#333333' }"
          :data="tableData"
          stripe
          style="width: 100%"
          height="440"
        >
          <el-table-column prop="date" label="日期" align="center">
          </el-table-column>
          <el-table-column prop="surplusSum" label="总时长" align="center">
          </el-table-column>
          <el-table-column
            prop="longTransferSum"
            label="长录音时长"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="shortTransferSum"
            label="短录音时长"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="avgTransferSum"
            label="平均接待转写时长"
            align="center"
          >
          </el-table-column>
        </el-table>

        <div style="display: flex; justify-content: flex-end; margin-top: 10px">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.current"
            :page-sizes="[10, 30, 50]"
            :page-size="params.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="params.total"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <section class="barBox">
      <div class="item l-side">
        <div class="title">
          <p>项目消费时长排名（top10）</p>
          <el-button type="text" size="medium" @click="allHousePage"
            >查看全部</el-button
          >
        </div>

        <div class="bar" id="lSideBar"></div>
      </div>
      <div class="item r-side">
        <div class="title">
          <p>项目平均接待转写时长排名（top10）</p>
          <el-button type="text" size="medium" @click="allHousePage"
            >查看全部</el-button
          >
        </div>

        <div class="bar" id="rSideBar"></div>
      </div>
    </section>




    <el-dialog
      title="项目转写时长"
      :visible.sync="housePageShow"
      :close-on-click-modal="false"
    >
      <div class="z-title">
        <p>
          统计时间：{{ housePageParams.date }}
        </p>
        <el-button @click="downloadExcel" type="primary">导出</el-button>
      </div>
      <el-table :data="housePage" height="400px">
        <el-table-column prop="houseName" label="项目名称"></el-table-column>
        <el-table-column prop="rechargeCount" label="消费时长"></el-table-column>
        <el-table-column prop="data" label="平均接待转写时长"> </el-table-column>
      </el-table>
      <div
        style="
          padding: 10px 0;
          width: 100%;
          display: flex;
          justify-content: flex-end;
        "
      >
        <el-pagination
          @size-change="handleSizeChangeLog"
          @current-change="handleCurrentChangeLog"
          :current-page="housePageParams.current"
          :page-sizes="[10, 50, 100]"
          :page-size="housePageParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="housePageParams.total"
        >
        </el-pagination>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import * as echarts from "echarts";
import { exportMethodPost } from "@/util/util";

export default {
  data() {
    return {
      //  入参
      params: {
        current: 1, //
        size: 10, // 分页
        total: 0, // 总条数
        dateType: 3, //  1近七天 3 近十五天 2近三十天
        startDate: "", // 开始时间
        endDate: "", // 结束时间
        operateType: "", // 0:购买，1: 赠送，2:扣除购买，3:扣除赠送，4:长录音转写扣除，5:短录音转写扣除
        houseId: "", // 项目id
        orgType: localStorage.getItem("orgType") || "", // 登陆后台
        agentId: localStorage.getItem("agentId") || "", // 代理商id
        orgCode: localStorage.getItem("orgCode") || "", // 公司code
      },

      customtime: [], // 自定义筛选的时间
      houseList: [], // 项目列表
      echarValue1: "0", // 0折线趋势图 1表格
      options1: [
        // 筛选表格类型
        {
          label: "趋势图",
          value: "0",
        },
        {
          label: "表格",
          value: "1",
        },
      ],
      showList: [
        // 展示四个模块
        {
          title: "转写总时长（小时）",
          paramsName: "allCostTransferTime", // 折线统计图&表格数据

          value: "", // 第一时段转写总时长值
          valueName: "useSum", // 转写总时长公用一个名字
          value1: "", // 第二时段转写总时长
          value2: "", // 第一二时段总时长对比
          //   折线统计图数据
          data: [], //时段a
          data1: [], //时段b
        },
        {
          title: "长录音时长（小时）",
          paramsName: "longCostTransferTime", // 折线统计图&表格数据

          value: "", // 第一时段长录音时长
          valueName: "longTransferSum", // 长录音时长 公用一个名字
          value1: "", // 第二时段长录音时长
          value2: "", // 第一二时段长录音对比

          //   折线统计图数据
          data: [], //时段a
          data1: [], //时段b
        },
        {
          title: "短录音时长（小时）",
          paramsName: "shortCostTransferTime", // 折线统计图&表格数据

          value: "", // 第一短录音时长
          valueName: "shortTransferSum", // 短录音时长
          value1: "", // 第二时段短录音时长
          value2: "", // 第一二时段短录音时长

          //   折线统计图数据
          data: [], //时段a
          data1: [], //时段b
        },
        {
          title: "平均接待转写时长（分）",
          paramsName: "avgCostTransferTime", // 折线统计图&表格数据

          value: "", // 第一时段平均接待转写时长
          valueName: "avgTransferSum", // 平均接待转写时长
          value1: "", // 第二时段平均接待转写时长
          value2: "", // 第一二时段平均接待转写时长

          //   折线统计图数据
          data: [], //时段a
          data1: [], //时段b
        },
      ], // 筛选用的数据
      selectShowIndex: 0, // 选中下标
      tableData: [], // 表格数据

      housePageShow: false,// 展示消费统计时长弹窗
      housePage: [], // 项目转写、消费统计时长
      housePageParams: {
        current: 1, //
        size: 10, // 分页
        total: 0, // 总条数
        date: '', // 
      }, // 全部撰写消费
    };
  },

  created() {
    this.getHouseList();
    this.consumptionTrend();
  },

  methods: {
    // 导出
    downloadExcel() {
      exportMethodPost(
        "/autoSR/zk/recharge/houseTransferTimeExport",
        "项目转写消费时长",
        this.params
      );
    },
    // 选择消费趋势的选项卡 只使用下标方便取当前选中的数组数据
    selectShowList(index) {
      // if (index == this.selectShowIndex) return
      this.selectShowIndex = index;
      let array = this.showList[index];
      console.log(array);
      let xAxis1 = array.data.map((item) => {
        return item.date;
      });
      let xAxis2 = array.data1.map((item) => {
        return item.date;
      });
      let yAxis1 = array.data.map((item) => {
        return item.data;
      });
      let yAxis2 = array.data1.map((item) => {
        return item.data;
      });
      let nameTime1 = `${array.data[0].date}-${
        array.data[array.data.length - 1].date
      }`;
      let nameTime2 = `${array.data1[0].date}-${
        array.data1[array.data1.length - 1].date
      }`;
      this.housePageParams.date = nameTime1
      let arr = [
        {
          name: nameTime1,
          type: "line",
          data: yAxis1,
        },
        {
          name: nameTime2,
          type: "line",
          data: yAxis2,
        },
      ];

      this.SwitchCARDS(arr, "main", [xAxis1, xAxis2], [nameTime1, nameTime2]);
    },
    // 消费趋势切换展示方式
    echarValue1Change(e) {
      if (e == 0) {
        this.$nextTick(() => {
          this.selectShowList(this.selectShowIndex);
        });
      }
    },
    tabtimetap(index) {
      this.params.dateType = index;
      this.consumptionTrend();
    },

    // 筛选
    screen() {
      this.consumptionTrend();
    },

    // 楼盘筛选
    houseChange() {
      this.consumptionTrend();
    },

    // 清空筛选
    empty() {
      this.params.dateType = 3; //  1近七天 2 近十五天 3近三十天
      this.params.operateType = ""; // 0:购买，1: 赠送，2:扣除购买，3:扣除赠送，4:长录音转写扣除，5:短录音转写扣除
      this.params.houseId = ""; // 项目id
      this.emptyTimePickerChoose();
    },

    // 清空时间选择器
    emptyTimePickerChoose() {
      this.customtime = [];
      this.params.startDate = ""; // 开始时间
      this.params.endDate = ""; // 结束时间
    },

    // 自定义时间筛选
    confirmtime() {
      this.params.startDate = this.customtime[0];
      this.params.endDate = this.customtime[1];
      this.params.dateType = null;
      this.consumptionTrend();
    },

    handleCurrentChange(e) {
      this.params.current = e;
      this.consumptionTrend();
    },
    handleSizeChange(e) {
      this.params.size = e;
      this.consumptionTrend();
    },

    // 获取转写消费统计
    consumptionTrend() {
      this.$api.http.consumptionTrend(this.params).then((res) => {
        console.log(res);
        if (res.data) {
          let obj = res.data;
          this.showList.forEach((item) => {
            // 这部分是消费趋势的card数据
            if (obj.firstValue) {
              item.value = obj.firstValue[item.valueName] || 0;
            }
            if (obj.secondValue) {
              item.value1 = obj.secondValue[item.valueName] || 0;
            }
            if (obj.contrast) {
              item.value2 = obj.contrast[item.valueName] || 0;
            }

            // 这部分是折线统计图数据
            if (obj.dataTable) {
              item.data = obj.dataTable[item.paramsName] || [];
            }
            if (obj.dataTable2) {
              item.data1 = obj.dataTable2[item.paramsName] || [];
            }
          });

          if (this.echarValue1 == 0) {
            this.selectShowList(this.selectShowIndex);
          }
          // 转写消费趋势表格数据
          if (obj.dataTablePage) {
            this.tableData = obj.dataTablePage.records;
            this.params.total = obj.dataTablePage.total;
          }
          // 项目消费时长Top10
          if (obj.houseCostTopTen) {
            this.creatHouseCostTopTen(obj.houseCostTopTen);
          }
          // 项目平均转写时长Top10
          if (obj.houseAvgCostTopTen) {
            this.creatHouseAvgCostTopTen(obj.houseAvgCostTopTen);
          }
        }
      });
    },

    handleSizeChangeLog(val) {
      this.housePageParams.current = val;
      this.allHousePage();
    },
    handleCurrentChangeLog(val) {
      this.housePageParams.size = val;
      this.allHousePage();
    },
    // 获取转写消费统计
    allHousePage() {
      let params = {
        dateType: this.params.dateType, //  1近七天 3 近十五天 2近三十天
        startDate: this.params.startDate, // 开始时间
        endDate: this.params.endDate, // 结束时间
        operateType: this.params.operateType, // 0:购买，1: 赠送，2:扣除购买，3:扣除赠送，4:长录音转写扣除，5:短录音转写扣除
        houseId: this.params.houseId, // 项目id
        orgType: this.params.orgType, // 登陆后台
        agentId: this.params.agentId, // 代理商id
        orgCode: this.params.orgCode, // 公司code
        ...this.housePageParams, // 合并分页
      };
      this.$api.http.allHousePage(params).then((res) => {
        console.log(res);
        if (res.data) {
          this.housePage = res.data.records;
          this.housePageParams.total = res.data.total;
          console.log(res.data.records, "housePage");
          this.housePageShow = true
        }
      });
    },
    // 处理项目消费时长Top10的数据
    creatHouseCostTopTen(data) {
      let [xAxis, yAxis] = [[], []];
      console.log(data);
      data.forEach((item, index) => {
        xAxis.push(item.houseName);
        yAxis.push({
          value: item.data,
          itemStyle: {
            color: this.setColor(index),
          },
        });
      });

      this.createdBar({
        id: "lSideBar",
        xAxis,
        yAxis,
      });
    },

    // 处理项目消费时长Top10的数据
    creatHouseAvgCostTopTen(data) {
      let [xAxis, yAxis] = [[], []];
      console.log(data);
      data.forEach((item, index) => {
        xAxis.push(item.houseName);
        yAxis.push({
          value: item.data,
          itemStyle: {
            color: this.setColor(index),
          },
        });
      });
      this.createdBar({
        id: "rSideBar",
        xAxis,
        yAxis,
      });
    },

    // 设置颜色
    setColor(index) {
      let color = "";
      switch (index) {
        case 0:
          color = "#E7483C";
          break;
        case 1:
          color = "#FF8C13";
          break;
        case 2:
          color = "#FFCC00";
          break;
        default:
          color = "#4FC78F";
          break;
      }
      return color;
    },
    //获取项目数据
    getHouseList() {
      this.$api.api.findHouseByUser({
          orgType: localStorage.getItem("orgType"),
        }).then((res) => {
        this.houseList = res.data;
      });
    },

    //卡片下折线图
    SwitchCARDS(arr, str, timeDate, Strname) {
      let chartDom = document.getElementById(str);
      echarts.init(chartDom).dispose();
      let myChart = echarts.init(chartDom);
      myChart.clear();
      let option = {
        color: [
          "#6F8EDC",
          "#EE6666",
          "#F98120",
          "#1CC99E",
          "#9474FB",
          "#66AFF5",
          "#FABD2B",
          "#FFCF8F",
          "#657292",
          "#7A6A99",
          "#BF5D52",
          "#77B7E4",
          "#E6A065",
          "#9D5139",
          "#C1AA88",
          "#F87F7A",
          "#F6CF74",
          "#7F5506",
          "#88BB9B",
          "#6E99AA",
          "#5789D0",
        ],
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: Strname,
          top: "10",
          icon: "roundRect",
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 18,
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: timeDate[0],
            axisLabel: {
              //重点在这一块，其余可以忽略
              textStyle: {
                color: "#212121", //更改坐标轴文字颜色
              },
            },
            axisLine: {
              lineStyle: {
                type: "solid",
                color: "#DDE1EE", //x线的颜色
                width: "1", //坐标线的宽度
              },
            },
          },
          {
            type: "category",
            data: timeDate[1],
            axisLabel: {
              //重点在这一块，其余可以忽略
              textStyle: {
                color: "#212121", //更改坐标轴文字颜色
              },
            },
            axisLine: {
              lineStyle: {
                type: "solid",
                color: "#DDE1EE", //x线的颜色
                width: "1", //坐标线的宽度
              },
            },
          },
        ],
        yAxis: {
          type: "value",
          splitNumber: 4,
          axisLabel: {
            //重点在这一块，其余可以忽略
            textStyle: {
              color: "#212121", //更改坐标轴文字颜色
            },
          },
          axisLine: {
            lineStyle: {
              ype: "solid",
              color: "#DDE1EE", //x线的颜色
              width: "1", //坐标线的宽度
            },
          },
          splitLine: {
            lineStyle: {
              type: "dashed", // y轴分割线类型
            },
          },
          axisTick: {
            //y轴刻度线
            show: false,
          },
        },
        series: arr,
      };
      option && myChart.setOption(option);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },

    // 柱状图
    createdBar(data) {
      let chartDom = document.getElementById(data.id);
      let myChart = echarts.init(chartDom);
      myChart.clear();

      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: (e) => {
            let obj = e[0];
            return `${obj.name}<br/>${obj.marker}转写时长：${obj.value}`;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        legend: {
          data: data.xAxis,
          top: "10",
          icon: "roundRect",
        },
        xAxis: {
          type: "category",
          data: data.xAxis,
        },
        yAxis: {
          type: "value",
          name: "单位（小时）",
          nameTextStyle: {
            color: "#aaa",
            nameLocation: "start",
          },
        },
        series: {
          data: data.yAxis,
          type: "bar",
        },
      };
      option && myChart.setOption(option);
    },
  },
};
</script>

<style lang="scss" scoped>
.pages {
  .app-top {
    margin: 0 auto;
    width: 98%;
    background: #ffffff;
    box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.04);
    border-radius: 4px;
    padding-top: 15px;
    padding-bottom: 15px;

    .app-titel {
      width: 100%;
      display: flex;
      align-items: center;

      .div-lab {
        padding: 0 0 0 20px;
        display: flex;
        align-items: center;
      }

      .titel-text {
        font-size: 16px;
        color: #32363d;
      }

      .toptimeqhuan {
        width: 190px;
        height: 32px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
        display: flex;
        align-items: center;
        overflow: hidden;
        margin-left: 20px;
        cursor: pointer;
      }

      .toptimeqhuan div {
        flex: 1;
        text-align: center;
        line-height: 32px;
        font-size: 14px;
      }
    }
  }

  .app-box-er {
    margin: 0 auto;
    width: 98%;
    background: #ffffff;
    box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.04);
    border-radius: 4px;
    margin-top: 15px;
    padding: 15px;

    .title {
      display: flex;
      justify-content: space-between;

      .lefts {
        font-weight: bold;
        line-height: 40px;
      }
    }

    .tabcard {
      display: grid;
      grid-template-columns: repeat(6, 16%);
      grid-column-gap: 12px;
      grid-row-gap: 18px;

      /deep/ .el-card__body {
        padding: 8px;
        cursor: pointer;
      }

      .text1 {
        height: 16px;
        font-size: 16px;
        font-weight: 400;
        line-height: 16px;
        text-indent: 20px;
        margin-top: 10px;
        color: #666666;
        display: flex;
        align-items: center;
      }

      .text2 {
        height: 32px;
        font-size: 32px;
        font-weight: normal;
        line-height: 32px;
        text-indent: 20px;
        margin-top: 10px;
      }

      .text3 {
        font-size: 14px;
        margin: 10px 0;
        width: 100%;
        text-indent: 20px;
        display: flex;
        align-items: center;

        .textUp {
          font-size: 14px;
          display: flex;
          font-weight: 600;
          color: rgba(231, 72, 60, 1);
          background: rgba(253, 240, 239, 1);
          align-items: center;
          padding: 3px 12px 3px 0;
          border-radius: 3px;
          margin-left: 8px;

          .up {
            font-size: 14px;
            display: block;
            width: 20px;
            height: 15px;
            background: url("../../../public/img/indexIcon/indexCardUp.png")
              no-repeat;
            background-size: 100%;
            margin-left: 8px;
          }
        }

        .textDown {
          font-size: 14px;
          display: flex;
          font-weight: 600;
          color: rgba(7, 183, 157, 1);
          background: rgba(235, 250, 246, 1);
          align-items: center;
          padding: 3px 12px 3px 0;
          border-radius: 3px;
          margin-left: 8px;

          .down {
            display: block;
            width: 20px;
            height: 15px;
            background: url("../../../public/img/indexIcon/indexCardDown.png")
              no-repeat;
            background-size: 100%;
            margin-left: 8px;
          }
        }
      }

      .tophovese {
        border: 1px solid #2671e2 !important;
        background: rgba(38, 113, 226, 0.04);
        color: #666 !important;
      }
    }

    .tophovese {
      color: #2671e2 !important;
    }
  }

  .barBox {
    margin: 20px auto 0;
    width: 98%;
    height: 500px;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 1%;

    .item {
      display: flex;
      flex-direction: column;
      background: #fff;

      .title {
        padding: 10px 20px;
        display: flex;
        justify-content: space-between;
        align-content: center;
        flex-shrink: 0;
        p {
          font-weight: bold;
        }
      }

      .bar {
        padding: 0 10px;
        flex-grow: 1;
      }
    }
  }

  #main {
    width: 100%;
    height: 380px;
  }
}

.z-title {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

</style>