<template>
  <div class="app-container">
    <div class="app-content">

      <div class="title" style="display: flex; justify-content: center; align-items: center;">广告转化统计</div>


      <el-form class="search-form" :inline="true" label-width="90px">
        <el-form-item label="统计时间">
          <el-select v-model="queryParams.type" clearable placeholder="请选择日期">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="统计类型">
          <el-select v-model="queryParams.tableType" placeholder="请选择类型">
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="统计维度">
          <el-select v-model="queryParams.staticType" placeholder="请选择维度">
            <el-option
              v-for="item in options3"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择部门" prop="userId">
            <treeselect style="width: 217px" :clearable="false" clearable v-model="deptId" :options="deptOptions" :show-count="true"
                        placeholder="请选择归属部门"/>
        </el-form-item>
        <el-form-item label="选择员工" prop="userId">
          <el-select v-model="queryParams.userId" filterable clearable @change="accountListFun" placeholder="请选择员工">
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推广账户" prop="accountId">
          <el-select v-model="queryParams.accountId" @change="planLoad" filterable clearable placeholder="请选择推广账户">
            <el-option
              v-for="item in accountList"
              :key="item.accountId"
              :label="item.accountName"
              :value="item.accountId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划" prop="pid" v-if="queryParams.accountId" v-loading="pload">
          <el-select v-model="queryParams.pid" @change="unitLoad" filterable clearable placeholder="请选择计划">
            <el-option
              v-for="item in planList"
              :key="item.campaignFeedId"
              :label="item.campaignFeedName"
              :value="item.campaignFeedId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单元" prop="uid" v-if="queryParams.accountId" v-loading="uload">
          <el-select v-model="queryParams.uid" @change="creativeLoad" filterable clearable placeholder="请选择单元">
            <el-option
              v-for="item in unitList"
              :key="item.adgroupFeedId"
              :label="item.adgroupFeedName"
              :value="item.adgroupFeedId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创意" prop="aid" v-if="queryParams.accountId" v-loading="aload">
          <el-select v-model="queryParams.aid" @change="achange" filterable clearable placeholder="请选择创意">
            <el-option
              v-for="item in creativeList"
              :key="item.creativeFeedId"
              :label="item.creativeFeedName"
              :value="item.creativeFeedId">
            </el-option>
          </el-select>
        </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>
    </div>
    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
<!--    <el-button class="export" size="small" @click="handleExport"-->
<!--               style="float: right; margin-bottom: 15px; margin-right: 40px;">导出-->
<!--    </el-button>-->
    <div class="table-box" style="margin: 0 auto;width: 80%">
      <el-table :data="tableList" border style="width: 100%;">
        <el-table-column prop="direction" :label="queryParams.staticType == 1 ? '地区' : queryParams.staticType == 2 ? '性别' : queryParams.staticType == 3 ? '年龄' : ''" />
        <el-table-column prop="name" :label="queryParams.tableType == 1 ? '账户' : queryParams.tableType == 2 ? '计划' : queryParams.tableType == 3 ? '单元' : queryParams.tableType == 3 ? '创意' : ''" />
        <el-table-column prop="nickName" label="员工名称" />
        <el-table-column prop="total" label="加微量" />
        <el-table-column prop="reg" label="注册量（转化率）">
          <template slot-scope="scope">
            {{scope.row.reg}}（{{scope.row.regPri}}%）
          </template>
        </el-table-column>
        <el-table-column prop="finis" label="完课量（转化率）">
          <template slot-scope="scope">
            {{scope.row.finis}}（{{scope.row.finisPri}}%）
          </template>
        </el-table-column>
        <el-table-column prop="order" label="订单转化数（转化率）">
          <template slot-scope="scope">
            {{scope.row.order}}（{{scope.row.orderPri}}%）
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

</template>

