<template>
  <div class="app-container" v-loading="loadingState" text="拼命加载中">
    <el-form :inline="true">
      <el-form-item label="启用分组选择">
        <el-switch v-model="swicthObj.value" @change="changeAppSel">
        </el-switch>
      </el-form-item>

      <el-form-item label="" v-show="swicthObj.value">
        <zx-app-group :value.sync="condition.pkg"></zx-app-group>
      </el-form-item>

      <el-form-item label="App名称" v-show="!swicthObj.value">
        <el-select v-model="condition.pkg" @change="changeLocalPkg" filterable>
          <el-option
            v-for="(item, index) in pkgList"
            :key="index"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="查询日期">
        <el-date-picker
          v-model="queryDate"
          type="daterange"
          align="center"
          unlink-panels
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        />
      </el-form-item>

      <el-form-item label="投放方式">
        <el-select v-model="condition.agentMethod" filterable>
          <el-option
            v-for="(itm, idx) in putInList"
            :key="idx"
            :value="itm.value"
            :label="itm.label"
          />
        </el-select>
      </el-form-item>
      <!-- 查询图表数据queryChartData只在归因页面查询 -->
      <el-button
        type="primary"
        @click="
          putinFetchAttribution_analysis();
          filterMode ? null : queryChartData();
        "
      >
        查询
      </el-button>
    </el-form>

    <!-- 通过filterMode来判别是否是投放归因页面 -->
    <el-tabs v-if="!filterMode" v-model="tabPaneName">
      <el-tab-pane label="归因分析图" name="1">
        <!-- 投放归因折线图 -->
        <zx-charts ref="childCahrts"></zx-charts>
      </el-tab-pane>
      <el-tab-pane label="消耗排名表" name="2">
        <!-- 包排序表格侧面柱状图 -->
        <zx-rank-chart ref="rankCostChart"> </zx-rank-chart>
      </el-tab-pane>
    </el-tabs>

    <!-- 选择筛选模式及其过滤条件,filterMode=false在投放归因页面 -->
    <template v-if="filterMode">
      <el-card shadow="never" body-style="padding:15px">
        <el-row :gutter="10">
          <el-col :span="3" v-for="(itm, idx) of screenList" :key="idx">
            <el-link target="_blank" :type="itm.type" @click="filterType(idx)">
              <b>{{ itm.name }}</b>
            </el-link>
          </el-col>
        </el-row>
      </el-card>

      <div style="margin: 10px 0">
        筛选项：
        <el-tag
          style="margin-left: 5px"
          :key="idx"
          v-for="(tag, idx) in filterCondition"
          effect="plain"
          closable
          @close="delFilterCondition(tag, idx)"
        >
          {{ tag.name + "：" + tag.filterName }}
        </el-tag>
      </div>
    </template>

    <!-- 归因数据展示 -->
    <zx-table
      v-if="curIdx == -1"
      :header="attributionGroupHeader"
      :putList="putList"
      @showFilterMode="showFilterMode"
      @addAttributionCondition="addAttributionCondition"
    />
    <!-- 平台数据展示 -->
    <zx-table
      v-else-if="curIdx == 0"
      :header="platformGroupHeader"
      :putList="putList"
      @addAttributionCondition="addAttributionCondition"
    />
    <!-- 渠道 -->
    <zx-table
      v-else-if="curIdx == 1"
      :header="channelGroupHeader"
      :putList="putList"
      @addAttributionCondition="addAttributionCondition"
    />
    <!-- 广告主 accountGroupHeader -->
    <zx-table
      v-else-if="curIdx == 2"
      :header="accountGroupHeader"
      :putList="putList"
      :statusControlBtn="curIdx"
      :condition="condition"
      @addAttributionCondition="addAttributionCondition"
    />
    <!-- 广告组 adGroupHeader -->
    <zx-table
      v-else-if="curIdx == 3"
      :header="adGroupHeader"
      :putList="putList"
      :statusControlBtn="curIdx"
      @addAttributionCondition="addAttributionCondition"
      @singleAttributionStatusChange="singleAttributionStatusChange"
      @listAttributionStatusChange="listAttributionStatusChange"
    />
    <!-- 广告计划 adPlanGroupHeader -->
    <zx-table
      v-else-if="curIdx == 4"
      :header="adPlanGroupHeader"
      :putList="putList"
      :statusControlBtn="curIdx"
      :condition="condition"
      @addAttributionCondition="addAttributionCondition"
      @singleAttributionStatusChange="singleAttributionStatusChange"
      @listAttributionStatusChange="listAttributionStatusChange"
    />
    <!-- 创意 creativeGroupHeader -->
    <zx-table
      v-else-if="curIdx == 5"
      :header="creativeGroupHeader"
      :putList="putList"
      :statusControlBtn="curIdx"
      @addAttributionCondition="addAttributionCondition"
      @singleAttributionStatusChange="singleAttributionStatusChange"
      @listAttributionStatusChange="listAttributionStatusChange"
    />
    <!-- 分页 -->
    <div style="width: 100%; text-align: center">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="condition.page"
        :page-sizes="[10, 20, 50, 80]"
        :page-size="condition.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal"
      />
    </div>
  </div>
