<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        :placeholder="$t('pages.userBankAccounts.filter.system')"
        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>

      <div class="filter-item">
        <account-input v-model="listQuery.userId" :sys-origin="listQuery.sysOrigin" :placeholder="$t('pages.userBankAccounts.filter.userId')" />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        {{ $t('pages.userBankAccounts.action.search') }}
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('pages.userBankAccounts.action.add') }}
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        :disabled="exportLoading"
        :loading="exportLoading"
        @click="exprotExcel"
      >
        {{ $t('pages.userBankAccounts.action.export') }}
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        @click="readExcel"
      >
        {{ $t('pages.userBankAccounts.action.import') }}<i class="el-icon-upload el-icon--right" />
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :element-loading-text="$t('pages.userBankAccounts.loading')"
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
    >
      <el-table-column type="index" width="50" label="No" />
      <el-table-column prop="sysOrigin" :label="$t('pages.userBankAccounts.table.system')" align="center" width="80">
        <template slot-scope="scope">
          <sys-origin-icon :icon="scope.row.sysOrigin" :desc="scope.row.sysOrigin" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.userBankAccounts.table.user')" align="center" min-width="200">
        <template slot-scope="scope">
          <user-table-exhibit :user-profile="scope.row.userProfile" :query-details="true" />
        </template>
      </el-table-column>
      <el-table-column prop="earnPoints" :label="$t('pages.userBankAccounts.table.earnPoints')" align="center" min-width="100" />
      <el-table-column prop="consumptionPoints" :label="$t('pages.userBankAccounts.table.consumptionPoints')" align="center" min-width="100" />
      <el-table-column prop="balance" :label="$t('pages.userBankAccounts.table.balance')" align="center" min-width="100" />
      <el-table-column prop="createTime" :label="$t('pages.userBankAccounts.table.createTime')" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" :label="$t('pages.userBankAccounts.table.updateTime')" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.updateTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('pages.userBankAccounts.table.actions')" align="center">
        <template slot-scope="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              <i class="el-icon-more" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="showGoldInputBox(scope.row, true)">{{ $t('pages.userBankAccounts.action.send') }}</el-dropdown-item>
              <el-dropdown-item @click.native="showGoldInputBox(scope.row, false)">{{ $t('pages.userBankAccounts.action.deduct') }}</el-dropdown-item>

              <el-dropdown-item @click.native="showTransferBox(scope.row)">{{ $t('pages.userBankAccounts.action.transfer') }}</el-dropdown-item>
              <el-dropdown-item @click.native="clickRunningWater(scope.row)">{{ $t('pages.userBankAccounts.action.transactions') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="listQuery.lastId" class="load-more">
      <span v-if="notData">{{ $t('pages.userBankAccounts.action.allLoaded') }}</span>
      <el-button v-else size="mini" :disabled="loadMoreLoading" :loading="loadMoreLoading" @click="clickLoadMore">{{ $t('pages.userBankAccounts.action.loadMore') }}</el-button>
    </div>
    <form-edit
      v-if="formEditVisable"
      :row="thatRow"
      :sys-origin="listQuery.sysOrigin"
      @close="formEditClose"
      @success="formEditSuccess"
    />
    <div class="gold-input-box">
      <el-dialog
        :title="getGoldActionName(type)"
        :visible="goldInputBoxVisible"
        :modal-append-to-body="true"
        :append-to-body="true"
        width="400px"
      >
        <el-form
          ref="form"
          :rules="formRules"
          :model="formData"
          label-position="left"
          label-width="70px"
          style="width: 300px; margin-left:50px;"
        >
          <el-form-item :label="$t('pages.userBankAccounts.form.amount')" prop="quantity">
            <el-input
              v-model.trim="formData.quantity"
              :placeholder="getGoldAmountPlaceholder(type)"
            />
          </el-form-item>

          <el-form-item :label="$t('pages.userBankAccounts.form.internalRemark')" prop="remark">
            <el-input
              v-model.trim="formData.remark"
              :placeholder="$t('pages.userBankAccounts.placeholder.internalRemark')"
            />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="hideGoldInputBox()">
            {{ $t('pages.userBankAccounts.action.cancel') }}
          </el-button>
          <el-button
            v-loading="listLoading"
            type="primary"
            @click="goldSubmit()"
          >
            {{ $t('pages.userBankAccounts.action.submit') }}
          </el-button>
        </div>
      </el-dialog>
    </div>
    <form-edit
      v-if="formEditVisable"
      :row="thatRow"
      :sys-origin="listQuery.sysOrigin"
      @close="formEditClose"
      @success="formEditSuccess"
    />
    <running-water
      v-if="runningWaterVisible"
      :row="thatRow"
      @close="runningWaterVisible=false"
    />
    <div class="gold-input-box">
      <el-dialog
        :title="$t('pages.userBankAccounts.action.transfer')"
        :visible="transferVisible"
        :modal-append-to-body="true"
        :append-to-body="true"
        width="500px"
      >
        <el-form
          ref="form"
          :rules="transferFormRules"
          :model="transferFormData"
          label-position="left"
          label-width="70px"
          style="width: 400px; margin-left:50px;"
        >

          <el-form-item prop="acceptUserId" :label="$t('pages.userBankAccounts.form.payee')">
            <account-input ref="transferAccountInput" v-model="transferFormData.acceptUserId" :sys-origin="transferFormData.sysOrigin" :placeholder="$t('pages.userBankAccounts.placeholder.userAccount')" />
          </el-form-item>

          <el-form-item :label="$t('pages.userBankAccounts.form.amount')" prop="quantity">
            <el-input
              v-model.trim="transferFormData.quantity"
              :placeholder="$t('pages.userBankAccounts.placeholder.transferAmount')"
            />
          </el-form-item>

          <el-form-item :label="$t('pages.userBankAccounts.form.internalRemark')" prop="remark">
            <el-input
              v-model.trim="transferFormData.remark"
              :placeholder="$t('pages.userBankAccounts.placeholder.internalRemark')"
            />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="hideTransferBox()">
            {{ $t('pages.userBankAccounts.action.cancel') }}
          </el-button>
          <el-button
            v-loading="listLoading"
            type="primary"
            @click="transferSubmit()"
          >
            {{ $t('pages.userBankAccounts.action.submit') }}
          </el-button>
        </div>
      </el-dialog>
    </div>

    <div class="excel-import">
      <el-dialog :title="$t('pages.userBankAccounts.importDialog.title')" :visible.sync="uploadDialogVisible" :close-on-click-modal="false" width="400px" :modal-append-to-body="true" :append-to-body="true">
        <div class="upload_box">
          <span>{{ $t('pages.userBankAccounts.importDialog.selectFile') }}</span>
          <el-button type="text" :loading="downloadTemplateLoading"><i class="el-icon-tickets" style="margin-right: 4px;" /><a href="https://dev.file.momooline.com/files/Import%20Template.xlsx">{{ $t('pages.userBankAccounts.importDialog.downloadTemplate') }}</a></el-button>
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            action=""
            :auto-upload="true"
            :on-success="uploadSuccess"
            :disabled="uploadLoding"
            :show-file-list="false"
            :http-request="uploadTemplate"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">{{ $t('pages.userBankAccounts.importDialog.dragHere') }}<em>{{ $t('pages.userBankAccounts.importDialog.clickUpload') }}</em></div>
          </el-upload>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { pageBank, deductMoney, sendMoney, transferMoney, exprotBank, confirmImport } from '@/api/app-user-bank-balance'
import { mapGetters } from 'vuex'
import FormEdit from './form-edit'
import RunningWater from './running-water'

export default {
  name: 'UserBankBalance',
  components: { FormEdit, RunningWater },
  data() {
    return {
      runningWaterVisible: false,
      thatRow: null,
      userInfo: {},
      transferVisible: false,
      searchDisabled: false,
      goldInputBoxVisible: false,
      uploadDialogVisible: false,
      // true：发送  false：扣除
      type: false,
      thatSelectedUserId: '',
      listQuery: {
        limit: 20,
        sysOrigin: 'HALAR',
        userId: '',
        lastId: ''
      },
      formData: {
        userId: '',
        quantity: '',
        sysOrigin: '',
        remark: ''
      },
      transferFormData: {
        userId: '',
        acceptUserId: '',
        quantity: '',
        sysOrigin: '',
        remark: ''
      },
      listLoading: false,
      list: [],
      notData: false,
      loadMoreLoading: false,
      formEditVisable: false,
      exportLoading: false
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms']),
    commonRules() {
      return [
        { required: true, message: this.$t('pages.userBankAccounts.validation.required'), trigger: 'blur' }
      ]
    },
    formRules() {
      return {
        userId: this.commonRules,
        quantity: { required: true, message: this.$t('pages.userBankAccounts.validation.requiredField'), trigger: 'blur' },
        sysOrigin: this.commonRules
      }
    },
    transferFormRules() {
      return {
        userId: this.commonRules,
        acceptUserId: this.commonRules,
        quantity: { required: true, message: this.$t('pages.userBankAccounts.validation.requiredField'), trigger: 'blur' },
        sysOrigin: this.commonRules
      }
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
  },
  methods: {
    renderData(isReset) {
      const that = this
      if (!that.listQuery.sysOrigin) {
        return
      }
      if (isReset === true) {
        that.list = []
        that.notData = false
        that.listQuery.lastId = ''
      }
      that.listLoading = true
      pageBank(that.listQuery).then(res => {
        that.listLoading = false
        that.loadMoreLoading = false
        const { body } = res
        const list = body || []
        that.notData = list.length <= 0
        if (!that.notData) {
          that.list = that.list.concat(list)
          that.listQuery.lastId = that.list[that.list.length - 1].id
        }
      }).catch(er => {
        that.listLoading = false
        that.loadMoreLoading = false
      })
    },
    handleSearch() {
      this.renderData(true)
    },
    handleCreate() {
      this.thatRow = null
      this.formEditVisable = true
    },
    handleClose() {
      this.$emit('close')
    },
    clickRunningWater(details) {
      this.thatRow = details
      this.runningWaterVisible = true
    },
    handleMouseEnter(row) {
      this.thatRow = row
    },
    formEditClose() {
      this.formEditVisable = false
    },
    formEditSuccess() {
      this.formEditVisable = false
      this.renderData(true)
    },
    showGoldInputBox(row, type) {
      const that = this
      that.type = type

      that.formData = {
        userId: row.id,
        quantity: '',
        sysOrigin: row.sysOrigin,
        remark: ''
      }
      that.goldInputBoxVisible = true
    },
    showTransferBox(row) {
      const that = this

      that.transferFormData = {
        userId: row.id,
        acceptUserId: '',
        quantity: '',
        sysOrigin: row.sysOrigin,
        remark: ''
      }
      that.transferVisible = true
    },
    getGoldActionName(type) {
      return type ? this.$t('pages.userBankAccounts.action.send') : this.$t('pages.userBankAccounts.action.deduct')
    },
    getGoldAmountPlaceholder(type) {
      return type ? this.$t('pages.userBankAccounts.placeholder.sendAmount') : this.$t('pages.userBankAccounts.placeholder.deductAmount')
    },
    hideGoldInputBox() {
      const that = this
      that.goldInputBoxVisible = false
    },
    hideTransferBox() {
      const that = this
      that.transferVisible = false
    },
    readExcel() {
      const that = this
      that.uploadDialogVisible = true
    },
    goldSubmit() {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        that.listLoading = true
        if (that.type) {
          sendMoney(that.formData).then(res => {
            that.$opsMessage.success()
            that.goldInputBoxVisible = false
            that.listLoading = false
            that.renderData(true)
          }).catch(er => {
            that.listLoading = false
            that.$opsMessage.success()
            console.error(er)
          })
          return
        }
        deductMoney(that.formData).then(res => {
          that.$opsMessage.success()
          that.goldInputBoxVisible = false
          that.listLoading = false
          that.renderData(true)
        }).catch(er => {
          that.listLoading = false
          that.$opsMessage.success()
          console.error(er)
        })
      })
    },
    transferSubmit() {
      const that = this

      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        that.listLoading = true
        transferMoney(that.transferFormData).then(res => {
          that.$opsMessage.success()
          that.transferVisible = false
          that.$refs.transferAccountInput.clearValue()
          that.listLoading = false
          that.renderData(true)
        }).catch(er => {
          that.listLoading = false
          console.error(er)
        })
      })
    },
    clickLoadMore() {
      const that = this
      that.loadMoreLoading = true
      that.renderData()
    },
    exprotExcel() {
      const that = this
      if (that.exportLoading) {
        return
      }
      that.exportLoading = true
      exprotBank({ sysOrigin: that.listQuery.sysOrigin }).then(res => {
        that.exportLoading = false
      }).catch(er => {
        that.exportLoading = false
        this.$opsMessage.fail(this.$t('pages.userBankAccounts.message.downloadFailed'))
      })
    },
    uploadTemplate(value) {
      const that = this
      that.uploadLoding = true
      that.loading = this.$loading({
        lock: true,
        text: this.$t('pages.userBankAccounts.message.importing'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      var form = new FormData()
      form.append('file', value.file)
      confirmImport(form).then(res => {
        if (res.status) {
          this.uploadSuccess()
        }
      }).catch(er => {
        this.messageError()
      })
    },
    uploadSuccess() {
      const that = this
      setTimeout(() => {
          that.$message({ type: 'success', message: this.$t('pages.userBankAccounts.message.importSuccess') })
          that.uploadDialogVisible = false
          that.uploadLoding = false
          that.loading.close()
          that.renderData(true)
      }, 1000)
    },
    messageError() {
      const that = this
      that.$message({ type: 'error', message: this.$t('pages.userBankAccounts.message.importFailed') })
      that.uploadLoding = false
      that.loading.close()
      that.renderData(true)
    }
  }
}
</script>
<style scoped lang="scss">

.load-more {
  padding: 20px;
  text-align: center;
}
</style>
