<template>
  <div class="wrap home">
    <!-- 站点选择和时间筛选 -->
    <a-row class="r1" :gutter="8">
      <a-col :xl="7" :xxl="6" v-if="siteList.length > 1">
        <div class="choose-site">
          <span class="t1">站点：</span>
          <select-site @com-methods="changeSite" />
          <!--          <a-select v-model="queryParam.siteId"-->
          <!--                    show-search-->
          <!--                    :filter-option="filterOption"-->
          <!--                    placeholder="全部站点"-->
          <!--                    style="width: 70%"-->
          <!--                    @change="reloadData">-->
          <!--            <a-select-option v-for="data in siteList" :key="data.id" :value="data.id">-->
          <!--              {{ data.name }}-->
          <!--            </a-select-option>-->
          <!--          </a-select>-->
        </div>
      </a-col>
      <a-col :xl="8" :xxl="6">
        <div class="choose-site">
          <span class="t1">统计时间：</span>
          <a-range-picker @change="onChangeDatePciker" :disabledDate="disabledDate" :value="rangeDate" style="width: 70%" />
        </div>
      </a-col>
      <a-col :xl="9" :xxl="12">
        <a-button :class="queryParam.dateType == '' ? 'active' : ''" @click="setTime('')">全部时间</a-button>
        <a-button :class="queryParam.dateType == 'thirtyDay' ? 'active' : ''" @click="setTime('thirtyDay')">近30天</a-button>
        <a-button :class="queryParam.dateType == 'sevenDay' ? 'active' : ''" @click="setTime('sevenDay')">近一周</a-button>
        <a-button :class="queryParam.dateType == 'yesterday' ? 'active' : ''" @click="setTime('yesterday')">昨日</a-button>
        <a-button :class="queryParam.dateType == 'today' ? 'active' : ''" @click="setTime('today')">今日</a-button>
      </a-col>
    </a-row>

    <!-- 占位 -->
    <div style="height: 20px"></div>

    <a-spin :spinning="loading" tips="加载中...">
      <a-row class="r5" :gutter="[20, 20]">
        <a-row class="r5-1">
          <a-col :span="24">
            <div class="fr" v-if="coreDataChart.x.length > 0">
              <span><i style="background: #544beb"></i>UV</span>
              <span><i style="background: #f0b358"></i>PV</span>
              <span><i style="background: #58cca8"></i>询盘数</span>
            </div>
            <area-chart v-if="coreDataChart.x.length > 0" :dataSource="coreDataChart" />
            <a-empty v-else style="float: right; width: 100%; margin-top: 110px" />
          </a-col>
        </a-row>
        <a-row style="margin: 20px">
          <a-table :columns="dailyDataColumns" :data-source="dailyDataSource" size="middle" rowKey="type" :pagination="false">
            <template #newUserProportionSlot="text, record">
              <template v-if="record.newUvNum === 0"> 0.00 % </template>
              <template v-else>
                {{ ((record.newUvNum * 100) / record.uvNum).toFixed(2) + ' %' }}
              </template>
            </template>
            <template #conversionSlot="text, record">
              <span style="margin-left: 20px"></span>
              <template v-if="record.enquiryNum === 0 || record.uvNum === 0"> 0.00 % </template>
              <template v-else>
                {{ ((record.enquiryNum * 100) / record.uvNum).toFixed(2) + ' %' }}
              </template>
            </template>
            <template #centerSlot="text, record, index">
              <span style="margin-left: 20px">{{ text }}</span>
            </template>
            <template #enquiryNumSlot="text, record, index">
              <router-link v-if="text > 0" :to="{ path: '/inquiry/list', query: { start: record.time, end: record.time } }">
                <span style="margin-left: 20px; color: blue">{{ text }}</span>
              </router-link>
              <span v-else style="margin-left: 20px">{{ text }}</span>
            </template>
          </a-table>
        </a-row>
      </a-row>
    </a-spin>
  </div>
</template>