</template>

<script>
import {
  putinFetchAttribution_analysis,
  menuSelectApps,
  attributionStatusChange,
} from "@/api/report";
const moment = require("moment");

import ZxTable from "./components/ZxTableAttribution";
import ZxCharts from "./components/ZxCharts";
import ZxRankChart from "./components/ZxRankChart";
import ZxAppGroup from "./components/ZxAppGroup";

export default {
  name: "DataPlan",
  components: {
    ZxTable,
    ZxCharts,
    ZxRankChart,
    ZxAppGroup,
  },
  data() {
    //9个公用的表格字段
    let publicColumn = [
      {
        prop: "showPv",
        label: "展示",
        align: "center",
        width: "120",
        sortable: "custom",
      },
      {
        prop: "click",
        label: "点击",
        align: "center",
        width: "120",
        sortable: "custom",
      },
      {
        prop: "clickRate",
        label: "点击率",
        align: "center",
        width: "120",
        sortable: "custom",
        tag: "percentSign",
      },
      {
        prop: "cost",
        label: "消耗金额",
        align: "center",
        width: "120",
        sortable: "custom",
      },
      {
        prop: "ecpm",
        label: "eCPM",
        align: "center",
        width: "120",
        sortable: "custom",
      },
      {
        prop: "cpc",
        label: "CPC",
        align: "center",
        width: "120",
        sortable: "custom",
      },
      {
        prop: "convert",
        label: "转化",
        align: "center",
        // width: "100",
        sortable: "custom",
      },
      {
        prop: "convertPrice",
        label: "转化成本",
        align: "center",
        width: "120",
        sortable: "custom",
      },
      {
        prop: "convertRatePercent",
        label: "转化率(%)",
        align: "center",
        width: "120",
        sortable: "custom",
        tag: "percentSign",
      },
    ];
    return {
      swicthObj: {
        value: false, //开关状态
        pkgQueue: [""], //切换开关时候保存pkg状态
      },
      tabPaneName: "1", //选中的tab
      pickerOptions: {}, //表格时间
      loadingState: true, //加载状态
      filterMode: false, //获取包后展示表格
      pkgList: [], //包的类行 包（app）列表
      queryDate: [], //选择的日期
      putList: [], //展示的table数据
      curIdx: -1, //当前索引，控制显示那个表格,-1表示投放归因
      condition: {
        //传递的参数
        pkg: "", //平台选择
        startDate: "", //开始日期
        endDate: "", //截止日期
        pageType: null,
        advertiserId: null,
        agentId: null,
        campaignId: null,
        creativeId: null,
        planId: null,
        platformType: null,
        agentMethod: "", //增加字段，默认为全部“”，1表示代投，2表示自投
        page: 1,
        size: 10,
      },
      pageTotal: 0, //分页数据总条数
      putInList: [
        { label: "全部", value: "" },
        { label: "代投", value: "1" },
        { label: "自投", value: "2" },
      ],
      screenList: [
        //选择的显示数据的模式 对应tab中的6个显示规则
        { name: "平台", type: "primary", pageType: "group_platform" },
        { name: "渠道", type: "default", pageType: "group_agent" },
        { name: "广告主", type: "default", pageType: "group_advertiser" },
        { name: "广告组", type: "default", pageType: "group_campaign" },
        { name: "广告计划", type: "default", pageType: "group_plan" },
        { name: "创意", type: "default", pageType: "group_creative" },
      ],
      filterCondition: [
        //标签数据控制
        // { name: "平台",idx: 0, filterName: "头条", type: "platformType" }, //平台
        // { name: "渠道" }, //渠道
        // { name: "账号" }, //账号
        // { name: "广告组" }, //广告组 计划组
        // { name: "广告计划" } //广告  计划
      ],

      //归因分析 表头
      attributionGroupHeader: [
        {
          prop: "period",
          label: "周期",
          align: "center",
          fixed: "left",
          width: "210",
        },
        {
          prop: "appName",
          label: "应用名称",
          align: "center",
          fixed: "left",
          width: "200",
        },
        {
          prop: "platform",
          label: "客户端",
          align: "center",
          fixed: "left",
          width: "100",
          tag: "mobileTerminal", //终端列显示需要数字转换三个平台 安卓、IOS、H5
        },
        {
          // prop: "",
          label: "操作",
          align: "center",
          width: "150",
          fixed: "left",
          tag: "attributionOperation", //归因操作按钮
        },
      ].concat(publicColumn),
      //平台
      platformGroupHeader: [
        {
          prop: "platformName",
          label: "平台",
          align: "center",
          width: "120",
          tag: "platform", //平台显示
        },
      ].concat(publicColumn),
      //渠道,代理商
      channelGroupHeader: [
        {
          prop: "agentName",
          label: "渠道名称",
          align: "center",
          width: "120",
          tag: "channelName",
        },
      ].concat(publicColumn),
      //广告主
      accountGroupHeader: [
        {
          type: "selection",
          width: "55",
          fixed: "left",
          tag: "selection",
        },
        {
          prop: "advertiserId",
          label: "广告主ID",
          align: "center",
          width: "150",
          fixed: "left",
        },
        {
          prop: "advertiserName",
          label: "广告主",
          align: "center",
          width: "150",
          fixed: "left",
          tag: "account",
          tooltip: true,
        },
        {
          prop: "validBalance",
          label: "账户余额",
          align: "center",
          width: "120",
          tag: "budget",
        },
        {
          prop: "budget",
          label: "预算",
          align: "center",
          width: "120",
          tag: "budget",
        },
      ].concat(publicColumn),
      //广告组
      adGroupHeader: [
        {
          type: "selection",
          width: "55",
          fixed: "left",
          tag: "selection",
        },
        {
          prop: "status",
          label: "状态",
          align: "center",
          width: "150",
          fixed: "left",
          tag: "state",
        },
        {
          prop: "campaignId",
          label: "广告组ID",
          align: "center",
          width: "180",
          fixed: "left",
        },
        {
          prop: "campaignId",
          label: "广告组",
          align: "center",
          width: "180",
          fixed: "left",
          tag: "adGroup",
        },
        {
          prop: "budget",
          label: "预算",
          align: "center",
          width: "120",
          tag: "budget",
        },
      ].concat(publicColumn),
      //广告计划
      adPlanGroupHeader: [
        {
          type: "selection",
          width: "55",
          fixed: "left",
          tag: "selection",
        },
        {
          prop: "optStatus",
          label: "状态",
          align: "center",
          width: "150",
          fixed: "left",
          tag: "state",
        },
        {
          prop: "planId",
          label: "广告计划ID",
          align: "center",
          width: "180",
          fixed: "left",
        },
        {
          prop: "planName",
          label: "广告计划",
          align: "center",
          width: "150",
          fixed: "left",
          tag: "adPlan",
          tooltip: true,
        },
        {
          prop: "budget",
          label: "预算",
          align: "center",
          width: "120",
          tag: "budget",
          sortable: "custom",
        },
        {
          //在广告计划中显示,后期根据需求更改tag，目前与预算保持一致
          prop: "cpaBid",
          label: "出价oCMP",
          align: "center",
          width: "120",
          tag: "budget",
        },
      ].concat(publicColumn),
      //广告素材  创意
      creativeGroupHeader: [
        {
          type: "selection",
          width: "55",
          fixed: "left",
          tag: "selection",
        },
        {
          prop: "optStatus",
          label: "状态",
          align: "center",
          width: "150",
          fixed: "left",
          tag: "state",
        },
        {
          prop: "creativeId",
          label: "广告素材ID",
          align: "center",
          width: "180",
          fixed: "left",
        },
        {
          prop: "creativeId",
          label: "广告素材",
          align: "center",
          width: "180",
          fixed: "left",
        },
      ].concat(publicColumn),
    };
  },
  created() {
    this.queryDate[0] = moment().subtract(0, "days").format("YYYY-MM-DD");
    this.queryDate[1] = moment().format("YYYY-MM-DD");
    // 时间过滤组件加上侧边时间格式设置
    this.pickerOptions = this.$store.state.pickerOptions;

    this.menuSelectApps(); // 获取App名称配置列表
  },

  methods: {
    /**
     * 切换开关时，保存和获取上一个状态的值
     */
    changeAppSel() {
      this.swicthObj.pkgQueue.push(this.condition.pkg); //切换之前将当前值保存
      this.condition.pkg = this.swicthObj.pkgQueue.shift(); //弹出队列第一个值
    },
    /**
     * @method 保存本地app参数
     */
    changeLocalPkg(val) {
      localStorage.setItem("putAttributionPkg", val);
    },
    /**
     * 通知子组件请求数据 只有在投放归因页面才会调用此方法查询图表数据，减少多余请求以提高性能
     * 传递参数
     *    查询日期 queryDate（区分一天还是一天以上）
     *    投放方式 condition.agentMethod
     *    APP名称  condition.pkg
     */
    queryChartData() {
      //ZxCharts获取数据方法调用
      this.$refs.childCahrts.getChartsData(
        this.queryDate,
        this.condition.agentMethod,
        this.condition.pkg
      );
      //ZxRankChart获取数据方法调用
      this.$refs.rankCostChart.getChartsData(
        this.queryDate,
        this.condition.agentMethod,
        this.pkgList
      );
    },

    //修改单个状态
    singleAttributionStatusChange(idx, str, params, rowVal) {
      if (rowVal) {
        this.condition.advertiserId = rowVal.advertiserId;
      }
      if (!this.condition.advertiserId || this.condition.advertiserId === "") {
        this.$message.warning("请先选择广告主！");
        return;
      }
      //添加广告主参数
      params["advertiserId"] = this.condition.advertiserId;
      // console.log(params);
      attributionStatusChange(params)
        .then((res) => {
          // console.log(res);
          if (res.status == 200) {
            this.$message.success("状态更新成功！");
            //更改按钮显示状态
            if (str === "CAMPAIGN_STATUS_ENABLE") {
              this.putList[idx].status =
                params["optStatus"] === "disable" ? "-" : str;
            } else {
              this.putList[idx].optStatus =
                params["optStatus"] === "disable" ? "-" : str;
            }
          } else if (res.status == 500) {
            this.$message.warning(res.msg);
          } else {
            this.$message.error(`更改参数异常，错误代码：${res.status}`);
          }
          this.condition.advertiserId = "";
        })
        .catch((err) => {
          this.$message.error("状态更改请求出错！");
          console.log(err);
        });
    },

    //批量修改状态
    listAttributionStatusChange(selList, sta) {
      // if (!this.condition.advertiserId || this.condition.advertiserId === "") {
      //   this.$message.warning("请先选择广告主！");
      //   return;
      // }
      if (this.condition.advertiserId && this.condition.advertiserId != "") {
        let params = {};
        //添加广告主参数 和 开启或关闭指令参数
        params["advertiserId"] = this.condition.advertiserId;
        params["optStatus"] = sta;
        let id = "",
          idName;
        //批量更改按钮的状态，开启或者关闭 并保存选择的id
        selList.forEach((itm) => {
          if (itm.campaignId) {
            itm.status = sta === "enable" ? "CAMPAIGN_STATUS_ENABLE" : "-";
            id += itm.campaignId + ",";
            idName = "campaignId";
          } else if (itm.planId) {
            itm.optStatus = sta === "enable" ? "AD_STATUS_ENABLE" : "-";
            id += itm.planId + ",";
            idName = "planId";
          } else if (itm.creativeId) {
            itm.optStatus = sta === "enable" ? "CREATIVE_STATUS_ENABLE" : "-";
            id += itm.creativeId + ",";
            idName = "creativeId";
          }
        });
        id = id.substr(0, id.length - 1);
        //添加三个条件的其中一个
        params[idName] = id;
        // console.log(params);
        attributionStatusChange(params)
          .then((res) => {
            // console.log(res);
            if (res.status == 200) {
              this.$message.success("状态批量更新成功！");
            } else if (res.status == 500) {
              this.$message.warning(res.msg);
            } else {
              this.$message.error(`更改参数异常，错误代码：${res.status}`);
            }
          })
          .catch((err) => {
            this.$message.error("状态更改请求出错！");
            console.log(err);
          });
      } else {
        let num = 0;
        selList.map((item) => {
          let params = {
            advertiserId: item.advertiserId,
            optStatus: sta,
            campaignId: item.campaignId,
          };
          attributionStatusChange(params)
            .then((res) => {
              // console.log(res);
              if (res.status == 200) {
                this.$message.success("状态批量更新成功！");
              } else if (res.status == 500) {
                this.$message.warning(res.msg);
              } else {
                this.$message.error(`更改参数异常，错误代码：${res.status}`);
              }
              num++;
              if (num == selList.length) {
                this.putinFetchAttribution_analysis();
              }
            })
            .catch((err) => {
              this.$message.error("状态更改请求出错！");
              console.log(err);
              num++;
              if (num == selList.length) {
                this.putinFetchAttribution_analysis();
              }
            });
        });
      }
    },

    // 获取App名称配置列表
    menuSelectApps: function () {
      menuSelectApps({
        platformId: 4,
        menuCode: "putin.apps",
      }).then((res) => {
        this.pkgList = res.result.data;
        this.pkgList.unshift({ label: "全部", value: "" });
        let pkgHistory = localStorage.getItem("putAttributionPkg");
        this.condition.pkg = pkgHistory ? pkgHistory : ""; //获取上次搜索参数,如果没有默认为空
        this.putinFetchAttribution_analysis("group_pkg"); // 投放归因
        this.queryChartData(); //初始化表格
      });
    },

    // 投放归因  参数表示不同类型页面的请求
    putinFetchAttribution_analysis: function (pageType) {
      this.loadingState = true;
      this.condition.startDate = this.queryDate[0];
      this.condition.endDate = this.queryDate[1];
      if (pageType) {
        this.condition.pageType = pageType;
      }
      this.putList = [];
      putinFetchAttribution_analysis({
        ...this.condition,
      })
        .then((res) => {
          if (res.status === 200) {
            this.pageTotal = res.result.data.total; //当前的总条数
            this.putList = res.result.data.content;
            //当只有两条数据时，将汇总排在前面
            if (this.putList && this.putList.length == 2) {
              if (JSON.stringify(this.putList[0]).search("#ALL#") == -1) {
                this.putList.reverse();
              }
            }
          }
          this.loadingState = false;
        })
        .catch((err) => {
          this.loadingState = false;
          this.$message.error(`请求错误: ${err}`);
          console.log(err);
        });
    },

    /**
     * 添加归因汇总条件及其参数
     * 参数：
     *  filter-(...) 过滤条件如代理商、平台。。。过滤对应的参数名字
     *  filterConditionData-(filter) 第一个参数名绑定对应的参数值
     *  summary-(pageType)   对应汇总的参数
     *
     * filterName(标签字段所需)，添加标签字段有重复修改
     */
    addAttributionCondition: function (
      filter,
      filterConditionData,
      summary,
      filterName
    ) {
      this.condition[filter] = filterConditionData;
      //修改titileBar显示
      let idx = 0;
      for (let i = 0; i < this.screenList.length; i++) {
        this.screenList[i].type = "default";
        if (this.screenList[i].pageType == summary) idx = i;
      }
      this.screenList[idx].type = "primary";
      this.curIdx = idx;

      //提交的条件参数修改，及其标签添加
      if (filterName !== undefined) {
        let flag = true;
        for (let i = 0; i < this.filterCondition.length; i++) {
          if (filter === this.filterCondition[i].type) {
            this.filterCondition[i].filterName = filterName;
            flag = false;
            break;
          }
        }
        if (flag) {
          let addName = (name, idx) => {
            this.filterCondition.push({
              name: name,
              idx: idx,
              filterName: filterName,
              type: filter,
            });
          };
          if (filter === "platformType") {
            addName("平台", 0);
          } else if (filter === "agentId") {
            addName("渠道", 1);
          } else if (filter === "advertiserId") {
            addName("广告主", 2);
          } else if (filter === "campaignId") {
            addName("广告组", 3);
          } else if (filter === "planId") {
            addName("广告计划", 4);
          }
        }
      }
      //步骤跳转时更新当前所在页
      this.condition.page = 1;
      this.putinFetchAttribution_analysis(summary);
    },

    //根据选择的过滤条件，获取数据
    filterType: function (idx) {
      this.curIdx = idx;
      for (let i = 0; i < this.screenList.length; i++) {
        this.screenList[i].type = "default";
      }
      this.screenList[idx].type = "primary";

      //层级删除标签
      this.filterCondition = this.filterCondition.filter((itm) => {
        if (itm.idx >= idx) {
          this.condition[itm.type] = "";
          return false;
        }
        return true;
      });
      //切换时，更新到第一页
      this.condition.page = 1;
      //选择页面时更改请求方式,并刷新数据集
      this.putinFetchAttribution_analysis(this.screenList[idx].pageType);
    },

    //展示过滤条件和展示模式选择框, 以及设置显示的table
    showFilterMode: function () {
      this.curIdx = 0; //表示点击后到平台
      this.filterMode = true; //展示过滤
    },

    //删除过滤条件，同时将该传递参数置为空
    delFilterCondition: function (tag, idx) {
      // console.log(tag, idx);
      this.filterCondition.splice(idx, 1);
      this.condition[tag.type] = "";
      this.condition.page = 1;
      this.putinFetchAttribution_analysis();
    },

    //下面两个是分页栏信息修改，修改后重新拉取数据
    //每页显示个数的修改
    handleSizeChange(val) {
      this.condition.size = val;
      this.putinFetchAttribution_analysis();
    },

    //当前页修改
    handleCurrentChange(val) {
      this.condition.page = val;
      this.putinFetchAttribution_analysis();
    },
  },
};
</script>

<style scoped></style>
