<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.reportType" 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="选择部门" 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.id" @change="planLoad" filterable clearable placeholder="请选择推广账户">
            <el-option
              v-for="item in accountList"
              :key="item.id"
              :label="item.accountName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-date-picker
            v-model="queryParams.time"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </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>
    </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">
      <el-table :data="dataList" border style="width: 100%" height="550">
        <el-table-column label="地区" v-if="queryParams.reportType == 2324048">
          <template slot-scope="scope">
            {{scope.row.prov.provinceName}} - {{scope.row.city.cityName}}
          </template>
        </el-table-column>
        <el-table-column label="性别" v-if="queryParams.reportType == 2503330">
          <template slot-scope="scope">
            {{scope.row.genderName}}
          </template>
        </el-table-column>
        <el-table-column label="年龄" v-if="queryParams.reportType == 2510393">
          <template slot-scope="scope">
            {{scope.row.ageName}}
          </template>
        </el-table-column>
        <el-table-column label="意向词" v-if="queryParams.reportType == 2532512">
          <template slot-scope="scope">
            {{scope.row.showWord}} - {{scope.row.feedWord}}
          </template>
        </el-table-column>
        <el-table-column prop="date" label="日期" />
        <el-table-column prop="campaignName" label="计划名称" />
        <el-table-column prop="adGroupName" label="推广单元" />
        <el-table-column prop="impression" label="展现" />
        <el-table-column prop="click" label="点击" />
        <el-table-column prop="cost" label="消费" />
        <el-table-column prop="ctr" label="点击率">
          <template slot-scope="scope">
            {{scope.row.ctr}}%
          </template>
        </el-table-column>
        <el-table-column prop="cpc" label="平均点击价格" />
        <el-table-column prop="cpm" label="千次展现消费" />
      </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 {getReportData} from "@/api/baidu/statistics";
import {getUserListByDeptId} from "@/api/company/companyUser";
import {listAll} 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: {
        id: null,
        reportType: 2324048,
        startDate: null,
        endDate: null,
        time: '',
      },
      accountList: [],
      users: [],
      dateList: [],
      tableList: [],
      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: 2324048,
        label: '地域'
      }, {
        value: 2503330,
        label: '性别'
      }, {
        value: 2510393,
        label: '年龄'
      }, {
        value: 2532512,
        label: '意图词'
      }],
    };
  },
  created() {
  },
  mounted() {
    // this.chart = echarts.init(this.$refs.chartContainer, 'macarons');
    // this.chart.on('mouseout', this.hideTooltip);
    // this.updateChart();
    this.getReportData();
    this.getTreeselect();
    this.accountListFun();
  },
  watch: {
    // dataList() {
    //   this.updateChart();
    // },
    'deptId': 'currDeptChange'
  },
  methods: {
    planLoad(){
    },
    /** 导出按钮操作 */
    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.getReportData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        type: null,
        storeId: null,
      }
      this.getReportData()
    },
    getReportData() {
      if(!this.queryParams.id){
        return;
      }
      if(!this.queryParams.time || this.queryParams.time.length < 2){
        return;
      }
      this.queryParams.startDate = this.queryParams.time[0];
      this.queryParams.endDate = this.queryParams.time[1];
      getReportData(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>