<script>
import {listStore} from "@/api/his/storeProduct";
import echarts from 'echarts'
import {orderChartData, storeOrderChart, storeOrderChartStore, storeExport} from "@/api/his/index";
import {conversionStatistics} from "@/api/baidu/statistics";
import {getUserListByDeptId} from "@/api/company/companyUser";
import {listAll, listAllPlan, listAllUnit, listAllCreative} from "@/api/baidu/BdAccount";
import Treeselect from "@riophae/vue-treeselect";
import {treeselect} from "@/api/company/companyDept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: {Treeselect},
  data() {
    return {
      deptOptions: [],
      exportLoading: false,
      deptId: null,
      queryParams: {
        type: null,
        tableType: "1",
        staticType: "1",
        userId: undefined,
        storeId: null,
      },
      accountList: [],
      users: [],
      dateList: [],
      tableList: [],
      storeOPtions: [],
      planList: [],
      unitList: [],
      creativeList: [],
      chart: null,
      pload: false,
      uload: false,
      aload: false,
      dataList: [],
      options: [{
        value: '1',
        label: '今天'
      }, {
        value: '2',
        label: '昨天'
      }, {
        value: '3',
        label: '本周'
      }, {
        value: '4',
        label: '上周'
      }, {
        value: '5',
        label: '本月'
      }
        , {
          value: '6',
          label: '上月'
        },
        {
          value: '7',
          label: '本季度'
        },
        {
          value: '8',
          label: '上季度'
        }
        , {
          value: '9',
          label: '本年'
        }
        , {
          value: '10',
          label: '去年'
        }],
      options2: [{
        value: '1',
        label: '账户'
      }, {
        value: '2',
        label: '计划'
      }, {
        value: '3',
        label: '单元'
      }, {
        value: '4',
        label: '创意'
      }],
      options3: [{
        value: '1',
        label: '地区'
      }, {
        value: '2',
        label: '性别'
      }, {
        value: '3',
        label: '年龄'
      }],
    };
  },
  created() {
    listStore().then(response => {
      this.storeOPtions = response.rows;
    });
  },
  mounted() {
    this.chart = echarts.init(this.$refs.chartContainer, 'macarons');
    this.chart.on('mouseout', this.hideTooltip);
    this.updateChart();
    this.conversionStatistics();
    this.getTreeselect();
    this.accountListFun();
  },
  watch: {
    dataList() {
      this.updateChart();
    },
    'deptId': 'currDeptChange'
  },
  methods: {
    planLoad(){
      this.queryParams.pid = null;
      this.queryParams.uid = null;
      this.queryParams.aid = null;
      this.pload = true;
      this.uload = true;
      this.aload = true;
      let data = {accountId: this.queryParams.accountId};
      listAllPlan(data).then(e => {
        this.planList = e.data;
        this.pload = false;
        this.uload = false;
        this.aload = false;
      })
      this.unitLoad();
    },
    unitLoad(){
      this.queryParams.uid = null;
      this.queryParams.aid = null;
      this.uload = true;
      this.aload = true;
      let data = {accountId: this.queryParams.accountId, campaignFeedId: this.queryParams.pid};
      listAllUnit(data).then(e => {
        this.unitList = e.data;
        this.uload = false;
        this.aload = false;
      })
      this.creativeLoad();
    },
    achange(){
      this.$forceUpdate()
    },
    creativeLoad(){
      this.queryParams.aid = null;
      this.aload = true;
      let data = {accountId: this.queryParams.accountId, adgroupFeedId: this.queryParams.uid};
      listAllCreative(data).then(e => {
        this.creativeList = e.data;
        this.aload = false;
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return storeExport(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
        if (response.data != null && response.data.length > 0) {
          this.dept.deptId = response.data[0].id;
        }
      });
    },
    currDeptChange(val) {
      this.deptId = val;
      this.getUserListByDeptId();
    },
    getUserListByDeptId() {
      this.queryParams.userId = undefined;
      var data = {deptId: this.deptId};
      getUserListByDeptId(data).then(response => {
        this.users = response.data;
      });
    },
    accountListFun() {
      listAll({userId: this.queryParams.userId}).then(e => {
        this.accountList = e.data;
      })
    },
    handleQuery() {
      this.conversionStatistics();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        type: null,
        storeId: null,
      }
      this.conversionStatistics()
    },
    conversionStatistics() {
      conversionStatistics(this.queryParams).then(e => {
        this.dateList = e.dataList;
        this.tableList = e.tableList;
        this.dataList = e.data;
      });
    },


    formatter(params) {
      const item1 = params[0].value;
      const item2 = params[1].value;
      const item3 = params[2].value;
      const item4 = params[3].value;
      return `
              <div>
                <div>日期：${params[0].axisValue}</div>
                <div>加微量：${item1}</div>
                <div>注册量：${item2}（${item2 == 0 || item1 == 0 ? "0" :((item2 / item1) * 100).toFixed(2)}%）</div>
                <div>完课量：${item3}（${item3 == 0 || item2 == 0 ? "0" :((item3 / item2) * 100).toFixed(2)}%）</div>
                <div>订单转化数：${item4}（${item4 == 0 || item2 == 0 ? "0" :((item4 / item2) * 100).toFixed(2)}%）</div>
              </div>
            `;
    },

    updateChart() {
      const option = {
        xAxis: {
          type: 'category',
          data: this.dateList,
        },
        yAxis: {
          type: 'value',
        },
        tooltip: {
          trigger: 'axis',
          formatter: this.formatter,
          axisPointer: {
            type: "line",
            lineStyle: {
              color: "rgba(227, 242, 252, 0.39)",
              width: 40,
              type: "solid",
            },
            z: 0,  //注意要设置层级，不然会在覆盖在柱子前面，设置为0就在柱子后面显示了。
          },
        },
        series: [
          {
            name: '加微量',
            type: 'line',
            barWidth: '40%',
            label: {
              show: true,
              position: 'top',
            },
            data: this.dataList[0],
          },
          {
            name: '注册量',
            type: 'line',
            barWidth: '40%',
            label: {
              show: true,
              position: 'top',
            },
            data: this.dataList[1],
          },
          {
            name: '完课量',
            type: 'line',
            barWidth: '40%',
            label: {
              show: true,
              position: 'top',
            },
            data: this.dataList[2],
          },
          {
            name: '下单量',
            type: 'line',
            barWidth: '40%',
            label: {
              show: true,
              position: 'top',
            },
            data: this.dataList[3],
          },
        ],


      };
      this.chart.setOption(option);
    },

    hideTooltip() {
      this.chart.dispatchAction({
        type: 'hideTip',
      });
    },
  },
};
</script>
<style>
.title {
  padding: 20px 30px 0px 30px;
  font-size: 18px;
  font-weight: bold;
  color: black;

}

.search-form {
  margin: 20px 30px 0px 30px;
}

.echart-box {
  margin: 0 auto;
  text-align: center;
}

.el-select {
  margin: 5px 10px;
}

.table-box {
  margin-top: 15px;

  .export {
    float: right;
    margin: 10px 0px;
  }
}

.app-container {
  border: 1px solid #e6e6e6;
  padding: 12px;


}

.app-content {
  background-color: white;


}

.data-box {
  padding: 30px;
  background-color: rgb(255, 255, 255);
  height: 100%;


}
</style>