<script>
  import '/@/assets/less/common.less';
  import { getAction } from '/@/api/manage/manage';
  import { JeecgListMixin } from '/@/hooks/component/JeecgListMixin';
  import moment from 'moment';
  import areaChart from './chart/areaChart.vue';
  import selectSite from '/@/components/adweb/selectSite.vue';

  export default {
    name: 'DailyData',
    components: {
      areaChart,
      selectSite,
    },
    mixins: [JeecgListMixin],
    data() {
      return {
        // 通用
        ipagination: {
          current: 1,
          pageSize: 30,
          pageSizeOptions: ['15', '30', '45', '60'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条';
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        disableMixinCreated: true,
        loading: true,
        // 筛选
        siteList: [],
        rangeDate: undefined,
        // 数据趋势的数据
        coreDataChart: {
          x: [],
          uv: [],
          pv: [],
          enquiry: [],
        },
        // 来源媒介列表
        dailyDataColumns: [
          {
            title: '统计时间',
            dataIndex: 'time',
          },
          {
            title: '访客（UV）',
            dataIndex: 'uvNum',
            scopedSlots: {
              customRender: 'centerSlot',
            },
          },
          {
            title: '新访客',
            dataIndex: 'newUvNum',
            scopedSlots: {
              customRender: 'centerSlot',
            },
          },
          {
            title: '新访客占比',
            scopedSlots: {
              customRender: 'newUserProportionSlot',
            },
          },
          {
            title: '浏览量（PV）',
            dataIndex: 'pvNum',
            scopedSlots: {
              customRender: 'centerSlot',
            },
          },
          {
            title: '询盘数',
            dataIndex: 'enquiryNum',
            scopedSlots: {
              customRender: 'enquiryNumSlot',
            },
          },
          {
            title: 'UV到询盘转化率',
            scopedSlots: {
              customRender: 'conversionSlot',
            },
          },
        ],
        dailyDataSource: [],
      };
    },
    mounted() {
      this.queryParam.dateType = 'sevenDay';
      this.rangeDate = [moment().subtract(7, 'days'), moment().subtract(1, 'days')];
      this.getSiteList();
    },
    methods: {
      // ========================================== 筛选 ==========================================
      //获取站点列表
      getSiteList() {
        let that = this;
        getAction('/sys/api/getSiteListByUid')
          .then(function (res) {
            if (res.code == 0) {
              if (res.data || res.data.length) {
                let defaultSiteCode = localStorage.getItem('siteCode');
                if (defaultSiteCode) {
                  let isInSite = false;
                  for (let i in res.data) {
                    if (defaultSiteCode === res.data[i].code) {
                      isInSite = true;
                      that.queryParam.siteId = res.data[i].id;
                      break;
                    }
                  }
                  if (!isInSite) {
                    that.queryParam.siteId = res.data[0].id;
                    localStorage.setItem('siteCode', res.data[0].code);
                  }
                } else {
                  that.queryParam.siteId = res.data[0].id;
                  localStorage.setItem('siteCode', res.data[0].code);
                }
                that.siteList = res.data;
                that.reloadData();
              }
            } else {
              that.$message.error('获取站点失败！');
            }
          })
          .catch(function (err) {
            console.log(err);
          });
      },
      // 搜索
      filterOption(inputValue, option) {
        return option.componentOptions.children[0].text.indexOf(inputValue) >= 0;
      },
      //搜索条件部分的逻辑
      onChangeDatePciker(date, dateString) {
        if (dateString.length > 0) {
          this.rangeDate = date;
          this.queryParam.start = dateString[0];
          this.queryParam.end = dateString[1];
          this.queryParam.dateType = undefined;
          this.reloadData();
        }
      },
      //日期选择只能今天之前
      disabledDate(current) {
        return current && current > moment().subtract(0, 'days');
      },
      //设置列表的时间查询条件
      setTime(time) {
        this.queryParam.dateType = time;
        this.queryParam.start = '';
        this.queryParam.end = '';
        if (time == '') {
          this.rangeDate = undefined;
        } else if (time == 'sevenDay') {
          this.rangeDate = [moment().subtract(7, 'days'), moment().subtract(1, 'days')];
        } else if (time == 'thirtyDay') {
          this.rangeDate = [moment().subtract(30, 'days'), moment().subtract(1, 'days')];
        } else if (time == 'yesterday') {
          this.rangeDate = [moment().subtract(1, 'days'), moment().subtract(1, 'days')];
        } else if (time == 'today') {
          this.rangeDate = [moment(), moment()];
        }
        this.reloadData();
      },

      changeSite(value, e) {
        this.selectSiteInfo = e.data.attrs.info;
        this.queryParam.siteId = this.selectSiteInfo.id;
        this.reloadData(this.queryParam.siteId);
      },

      //重新刷新页面数据
      reloadData(value) {
        this.loading = true;
        for (let i in this.siteList) {
          if (value === this.siteList[i].id) {
            localStorage.setItem('siteCode', this.siteList[i].code);
          }
        }
        this.getFlowIndexNumber();
        this.getDailyList();
      },
      // ========================================== 访客量、浏览量、询盘数量、折线图以及统计 ==========================================
      getFlowIndexNumber() {
        let that = this;
        getAction('/datacenter/flow/number', this.queryParam).then(function (res) {
          console.log('res', res);
          if (!res.result) {
            that.coreDataChart = {
              x: [],
              uv: [],
              pv: [],
              enquiry: [],
            };
            that.loading = false;
            return;
          }

          that.flowIndexNums = res.result.flowIndexNumber;
          let r = res.result.dailyTrends;
          let x = [],
            pv = [],
            uv = [],
            enquiry = [];
          if (r != null && r.length > 0) {
            for (let item of r) {
              x.push(item.date);
              pv.push(item.pvCount);
              uv.push(item.uvCount);
              enquiry.push(item.enquiryCount);
            }
          }
          that.coreDataChart.x = x;
          that.coreDataChart.pv = pv;
          that.coreDataChart.uv = uv;
          that.coreDataChart.enquiry = enquiry;

          that.loading = false;
        });
      },
      // ========================================== 每日数据列表 ==========================================
      getDailyList() {
        let that = this;
        getAction('/datacenter/daily/list', this.queryParam).then(function (res) {
          if (res.code == 200) {
            that.dailyDataSource = res.result;
          } else {
            that.dailyDataSource = [];
          }
        });
      },
    },
  };
</script>

<!-- 询盘页面的样式 -->
<style lang="less" scoped>
  .ant-alert {
    /deep/ .ant-btn {
      border-radius: 0;
      margin-left: 10px;
    }
  }

  .theme-color {
    color: @primary-color;
  }

  .r1 {
    .choose-site {
      display: flex;

      /deep/ .ant-select-selection {
        background: transparent;
        color: #fff;
      }

      /deep/ .ant-select-selection__clear {
        background: transparent;
      }

      /deep/ i,
      /deep/ .ant-calendar-range-picker-separator {
        color: #fff;
      }
    }

    .t1 {
      font-size: 18px;
      color: #fff;
    }

    .ant-calendar-picker {
      margin-right: 20px;

      /deep/ .ant-input {
        background: transparent;
        color: #e2e2e2;
      }
    }

    /deep/ .ant-btn {
      background: transparent;
      color: #e2e2e2;
      margin-right: 10px;

      &.active {
        background: #fff;
        border-color: #fff;
        color: @primary-color;
      }
    }
  }

  .r2 {
    background: #fff;
    border-radius: 10px;
    padding: 30px 20px;
    margin-top: 20px;

    .ant-col:not(:last-child) {
      border-right: 1px solid #e6e6e6;
    }

    p {
      margin: 0;
      text-align: center;

      &.t1 {
        color: #333;
        margin-bottom: 15px;

        img {
          margin-right: 10px;
          width: 15px;
          margin-top: -5px;
        }
      }

      &.t2 {
        color: @primary-color;
        font-size: 30px;
        font-weight: 500;
        line-height: 1;
        padding-left: 25px;
      }
    }
  }

  .r3 {
    margin-top: 20px;
  }

  .r4 {
    margin-top: 20px;

    /deep/ .ant-table-tbody {
      background: #fff;
    }

    /deep/ .ant-table-tbody > tr > td {
      border-bottom: 1px solid #f7f7f7;
    }
  }
</style>

<!-- 首页的样式 -->
<style scoped lang="less">
  p,
  span {
    color: #000;
    margin: 0;
  }

  .theme-color {
    color: @primary-color;
  }

  .title {
    font-size: 18px;
    color: #000;
  }
</style>
<style lang="less">
  .pop-wrap {
    .ant-popover-inner-content {
      padding: 0;
    }

    .wrap {
      width: 400px;
      padding: 20px 20px;
      background: url('../../../assets/home2-7/pop-bg.svg') no-repeat;
      background-position: bottom right;

      p {
        line-height: 1.8;

        i {
          color: @primary-color;
          margin-right: 10px;
        }
      }

      .name {
        font-size: 18px;
        margin-bottom: 20px;
      }

      .job {
        font-size: 15px;
        color: #9f9f9f;
      }

      .ant-col-8 {
        text-align: right;
      }
    }
  }
</style>
