<template>
  <div :class="queryBackOperation ? 'app-container-inside':'app-container'">
    <div class="filter-container">
      <el-select
        v-model="sysOrigins"
        placeholder="系统"
        style="width: 200px"
        class="filter-item"
        multiple
        collapse-tags
      >
        <el-option
          v-for="item in permissionsSysOriginPlatformAlls"
          :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-select
        v-model="listQuery.type"
        placeholder="类型"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in candyPurchasingTypes"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <div class="filter-item">
        <el-autocomplete
          v-model="listQuery.origin"
          popper-class="my-autocomplete"
          :fetch-suggestions="querySearch"
          placeholder="请输入或选择内容"
          clearable
          @select="handleSelect"
          @clear="handleSelect"
        >
          <i
            slot="suffix"
            class="el-icon-edit el-input__icon"
          />
          <template slot-scope="{ item }">
            <span :label="item.name">{{ item.name }}</span>
            <div :key="item.value" :value="item.value" style="font-size:12px; color:#d8d0d0">{{ item.value }}</div>
          </template>
        </el-autocomplete>
      </div>
      <div class="filter-item">
        <account-input v-model="listQuery.userId" :sys-origin="sysOrigins && sysOrigins.length === 1? sysOrigins[0] : ''" placeholder="用户ID" />
      </div>
      <el-input
        v-model.trim="listQuery.trackId"
        placeholder="跟踪ID"
        style="width: 200px;"
        class="filter-item"
      />
      <el-input
        v-model.trim="listQuery.id"
        v-number
        placeholder="记录ID"
        style="width: 200px;"
        class="filter-item"
      />
      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
      </div>
      <el-select
        v-model="listQuery.limit"
        placeholder="类型"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="(val) in limits"
          :key="val"
          :label="val+'条/页'"
          :value="val"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="listLoading"
        @click="handleSearch"
      >
        搜索
      </el-button>
    </div>
    <el-alert type="warning" :closable="false">
      注意: 可查看数据为最近1年内的数据
    </el-alert>
    <el-table
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column type="index" width="50" label="No" />
      <el-table-column prop="sysOrigin" label="系统" align="center" min-width="80">
        <template slot-scope="scope">
          <sys-origin-icon :icon="scope.row.runningWater.sysOrigin" :desc="scope.row.runningWater.sysOrigin" />
        </template>
      </el-table-column>
      <el-table-column label="用户" align="center" min-width="200">
        <template slot-scope="scope">
          <user-table-exhibit :user-profile="scope.row.userProfile" :query-details="true" :tag-name="scope.row.backOperationName" />
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" min-width="80">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.runningWater.type === 0">收入</span>
            <span v-else-if="scope.row.runningWater.type === 1">支出</span>
            <span v-else>未知</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="糖果数" align="center" min-width="80">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.runningWater.type === 0" class="font-danger">+{{ scope.row.runningWater.quantity }}</span>
            <span v-else-if="scope.row.runningWater.type === 1">-{{ scope.row.runningWater.quantity }}</span>
            <span v-else>{{ scope.row.runningWater.quantity }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="runningWater.balance" label="余额" align="center" />
      <el-table-column label="来源" prop="runningWater.originName" align="center" show-overflow-tooltip min-width="300">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="'标签:' + scope.row.runningWater.origin">
            <div>
              {{ scope.row.runningWater.originName }}
              <span v-if="scope.row.runningWater.remark">({{ scope.row.runningWater.remark }})</span>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="runningWater.createTime" label="创建时间" width="200" align="center">
        <template slot-scope="scope">
          <div>
            {{ scope.row.runningWater.createTime | dateFormat('yyyy-MM-dd HH:mm:ss') }}
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div style="text-align: center; margin-top:20px;">
      <el-button v-if="!notMore " size="mini" :disabled="listLoading" :loading="listLoading" @click="clickLoadMore">加载更多</el-button>
      <span v-else>已加载全部</span>
    </div>
  </div>
</template>

<script>

import { getClsGoldRunningWater } from '@/api/purchase'
import { originPlatforms } from '@/constant/origin'
import { candyPurchasingTypes, currencyOrigins } from '@/constant/type'
import { mapGetters } from 'vuex'
import { beforeDateObject, datePlusDays, getMonthLastDate } from '@/utils'

export default {
  name: 'GoldRunnigWater',
  props: {
    queryBackOperation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      limits: [10, 20, 30, 50, 100, 200],
      searchDisabled: false,
      minDate: null,
      maxDate: null,
      pickerOptions: {
        disabledDate(date) {
          return date.getTime() > datePlusDays(new Date(), 1).getTime()
        }
      },
      thatSelectedUserId: '',
      originPlatforms,
      candyPurchasingTypes,
      currencyOrigins,
      list: [],
      total: 0,
      rangeDate: [],
      listQuery: {
        limit: 20,
        userId: '',
        type: '',
        origin: '',
        startTime: '',
        endTime: '',
        sysOrigin: '',
        context: '',
        id: '',
        trackId: ''
      },
      sysOrigins: [],
      listLoading: false,
      clickUserId: '',
      restaurants: [],
      notMore: false,
      notProccessRangeDate: false,
      beforeIntervalDays: 1
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatformAlls'])
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (this.notProccessRangeDate === true) {
          this.notProccessRangeDate = false
          return
        }
        if (newVal && newVal.length > 0) {
          this.listQuery.startTime = newVal[0]
          this.listQuery.endTime = newVal[1]
          return
        }
        this.notProccessRangeDate = true
        const defaultRangeTime = this.defaultRangeTimestamp()
        this.rangeDate = defaultRangeTime
        this.listQuery.startTime = defaultRangeTime[0]
        this.listQuery.endTime = defaultRangeTime[1]
      }
    },
    queryBackOperation: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal === true) {
          this.listQuery.queryBackOperationUser = true
        }
      }
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatformAlls[0]
    if (!querySystem) {
      return
    }
    that.sysOrigins.push(querySystem.value)
    that.rangeDate = that.defaultRangeTimestamp()
    that.renderData()
  },
  mounted() {
    this.restaurants = this.currencyOrigins
  },
  methods: {
    defaultRangeTimestamp() {
      const defStartDate = beforeDateObject(this.beforeIntervalDays)
      const mDate = datePlusDays(new Date(), 1)
      mDate.setHours(23)
      mDate.setMinutes(59)
      mDate.setSeconds(59)
      const monthLastDate = getMonthLastDate()
      monthLastDate.setHours(23)
      monthLastDate.setMinutes(59)
      monthLastDate.setSeconds(59)
      const nowDate = mDate.getMonth() !== monthLastDate.getMonth() ? monthLastDate : mDate

      if (nowDate.getMonth() !== defStartDate.getMonth()) {
        return [defStartDate.getTime(), nowDate.getTime()]
      }

      return [defStartDate.getTime(), nowDate.getTime()]
    },

    renderData(isClean) {
      const that = this

      if (that.listLoading === true) {
        return
      }

      if (!that.listQuery.startTime || !that.listQuery.endTime) {
        that.$opsMessage.warn('请选择时间范围~')
        return
      }

      const startYear = new Date(that.listQuery.startTime).getFullYear()
      const endYear = new Date(that.listQuery.endTime).getFullYear()
      if (startYear !== endYear) {
        that.$opsMessage.warn('不允许跨年查询!')
        return
      }

      if (isClean === true) {
        that.list = []
        that.listQuery.context = null
        that.notMore = false
      }

      that.listQuery.sysOrigin = that.sysOrigins.length > 0 ? that.sysOrigins.join(',') : that.permissionsSysOriginPlatformAlls.map(item => item.value).join(',')

      that.listLoading = true
      getClsGoldRunningWater(that.listQuery).then(res => {
        that.listLoading = false
        const result = res.body
        if (result.errorCode) {
          that.$opsMessage.failresult.errorCode
          return
        }

        const list = result.waters || []
        that.notMore = result.listOver || false
        that.listQuery.context = result.context
        that.list = that.list.concat(list)
      }).catch(er => {
        that.listLoading = false
        console.error(er)
      })
    },
    handleSearch() {
      if (this.listQuery.origin !== '') {
        const origins = this.currencyOrigins.filter(this.createFilter(this.listQuery.origin))
        this.listQuery.origin = origins.length > 0 ? origins[0].value : this.listQuery.origin
      }
      this.renderData(true)
    },
    querySearch(queryString, cb) {
      var restaurants = currencyOrigins
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0) || (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0)
      }
    },
    handleSelect(item) {
      this.renderData(true)
    },
    clickLoadMore() {
      this.renderData()
    }
  }
}
</script>

