<template>
  <div class="app-container">
    <div v-if="isQueryPermissions">
      <div class="filter-container">
        <el-select
          v-model="listQuery.sysOrigin"
          placeholder="系统"
          style="width: 120px"
          class="filter-item"
          @change="handleSearch"
        >
          <el-option
            v-for="item in permissionsSysOriginPlatforms"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left;"> <sys-origin-icon :icon="item.value" :desc="item.value" /></span>
            <span style="float: left;margin-left:10px">{{ item.label }}</span>
          </el-option>
        </el-select>
        <el-input
          v-model.trim="listQuery.userId"
          v-number
          placeholder="长UID"
          style="width: 200px;"
          class="filter-item"
        />
        <el-input
          v-model.trim="listQuery.account"
          placeholder="短账号"
          style="width: 200px;"
          class="filter-item"
        />
        <div class="filter-item" style="width: 120px;">
          <select-system-region
            ref="regionSelectPolicy"
            v-model="listQuery.region"
            :sys-origin="listQuery.sysOrigin"
            clearable
            placeholder="区域"
            @change="handleSearch"
          />
        </div>
        <div class="filter-item">
          <el-tooltip effect="dark" content="仅包含开始时间至结束时间区间的数据" placement="bottom">
            <el-date-picker
              v-model="rangeDate"
              style="width: 100%;"
              value-format="yyyy-MM-dd"
              type="daterange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期开始"
              end-placeholder="结束日期结束"
              @change="handleDateRangeChange"
            />
          </el-tooltip>
        </div>
        <el-button
          :loading="searchLoading"
          :disabled="searchDisabled"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
        >
          搜索
        </el-button>
      </div>
      <div>
        <div slot="title" class="count-item">
          <i>
            <strong class="strong-style"> 筛选时间：</strong>
          </i>
          <i>
            <strong class="strong-style">{{ formatDate(listQuery.startDate) }} 00:00:00</strong>
          </i>
          <i>
            <strong class="strong-style">至{{ formatDate(listQuery.endDate) }} 00:00:00 区间的数据</strong>
          </i>
        </div>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        :default-sort="{ prop: 'effectivePerson', order: 'descending' }"
        element-loading-text="Loading"
        fit
        highlight-current-row
        @cell-mouse-enter="handleMouseEnter"
        @sort-change="handleSortChange"
      >
        <el-table-column label="BD" align="left" min-width="190">
          <template slot-scope="scope">
            <user-table-exhibit :user-profile="scope.row.userProfile" :query-details="true" />
          </template>
        </el-table-column>
        <el-table-column label="自己邀请人数（一级邀请）" align="left" min-width="80">
          <template slot-scope="scope">
            <span>
              {{
                isNull(scope.row.userInviteUserCount == null ? 0 : scope.row.userInviteUserCount.level1Invitation)
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="二级邀请人数" align="left" min-width="80">
          <template slot-scope="scope">
            <span>
              {{
                isNull(scope.row.userInviteUserCount == null ? 0 : scope.row.userInviteUserCount.level2Invitation)
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="三级邀请人数" align="left" min-width="80">
          <template slot-scope="scope">
            <span>
              {{
                isNull(scope.row.userInviteUserCount == null ? 0 : scope.row.userInviteUserCount.level3Invitation)
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="邀请总人数" align="left" min-width="80">
          <template slot-scope="scope">
            <span>
              {{
                isNull(scope.row.userInviteUserCount == null ? 0 : scope.row.userInviteUserCount.totalInvitation)
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="总充值（金币）" align="left" min-width="90">
          <template slot-scope="scope">
            <span>{{ isNull(scope.row.totalRecharge) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="BD客单价" align="left" min-width="80">
          <template slot-scope="scope">
            <span>{{ isNull(scope.row.customerUnitPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="区域平均客单价" align="left" min-width="100">
          <template slot-scope="scope">
            <span>{{ isNull(scope.row.regionalAvgCustomerUnitPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="effectivePerson" label="有效人数" align="" min-width="120" />
        <el-table-column label="区域" align="left" min-width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.regionName == null ? scope.row.region : scope.row.regionName }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable prop="regionRanking" label="BD区域排名" align="" min-width="120" />
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.cursor"
        :limit.sync="listQuery.limit"
        @pagination="renderData"
      />
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
// import { Table, TableColumn, Pagination } from 'element-ui'
import { pickerOptions } from '@/constant/el-const'
import { pageWorkStatistics } from '@/api/room-anchor'
import { mapGetters } from 'vuex'

export default {
  name: 'WorkStatistics',
  components: {
    Pagination
  },
  data() {
    return {
      // data: [],
      level: 0,
      dbDisabled: false,
      agentDisabled: false,
      pickerOptions,
      rangeDate: [],
      thatSelectedUserId: '',
      submitLoading: false,
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        sysOrigin: 'HALAR',
        sortType: 0,
        startDate: '',
        endDate: '',
        userId: '',
        account: ''
      },
      listLoading: false,
      searchLoading: false,
      startDate: '',
      endDate: new Date()
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms']),
    isQueryPermissions() {
      return true
    },
    startIndex() {
      return (this.currentPage - 1) * this.pageSize
    },
    endIndex() {
      return this.startIndex + this.pageSize
    }
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startDate = newVal[0]
          this.listQuery.endDate = newVal[1]
          return
        }
        this.listQuery.startDate = ''
        this.listQuery.endDate = ''
      }
    }
  },
  created() {
    const that = this
    that.renderData(true)
    const date = new Date(this.endDate)
    date.setMonth(date.getMonth() - 1)
    that.rangeDate = [date, new Date()]
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
  },
  methods: {
    formatDate(dateString) {
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (1 + date.getMonth()).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    renderData(isReset) {
      const that = this
      if (isReset === true) {
        that.listQuery.cursor = 1
        that.list = []
      }

      if (that.listLoading === true && isReset === true) {
        return
      }
      // 待后台优化，再放开
      that.listLoading = true
      that.searchDisabled = true
      that.listQuery.startDate = that.formatDate(that.listQuery.startDate)
      that.listQuery.endDate = that.formatDate(that.listQuery.endDate)
      pageWorkStatistics(that.listQuery).then(res => {
        that.total = res.body.total || 0
        that.list = res.body.records
        that.listLoading = false
        that.searchLoading = false
        that.searchDisabled = false
      }).catch(er => {
        that.listLoading = false
        that.searchLoading = false
        that.searchDisabled = false
      })
    },
    handleSearch() {
      const that = this
      that.searchLoading = true
      that.renderData(true)
    },
    handleMouseEnter(row) {
      this.thatSelectedUserId = row.userId
    },
    handleDateRangeChange(val) {
      // 当日期范围改变时，更新绑定的变量
      this.rangeDate = val
    },
    isNull(data) {
      return !data && data !== 0 ? '0' : data
    },
    handleSortChange(row) {
      if (row.order === 'descending') {
        this.listQuery.sortType = 1
      } else {
        this.listQuery.sortType = 0
      }
      this.renderData()
    }
  }
}
</script>
<style scoped lang="scss">
.this-level {
  padding-bottom: 30px;
  display: flex;

  > div {
    width: 150px;
  }
}
.strong-style{
  font-style: normal;
}
</style>
