<template>
  <div class="app-container">
    <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>

      <div class="filter-item">
        <account-input v-model="listQuery.userId" :sys-origin="listQuery.sysOrigin" placeholder="用户ID" />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        :disabled="exportLoading"
        :loading="exportLoading"
        @click="exprotExcel"
      >
        导出
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        @click="readExcel"
      >
        导入<i class="el-icon-upload el-icon--right" />
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
    >
      <el-table-column type="index" width="50" label="No" />
      <el-table-column prop="sysOrigin" label="系统" 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="用户" 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="获得总额" align="center" min-width="100" />
      <el-table-column prop="consumptionPoints" label="消费总额" align="center" min-width="100" />
      <el-table-column prop="balance" label="余额" align="center" min-width="100" />
      <el-table-column prop="createTime" label="创建时间" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.updateTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" 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)">发送</el-dropdown-item>
              <el-dropdown-item @click.native="showGoldInputBox(scope.row, false)">扣除</el-dropdown-item>

              <el-dropdown-item @click.native="showTransferBox(scope.row)">转账</el-dropdown-item>
              <el-dropdown-item @click.native="clickRunningWater(scope.row)">流水</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">已加载全部</span>
      <el-button v-else size="mini" :disabled="loadMoreLoading" :loading="loadMoreLoading" @click="clickLoadMore">加载更多</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=" 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="金额" prop="quantity">
            <el-input
              v-model.trim="formData.quantity"
              :placeholder="'请输入' + (type ? '发送' : '扣除') + '金额'"
            />
          </el-form-item>

          <el-form-item label="对内备注" prop="remark">
            <el-input
              v-model.trim="formData.remark"
              placeholder="请输入对内备注"
            />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="hideGoldInputBox()">
            取消
          </el-button>
          <el-button
            v-loading="listLoading"
            type="primary"
            @click="goldSubmit()"
          >
            提交
          </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="转账"
        :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="收款人">
            <account-input ref="transferAccountInput" v-model="transferFormData.acceptUserId" :sys-origin="transferFormData.sysOrigin" placeholder="用户账号" />
          </el-form-item>

          <el-form-item label="金额" prop="quantity">
            <el-input
              v-model.trim="transferFormData.quantity"
              :placeholder="'请输入转账金额'"
            />
          </el-form-item>

          <el-form-item label="对内备注" prop="remark">
            <el-input
              v-model.trim="transferFormData.remark"
              placeholder="请输入对内备注"
            />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="hideTransferBox()">
            取消
          </el-button>
          <el-button
            v-loading="listLoading"
            type="primary"
            @click="transferSubmit()"
          >
            提交
          </el-button>
        </div>
      </el-dialog>
    </div>

    <div class="excel-import">
      <el-dialog 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>请选择导入文件：</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">模板下载</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">将文件拖到此处，或<em>点击上传</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() {
    const commonRules = [
      { required: true, message: '必填字段', trigger: 'blur' }
    ]
    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: ''
      },
      formRules: {
        userId: commonRules,
        quantity: { required: true, message: '必填字段不可为空', trigger: 'blur' },
        sysOrigin: commonRules
      },
      transferFormRules: {
        userId: commonRules,
        acceptUserId: commonRules,
        quantity: { required: true, message: '必填字段不可为空', trigger: 'blur' },
        sysOrigin: commonRules
      },
      listLoading: false,
      list: [],
      notData: false,
      loadMoreLoading: false,
      formEditVisable: false,
      exportLoading: false
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  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
    },
    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('下载失败！')
      })
    },
    uploadTemplate(value) {
      const that = this
      that.uploadLoding = true
      that.loading = this.$loading({
        lock: true,
        text: '正在导入...',
        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: '导入成功' })
          that.uploadDialogVisible = false
          that.uploadLoding = false
          that.loading.close()
          that.renderData(true)
      }, 1000)
    },
    messageError() {
      const that = this
      that.$message({ type: 'error', message: '导入失败，请重试！' })
      that.uploadLoding = false
      that.loading.close()
      that.renderData(true)
    }
  }
}
</script>
<style scoped lang="scss">

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