<template>
  <div :class="{ 'app-container': $store.getters.roles[0] == 'admin' }">
    <el-row class="top-sum" v-loading="topInfo == null" v-if="topInfo">
      <el-col :span="6">
        <el-card shadow="never" class="card-show">
          <p class="p-title">今日消耗</p>
          <p class="p-main">
            {{ topInfo.costTotal ? 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="6">
        <el-card shadow="never" class="card-show">
          <p class="p-title">在投账户数</p>
          <p class="p-main">{{ topInfo.accountNum }}</p>
          <p class="p-main-data" style="visibility: hidden">
            在投账户数:{{ topInfo.accountNum }}
          </p>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="card-show">
          <p class="p-title">客户数</p>
          <p class="p-main">{{ topInfo.customersNum }}</p>
          <p class="p-main-data" style="visibility: hidden">
            客户数:{{ topInfo.customersNum }}
          </p>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="card-show">
          <p class="p-title">自运营消耗</p>
          <p class="p-main">
            {{
              topInfo.selfOperationCostTotal
                ? allMoney(topInfo.selfOperationCostTotal / 10)
                : "-"
            }}
          </p>
          <p class="p-main-data">
            日环比:<i
              :style="topInfo.selfOperationCostTotalRoi > 0 ? 'color:red' : 'color:green'"
              style="margin-right: 10px"
              >{{ topInfo.selfOperationCostTotalRoi + "%" }}
            </i>
            占比:<i :style="topInfo.roi > 0 ? 'color:red' : 'color:green'"
              >{{ topInfo.roi + "%" }}
            </i>
          </p>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never" class="top-sum" v-loading="loading">
      <div slot="header" class="clearfix">
        <span>项目维度数据</span>
        <el-date-picker
          v-model="uploadProjectDate"
          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"
          @change="getProjectData"
        ></el-date-picker>
      </div>
      <el-table v-loading="loading" :data="projectList" max-height="300">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="项目名称" align="center" prop="projectName">
        </el-table-column>
        <el-table-column label="运营" align="center" prop="operatorName">
        </el-table-column>
        <el-table-column label="消耗" align="center" prop="costTotal">
          <template slot-scope="scope">
            {{ scope.row.costTotal ? allMoney(scope.row.costTotal / 10) : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="ROI" align="center" prop="roi">
          <template slot-scope="scope">
            {{ scope.row.roi ? scope.row.roi  : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="ROI昨日对比" align="center" prop="rRoi">
          <template slot-scope="scope">
            {{ scope.row.rRoi ? scope.row.rRoi + "%" : "-" }}
          </template>
        </el-table-column>

        <el-table-column label="与昨日消耗对比" align="center" prop="costTotalRoi">
          <template slot-scope="scope">
            {{ scope.row.costTotalRoi ? scope.row.costTotalRoi + "%" : "-" }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card shadow="never" class="top-sum" v-loading="groupLoading">
      <div slot="header" class="clearfix">
        <span>运营组维度数据</span>
        <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"
          @change="getGroupData"
        ></el-date-picker>
      </div>
      <el-table :data="groupList" max-height="300">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="运营经理" align="center" prop="userName">
        </el-table-column>
        <el-table-column label="项目数" align="center" prop="projectNum">
        </el-table-column>
        <el-table-column label="运营数量" align="center" prop="operateNum">
        </el-table-column>
        <el-table-column label="消耗" align="center" prop="costTotal">
          <template slot-scope="scope">
            {{ scope.row.costTotal ? allMoney(scope.row.costTotal / 10) : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="人均消耗" align="center" prop="perCost">
          <template slot-scope="scope">
            {{ scope.row.perCost ? allMoney(scope.row.perCost / 10) : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="昨日消耗" align="center" prop="yesCostTotal">
          <template slot-scope="scope">
            {{ scope.row.yesCostTotal ? allMoney(scope.row.yesCostTotal / 10) : "-" }}
          </template>
        </el-table-column>

        <el-table-column label="与昨日消耗对比" align="center" prop="roi">
          <template slot-scope="scope">
            {{ scope.row.roi ? scope.row.roi + "%" : "-" }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card shadow="never" class="top-sum" v-loading="operationLoading">
      <div slot="header" class="clearfix">
        <span>运营数据</span>
        <el-date-picker
          v-model="uploadOperationDate"
          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"
          @change="getOperateCostList"
        ></el-date-picker>
      </div>
      <el-table :data="analysis" max-height="300" @row-click="changeEchart">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="运营名称" align="center" prop="userName">
        </el-table-column>
        <el-table-column label="项目数" align="center" prop="projectNum">
        </el-table-column>
        <el-table-column label="账户数" align="center" prop="accountNum">
        </el-table-column>
        <el-table-column label="消耗" align="center" prop="costTotal">
          <template slot-scope="scope">
            {{ scope.row.costTotal ? allMoney(scope.row.costTotal / 10) : "-" }}
          </template>
        </el-table-column>

        <el-table-column label="平均账户消耗" align="center" prop="accountCost">
          <template slot-scope="scope">
            {{ scope.row.accountCost ? allMoney(scope.row.accountCost / 10) : "-" }}
          </template>
        </el-table-column>

        <el-table-column label="与昨日消耗对比" align="center" prop="costTotalRoi">
          <template slot-scope="scope">
            {{ scope.row.costTotalRoi ? scope.row.costTotalRoi + "%" : "-" }}
          </template>
        </el-table-column>
      </el-table>
      <div
        id="echart"
        ref="echart"
        style="height: 400px; width: 100%; margin-top: 50px"
        v-loading="echartsLoading"
      ></div>
    </el-card>
  </div>
</template>

<script>
import {
  // getIndexPromoterRank, //获取达人排行
  // getIndexOrderRank, //获取商品排行
  // getPersonalInfo,
  getOperateHomePageHead,
  getProjectCostList,
  getOperationsGroupCostList,
  getOperateCostList,
  getOperateCostTrendChartList,
} from "@/api/operation/operation.js";
var echarts = require("echarts");
export default {
  name: "sale-html",
  data() {
    return {
      echartsType: "orderAmount",
      // 遮罩层
      loading: false,
      groupLoading: false,
      operationLoading: 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 },
      promoterRankList: [],
      promoterLoading: false,
      promoterTotal: 0,
      dateType: 0,
    };
  },
  filters: {},
  created() {
    this.userId = this.$store.getters.userId;
    // 450127;
    // this.$store.getters.userId;
    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.getInfomation();
    this.getProjectData();
    this.getGroupData();
    this.getOperateCostList();
    // this.getIndexPromoterRank();
    // this.getIndexOrderRank();
  },
  methods: {
    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() {
      getOperateHomePageHead({ userId: this.userId }).then((res) => {
        this.topInfo = res.result;
      });
    },
    getProjectData() {
      if (this.uploadProjectDate && this.uploadProjectDate.length == 2) {
        this.loading = true;
        getProjectCostList(
          this.addDateRange(
            { userId: this.userId },
            this.uploadProjectDate,
            "startDate",
            "endDate"
          )
        ).then((res) => {
          this.projectList = res.result;
          this.loading = false;
        });
      } else {
        this.$message.error("请选择时间");
      }
    },
    getGroupData() {
      if (this.uploadDate && this.uploadDate.length == 2) {
        this.groupLoading = true;
        getOperationsGroupCostList(
          this.addDateRange(
            { userId: this.userId },
            this.uploadDate,
            "startDate",
            "endDate"
          )
        ).then((res) => {
          this.groupList = res.result;
          this.groupLoading = false;
        });
      } else {
        this.$message.error("请选择时间");
      }
    },

    getOperateCostList() {
      if (this.uploadOperationDate && this.uploadOperationDate.length == 2) {
        this.operationLoading = true;
        getOperateCostList(
          this.addDateRange(
            { userId: this.userId },
            this.uploadOperationDate,
            "startDate",
            "endDate"
          )
        ).then((res) => {
          this.operationLoading = false;
          this.analysis = res.result;
        });
        this.getEchartList(this.userId, 0);
      } else {
        this.$message.error("请选择时间");
      }

      // this.initEchart("echart", this.handlerEchartOption(response.data.list));
    },
    getEchartList(userId, type) {
      this.echartsLoading = true;
      getOperateCostTrendChartList(
        this.addDateRange(
          { userId: userId, type: type },
          this.uploadOperationDate,
          "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.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.uploadDate = undefined;
      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) {
      const start = new Date(this.uploadOperationDate[0]);
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
      let y = start.getFullYear();
      let MM = start.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let dd = start.getDate();
      dd = dd < 10 ? "0" + dd : dd;
      let option = {
        tooltip: {
          trigger: "axis",
        },
        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.yesterdayInfo
            ? data.yesterdayInfo.map((item) => {
                return item.time;
              })
            : data.info.map((item) => {
                return item.time;
              }),
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: data.todayInfo ? this.uploadOperationDate[0] : "",
            type: "line",
            smooth: true,
            symbol: "circle",
            data: data.todayInfo
              ? data.todayInfo.map((item) => {
                  return (item.costTotal / 10).toFixed(2);
                })
              : data.info.map((item) => {
                  return (item.costTotal / 10).toFixed(2);
                }),
            lineStyle: {
              color: "#00BFFF",
              width: 2,
            },
            itemStyle: {
              color: "#00BFFF",
              borderWidth: 2,
              borderColor: "#00BFFF",
            },
          },
          {
            name: data.yesterdayInfo ? `${y}-${MM}-${dd}` : "",
            type: "line",
            smooth: true,
            symbol: "circle",
            data: data.yesterdayInfo
              ? data.yesterdayInfo.map((item) => {
                  return (item.costTotal / 10).toFixed(2);
                })
              : [],
            lineStyle: {
              color: "#00FF7F",
              width: 2,
            },
            itemStyle: {
              color: "#00FF7F",
              borderWidth: 2,
              borderColor: "#00FF00",
            },
          },
        ],
      };
      return option;
    },
    toSamplingList(item) {
      localStorage.setItem("samplingType", item);
      this.$router.replace({
        path: "/goodsManagement/samplingList",
      });
    },
    toOrderDetail(item) {
      this.$router.replace({
        path: "/supplyChain/goodsDetails",
        query: {
          id: item.itemId,
          name: item.itemTitle,
          orderStartDate: this.uploadDate[0],
          orderEndDate: this.uploadDate[1],
        },
      });
    },
    toOrderList() {
      this.$router.replace({
        path: "/supplyChain/goods",
      });
    },
    toPersonDetail(item) {
      this.$router.replace({
        path: "/supplyChain/indexDetails",
        query: {
          id: item.promoterId,
          name: item.promoterNickName,
          orderStartDate: this.uploadDate[0],
          orderEndDate: this.uploadDate[1],
        },
      });
    },
    toPersonList() {
      this.$router.replace({
        path: "/supplyChain/index",
      });
    },
    indexMethod(index) {
      return index + 1 + (this.queryParams.pageNum - 1) * 10;
    },
    indexMethodTwo(index) {
      return index + 1 + (this.queryParams.promoterPageNum - 1) * 10;
    },
    getIndexPromoterRank() {
      this.promoterLoading = true;
      var dateType;
      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;
      if (
        this.uploadDate[0] == `${y}-${MM}-${dd}` &&
        this.uploadDate[1] == `${y}-${MM}-${dd}`
      ) {
        dateType = 0;
        this.dateType = 0;
      } else {
        dateType = 1;
        this.dateType = 1;
      }
      getIndexPromoterRank(
        this.addDateRange(
          {
            dateType: dateType,
            pageNum: this.queryParams.promoterPageNum,
            pageSize: 10,
          },
          this.uploadDate,
          "orderStartDate",
          "orderEndDate"
        )
      ).then((response) => {
        this.promoterRankList = response.rows;
        this.promoterTotal = response.total;
        this.promoterLoading = false;
      });
    },
    getIndexOrderRank() {
      this.orderRankLoading = true;
      var dateType;
      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;
      if (
        this.uploadDate[0] == `${y}-${MM}-${dd}` &&
        this.uploadDate[1] == `${y}-${MM}-${dd}`
      ) {
        dateType = 0;
        this.dateType = 0;
      } else {
        dateType = 1;
        this.dateType = 1;
      }
      getIndexOrderRank(
        this.addDateRange(
          {
            dateType: dateType,
            pageNum: this.queryParams.pageNum,
            pageSize: 10,
          },
          this.uploadDate,
          "orderStartDate",
          "orderEndDate"
        )
      ).then((response) => {
        this.orderRankList = response.rows;
        this.orderTotal = response.total;
        this.orderRankLoading = false;
      });
    },
    priceFormat(num, n) {
      n = n || 2;
      let symbol = ",";
      if (num === null) return num;
      if (typeof num !== "number") throw new TypeError("num参数应该是一个number类型");
      if (n < 0) throw new Error("参数n不应该小于0");
      let hasDot = parseInt(num) != num; //这里检测num是否为小数，true表示小数
      let m = n != undefined && n != null ? n : 1;
      num =
        m == 0
          ? num.toFixed(m) + "."
          : hasDot
          ? n
            ? num.toFixed(n)
            : num
          : num.toFixed(m);
      symbol = symbol || ",";
      num = num.toString().replace(/(\d)(?=(\d{3})+\.)/g, function (match, p1, p2) {
        return p1 + symbol;
      });
      if (n == 0 || (!hasDot && !n)) {
        //如果n为0或者传入的num是整数并且没有指定整数的保留位数，则去掉前面操作中的小数位
        num = num.substring(0, num.indexOf("."));
      }
      return num;
    },
  },
};
</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 {
  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>
