<template>
  <div :class="{ 'app-container': $store.getters.roles[0] == 'admin' }">
    <el-row class="top-sum-search">
      <el-card shadow="never" class="card-show">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          label-width="100px"
        >
          <el-form-item label="项目名称" prop="accountId">
            <selectTree
              style="width: 240px"
              v-model="queryParams.accountId"
              filterable
              :multiple="true"
              :data="projectList"
              :props="{
                value: 'projectId',
                label: 'projectName',
                children: 'accountList',
              }"
              nodeKey="projectId"
              :lazy="false"
            />
          </el-form-item>
          <el-form-item label="时间" prop="userId">
            <el-date-picker
              v-model="uploadDate"
              style="width: 240px; float: right; padding: 3px 0"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>
    <el-row class="top-sum" v-loading="topInfo == null" v-if="topInfo">
      <el-col :span="4">
        <el-card shadow="never" class="card-show">
          <p class="p-title">总消耗</p>
          <p class="p-main">{{ allMoney(topInfo.costTotal / 10) }}</p>
          <p class="p-main-data">
            环比:<i :style="topInfo.costTotalRoi > 0 ? 'color:red' : 'color:green'"
              >{{ topInfo.costTotalRoi + "%" }}
            </i>
          </p>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="never" class="card-show">
          <p class="p-title">当日累计GMV</p>
          <p class="p-main">{{ allMoney(topInfo.t0Gmv / 10) }}</p>
          <p class="p-main-data">
            环比:<i :style="topInfo.t0GmvRoi > 0 ? 'color:red' : 'color:green'"
              >{{ topInfo.t0GmvRoi + "%" }}
            </i>
          </p>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="never" class="card-show">
          <p class="p-title">当日累计ROI</p>
          <p class="p-main">{{ topInfo.t0Roi }}</p>
          <p class="p-main-data">
            环比:<i :style="topInfo.t0RoiRoi > 0 ? 'color:red' : 'color:green'"
              >{{ topInfo.t0RoiRoi + "%" }}
            </i>
          </p>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="never" class="card-show">
          <p class="p-title">场观成本</p>
          <p class="p-main">{{ allMoney(topInfo.viewCost / 10) }}</p>
          <p class="p-main-data">
            环比:<i
              :style="topInfo.viewCostRoi > 0 ? 'color:red' : 'color:green'"
              style="margin-right: 10px"
              >{{ topInfo.viewCostRoi + "%" }}
            </i>
          </p>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="never" class="card-show">
          <p class="p-title">涨粉数</p>
          <p class="p-main">{{ topInfo.upFans }}</p>
          <p class="p-main-data">
            环比:<i
              :style="topInfo.upFansRoi > 0 ? 'color:red' : 'color:green'"
              style="margin-right: 10px"
              >{{ topInfo.upFansRoi + "%" }}
            </i>
          </p>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="never" class="card-show">
          <p class="p-title">当日累计订单成本</p>
          <p class="p-main">{{ allMoney(topInfo.orderCost / 10) }}</p>
          <p class="p-main-data">
            环比:<i
              :style="topInfo.orderCostRoi > 0 ? 'color:red' : 'color:green'"
              style="margin-right: 10px"
              >{{ topInfo.orderCostRoi + "%" }}
            </i>
          </p>
        </el-card>
      </el-col>
    </el-row>
    <el-card shadow="never" class="top-sum">
      <div slot="header" class="clearfix">
        <span>访问量统计</span>
      </div>

      <div
        id="echart"
        ref="echart"
        style="height: 400px; width: 100%; margin-top: 50px"
        v-loading="echartsLoading"
      ></div>
    </el-card>
    <el-card shadow="never" class="top-sum" v-loading="groupLoading">
      <div slot="header" class="clearfix">
        <span>数据报表</span>
        <div style="float: right; padding: 3px 0">
          <el-button type="primary" size="mini" @click="showAllCounms"
            >自定义列</el-button
          >
          <el-button :loading="exportLoading" size="mini" @click="exportExcel"
            >导出</el-button
          >
        </div>
      </div>
      <el-table :data="groupList">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="时间" align="center" prop="time" width="150px">
        </el-table-column>

        <el-table-column
          :label="item.name"
          align="center"
          :prop="item.code"
          v-for="(item, index) in showAllFields"
          :key="index"
          :width="showAllFields.length > 9 ? '150px' : 'auto'"
        >
          <template slot-scope="scope">
            <span
              v-if="
                item.name.indexOf('花费') != -1 ||
                item.name.indexOf('成本') != -1 ||
                item.name.indexOf('GMV') != -1
              "
            >
              {{ scope.row[item.code] ? allMoney(scope.row[item.code] / 10) : "-" }}
            </span>
            <span v-else> {{ scope.row[item.code] ? scope.row[item.code] : "-" }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getGroupData"
      />
    </el-card>
    <!-- 自定义列 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-checkbox-group v-model="ids">
        <el-checkbox
          v-for="city in reportFieldsList"
          :label="city.code + '@' + city.name"
          :key="city.code"
          style="width: 30%"
          >{{ city.name }}</el-checkbox
        >
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getProjectAndAccountByUserId,
  getStatisticalReportHead,
  getvisitorStatisticsTrendChartList,
  nodeAccountCost,
  getAccountDataReport,
  getReportFields,
  addKuaishouFields,
  getKuaishouFieldsByUserId,
} from "@/api/operation/operation.js";
import { downFilePost } from "@/api/supplyChain/supplyChain";
import selectTree from "../goodsManagement/selectTree";
var echarts = require("echarts");
export default {
  name: "Statistics",
  data() {
    return {
      echartsType: "orderAmount",
      // 遮罩层
      loading: false,
      groupLoading: false,
      operationLoading: false,
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 分配销售
      openAllocation: false,
      // 选择的销售id
      saleId: undefined,
      // 销售列表
      saleList: [],
      // 分配销售确定loading
      confirmLoadingSale: false,
      // 汇总数据获取
      taskNumber: {
        complete: 0,
        noStarted: 0,
      },
      userId: undefined,
      // 日期范围
      dateRange: [],
      uploadDate: [new Date(), new Date()],
      uploadProjectDate: [new Date(), new Date()],
      uploadOperationDate: [new Date(), new Date()],
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 销售线索回显
      formDataShow: null,
      // 表单参数
      form: {},
      //上传报表下拉数据
      formList: {},
      fileList: [],
      //获取销售线索文件流
      dateFile: null,
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {},
      // 分配销售展示列表
      saleAllocationList: [],
      topInfo: null,
      projectList: [],
      groupList: [],
      analysis: [],
      type: 1,
      echartsLoading: false,
      orderRankList: [],
      orderRankLoading: false,
      orderTotal: 0,
      queryParams: { pageNum: 1, pageSize: 10, promoterPageNum: 1, accountId: undefined },
      promoterRankList: [],
      promoterLoading: false,
      promoterTotal: 0,
      dateType: 0,
      reportFieldsList: [],
      fiexEdFields: [
        {
          code: "time",
          name: "时间",
        },
      ],

      showAllFields: [
        {
          code: "costTotal",
          name: "花费",
        },
        {
          code: "adShow",
          name: "曝光数",
        },
        {
          code: "actionbarClick",
          name: "行为数",
        },
        {
          code: "conversionNum",
          name: "转化数",
        },
        {
          code: "click",
          name: "素材曝光数",
        },
      ],
    };
  },
  components: {
    selectTree,
  },
  filters: {},
  created() {
    this.userId = this.$store.getters.userId;
    // 450127;
    // this.$store.getters.userId;
    this.getColumn();
    let date = new Date();
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? "0" + MM : MM;
    let dd = date.getDate();
    dd = dd < 10 ? "0" + dd : dd;
    this.uploadDate = [`${y}-${MM}-${dd}`, `${y}-${MM}-${dd}`];
    this.uploadProjectDate = [`${y}-${MM}-${dd}`, `${y}-${MM}-${dd}`];
    this.uploadOperationDate = [`${y}-${MM}-${dd}`, `${y}-${MM}-${dd}`];
    this.getProjectAndAccountByUserId();
    this.handleQuery();
  },
  methods: {
    getProjectAndAccountByUserId() {
      getProjectAndAccountByUserId({ userId: this.userId }).then((res) => {
        this.projectList = res.result.map((item) => {
          return {
            ...item,
            accountList: item.accountList.map((v) => {
              return {
                ...v,
                projectId: v.accountId,
                projectName: v.accountName,
              };
            }),
          };
        });
      });
    },
    getTimeState() {
      // 获取当前时间
      let timeNow = new Date();
      // 获取当前小时
      let hours = timeNow.getHours();
      // 设置默认文字
      let text = ``;
      // 判断当前时间段
      if (hours >= 0 && hours <= 5) {
        text = `凌晨好`;
      } else if (hours >= 6 && hours <= 9) {
        text = `早上好`;
      } else if (hours > 9 && hours <= 12) {
        text = `上午好`;
      } else if (hours > 12 && hours <= 14) {
        text = `中午好`;
      } else if (hours > 14 && hours <= 18) {
        text = `下午好`;
      } else if (hours > 18 && hours <= 24) {
        text = `晚上好`;
      }
      // 返回当前时间段对应的状态
      return text;
    },
    getInfomation() {
      getStatisticalReportHead(
        this.addDateRange(
          {
            userId: this.userId,
            accountIdList: this.queryParams.accountId
              ? this.queryParams.accountId.split(",")
              : [],
          },
          this.uploadDate,
          "startDate",
          "endDate"
        )
      ).then((res) => {
        this.topInfo = res.result;
      });
    },
    getGroupData() {
      if (this.uploadDate && this.uploadDate.length == 2) {
        this.groupLoading = true;
        getAccountDataReport(
          this.addDateRange(
            {
              pageNum: this.queryParams.pageNum,
              pageSize: this.queryParams.pageSize,
              userId: this.userId,
              accountIdList: this.queryParams.accountId
                ? JSON.stringify(this.queryParams.accountId.split(","))
                : "[]",
            },
            this.uploadDate,
            "startDate",
            "endDate"
          )
        ).then((res) => {
          this.groupList = res.rows;
          this.total = res.total;
          this.groupLoading = false;
        });
      } else {
        this.$message.error("请选择时间");
      }
    },
    getEchartList(userId, type) {
      this.echartsLoading = true;
      getvisitorStatisticsTrendChartList(
        this.addDateRange(
          {
            userId: this.userId,
            accountIdList: this.queryParams.accountId
              ? this.queryParams.accountId.split(",")
              : [],
          },
          this.uploadDate,
          "startDate",
          "endDate"
        )
      ).then((res) => {
        this.echartsLoading = false;
        this.initEchart("echart", this.handlerEchartOption(res.result));
      });
    },
    changeEchart(item) {
      if (item.userName == "汇总") {
        this.getEchartList(this.userId, 0);
      } else {
        this.getEchartList(item.userId, 1);
      }
    },
    /** 更多操作 */
    handleEdit(item, id) {},

    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      getSaleClueTaskList({ ...this.queryParams, userId: this.userId }).then(
        (response) => {
          console.log(response.data.rows);
          this.typeList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.confirmLoading = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.dateFile = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getInfomation();
      this.getEchartList();
      this.getGroupData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      let date = new Date();
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let dd = date.getDate();
      dd = dd < 10 ? "0" + dd : dd;
      this.uploadDate = [`${y}-${MM}-${dd}`, `${y}-${MM}-${dd}`];
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "上传报表";
    },

    changeEchartsType(e) {
      // if (!!e) {
      //   // this.getDataAnalysis();
      //   this.initEchart("echart", this.handlerEchartOption(this.analysis.list));
      // } else {
      //   this.$message({
      //     message: "请选择类型",
      //     type: "error",
      //   });
      // }
    },
    /** 获取echart的值 */
    initEchart(idName, optionName) {
      let that = this;
      const chart = this.$refs[idName];
      if (chart) {
        const myChart = echarts.init(document.getElementById(idName));
        myChart.setOption(optionName);
        window.addEventListener("resize", function () {
          that.clientWidth = document.documentElement.clientWidth - 224;
          myChart.resize();
        });
      }
    } /** echarts数据展示 订单统计*/,
    handlerEchartOption(data) {
      var that = this;
      let option = {
        tooltip: {
          trigger: "axis",
          triggerOn: "click",
          confine: true,
          appendToBody: true,
          formatter: function (params, ticket, callback) {
            console.log(params);
            var data = params[0].name.split("-").length > 1 ? true : false;
            var paramsData = {
              //   userId: that.userId,
              accountIdList: that.queryParams.accountId
                ? that.queryParams.accountId.split(",")
                : [],
            };
            if (data) {
              paramsData.date = params[0].name;
            } else {
              paramsData.date = that.uploadDate[0];
              paramsData.hour = params[0].name;
            }

            nodeAccountCost(paramsData).then((res) => {
              var dataShowAll = "";
              if (res.result.length > 0) {
                for (let i = 0; i < res.result.length; i++) {
                  dataShowAll +=
                     res.result[i].accountId +
                    "  :" + that.allMoney(res.result[i].costTotal / 10)
                    + "  环比:" +  res.result[i].roi +
                  "<br/>";
                }
                callback(ticket, dataShowAll);
              } else {
                dataShowAll = "无账户数据";
                callback(ticket, dataShowAll);
              }
            });
            return `正在请求数据`;
          },
        },
        title: {
          x: "center",
          y: "center",

          show: true,
          textStyle: {
            rich: {
              a: {
                height: 200,
                width: 280,
              },
            },
          },
        },
        legend: {
          // data: data.yesterdayInfo ? ["今天", "昨天"] : "",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        // toolbox: {
        //     feature: {
        //         saveAsImage: {}
        //     }
        // },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: data.map((item) => {
            return item.time;
          }),
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: this.uploadDate[0] + "~" + this.uploadDate[1],
            type: "line",
            smooth: true,
            symbol: "circle",
            data: data.map((item) => {
              return item.costTotal/10;
            }),
            lineStyle: {
              color: "#00BFFF",
              width: 2,
            },
            itemStyle: {
              color: "#00BFFF",
              borderWidth: 2,
              borderColor: "#00BFFF",
            },
          },
        ],
      };
      return option;
    },
    showAllCounms() {
      this.open = true;
      this.title = "自定义列";
      getReportFields().then((res) => {
        this.reportFieldsList = res.result;
        this.$nextTick(() => {
          this.ids = this.showAllFields.map((item) => {
            return item.code + "@" + item.name;
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.showAllFields = this.ids.map((item) => {
        return {
          code: item.split("@")[0],
          name: item.split("@")[1],
        };
      });
      addKuaishouFields({
        userId: this.userId,
        json: JSON.stringify(this.showAllFields),
        columnType: 1,
      }).then((res) => {
        this.open = false;
      });
    },
    getColumn() {
      getKuaishouFieldsByUserId({
        userId: this.userId,
        columnType: 1,
      }).then((res) => {
        if (res.result) {
          this.showAllFields = JSON.parse(res.result.json);
        }
      });
    },
    cancel() {
      this.open = false;
      this.ids = [];
    },
    exportExcel() {
      this.exportLoading = true;
      downFilePost(
        "/report/account/exportAccountDataReport",
        this.addDateRange(
          {
            userId: this.userId,
            accountIdList: this.queryParams.accountId
              ? this.queryParams.accountId.split(",")
              : [],
            columns: this.showAllFields.map((item) => {
              return item.code;
            }),
          },
          this.uploadDate,
          "startDate",
          "endDate"
        )
      ).then((res) => {
        let blob = new Blob([res], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        let downloadElement = document.createElement("a");
        let href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = "数据报表.xlsx"; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
        this.exportLoading = false;
      });
    },
  },
};
</script>

<style scoped lang="scss">
.top-class {
  text-align: left;
  font-family: cursive;
  font-size: 28px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  .top-left {
    flex: 1;
  }
  .top-right {
    flex: 1;
    display: flex;
    justify-content: end;
    font-size: 16px;
    font-family: none;
  }
}
.p-main-data {
  margin: 0;
  font-size: 14px;
}
.flex-class {
  display: flex;
  justify-content: space-between;
}
.top-sum-search {
  margin-bottom: 15px;
  ::v-deep .el-card__body {
    padding: 10px 0;
  }
}
.top-sum {
  margin-bottom: 15px;
  ::v-deep .card-show {
    text-align: center;
    .p-title {
      width: 100%;
      font-size: 10px;
      color: darkgray;
      font-weight: bold;
    }
    .p-main {
      width: 100%;
      font-size: 20px;
      font-weight: bold;
    }
    .like-a {
      color: cornflowerblue;
      cursor: pointer;
    }
  }
}
::v-deep .el-form-item__label {
  white-space: nowrap;
}
</style>
