<template>
  <div class="gold-running-water-drawer">
    <el-dialog
      :title="$t('pages.goldRunningWater.dialog.title')"
      :visible="true"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      width="80%"
    >
      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          :range-separator="$t('pages.goldRunningWater.filter.to')"
          :start-placeholder="$t('pages.goldRunningWater.filter.startDate')"
          :end-placeholder="$t('pages.goldRunningWater.filter.endDate')"
          :clearable="false"
          @change="handleDateChange"
        />
      </div>
      <div class="gold-running-water-content">
        <el-alert type="warning" :closable="false">
          {{ $t('pages.goldRunningWater.message.recentYearOnly') }}
        </el-alert>
        <el-table
          v-loading="listLoading"
          :data="list"
          fit
          highlight-current-row
        >
          <el-table-column
            :label="$t('pages.goldRunningWater.table.system')"
            align="center"
            show-overflow-tooltip
            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="$t('pages.goldRunningWater.table.type')"
            align="center"
            show-overflow-tooltip
            min-width="80"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.runningWater.type === 0">{{ $t('pages.goldRunningWater.type.income') }}</span>
              <span v-else-if="scope.row.runningWater.type === 1">{{ $t('pages.goldRunningWater.type.expense') }}</span>
              <span v-else>{{ $t('pages.goldRunningWater.type.unknown') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('pages.goldRunningWater.table.goldAmount')"
            align="center"
            show-overflow-tooltip
            min-width="120"
          >
            <template slot-scope="scope">
              <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>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('pages.goldRunningWater.table.balance')"
            prop="runningWater.balance"
            align="center"
            show-overflow-tooltip
            min-width="120"
          />
          <el-table-column
            :label="$t('pages.goldRunningWater.table.source')"
            prop="runningWater.originName"
            align="center"
            show-overflow-tooltip
            min-width="300"
          >
            <template slot-scope="scope">
              {{ scope.row.runningWater.originName }}
              <span
                v-if="scope.row.runningWater.remark"
              >({{ scope.row.runningWater.remark }})</span>
              <span
                v-if="scope.row.backOperationName"
              >、{{ scope.row.backOperationName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('pages.goldRunningWater.table.createdAt')"
            prop="runningWater.createTime"
            align="center"
            show-overflow-tooltip
            width="200"
          >
            <template slot-scope="scope">
              {{ scope.row.runningWater.createTime | dateFormat }}
            </template>
          </el-table-column>
        </el-table>
        <div
          v-if="list && list.length > 0"
          style="text-align: center; margin-top:20px;"
        >
          <el-button
            v-if="!notMore"
            size="mini"
            :disabled="listLoading"
            @click="clickLoadMore"
          >{{ $t('pages.goldRunningWater.action.loadMore') }}</el-button>
          <span v-else>{{ $t('pages.goldRunningWater.message.loadedAll') }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listGoldRunningWater } from '@/api/purchase'
export default {
  name: 'RunningWaterPreviewTabs',
  props: {
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      listLoading: false,
      list: [],
      rangeDate: [],
      listQuery: {
        userId: '',
        lastId: '',
        startTime: '',
        endTime: ''
      },
      notMore: false,
      pickerOptions: {
        disabledDate(date) {
          const tomorrow = new Date()
          tomorrow.setDate(tomorrow.getDate() + 1)
          tomorrow.setHours(23, 59, 59, 999)
          return date.getTime() > tomorrow.getTime()
        }
      }
    }
  },
  created() {
    // 先初始化默认时间范围（今天 00:00:00 ~ 23:59:59）
    const defaultRangeTime = this.defaultRangeTimestamp()
    this.rangeDate = defaultRangeTime
    this.listQuery.startTime = defaultRangeTime[0]
    this.listQuery.endTime = defaultRangeTime[1]
    // 再初始化 userId，最后触发一次加载
    if (this.userId) {
      this.listQuery.userId = this.userId
      this.renderData()
    }
  },
  watch: {
    userId(newVal) {
      if (newVal) {
        this.listQuery.userId = newVal
        this.resetAndLoad()
      }
    }
  },
  methods: {
    // 日期选择器 change 事件：直接从事件参数取值，避免 watch 异步延迟问题
    handleDateChange(val) {
      if (val && val.length === 2) {
        this.listQuery.startTime = val[0]
        this.listQuery.endTime = val[1]
      } else {
        // 清空时恢复默认
        const defaultRangeTime = this.defaultRangeTimestamp()
        this.rangeDate = defaultRangeTime
        this.listQuery.startTime = defaultRangeTime[0]
        this.listQuery.endTime = defaultRangeTime[1]
      }
      this.resetAndLoad()
    },
    // 换条件时必须调此方法，重置游标和列表后再加载
    resetAndLoad() {
      this.list = []
      this.listQuery.lastId = ''
      this.notMore = false
      this.renderData()
    },
    renderData() {
      const that = this
      if (!that.listQuery.userId) {
        return
      }
      that.listLoading = true
      listGoldRunningWater(that.listQuery)
        .then(res => {
          that.listLoading = false
          const { body } = res
          const list = body || []
          that.notMore = list.length <= 0
          that.list = that.list.concat(list)
          if (that.list && that.list.length > 0) {
            that.listQuery.lastId =
              that.list[that.list.length - 1].runningWater.id
          }
        })
        .catch(er => {
          that.listLoading = false
          console.error(er)
        })
    },
    // 默认时间范围：今天 00:00:00 ~ 今天 23:59:59
    defaultRangeTimestamp() {
      const startDate = new Date()
      startDate.setHours(0, 0, 0, 0)

      const endDate = new Date()
      endDate.setHours(23, 59, 59, 0)

      return [startDate.getTime(), endDate.getTime()]
    },
    handleClose() {
      this.$emit('close')
    },
    clickLoadMore() {
      this.renderData()
    }
  }
}
</script>
<style scoped lang="scss">
.gold-running-water-content {
  max-height: 450px;
  overflow: auto;
}
</style>
