<template>
  <a-card size="small" :bordered="false" class="withdrawalManagementNew-wrap jg-page-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :xl="6" :lg="6" :md="12" :sm="24">
              <a-form-item label="提现时间">
                <rangeDate id="withdrawal-time" ref="rangeDate" v-model="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="6" :md="6" :sm="6">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="withdrawal-refresh" >查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="withdrawal-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div style="margin:10px 0">
        <div style="margin:10px 0">
          <p>可提现金额：<strong style="color:#ed1c24;">{{ pageInfo&&(pageInfo.activeAmount||pageInfo.activeAmount==0)?toThousands(pageInfo.activeAmount):'--' }}</strong></p>
          <p>账户总金额：{{ pageInfo&&(pageInfo.amount||pageInfo.amount==0)?toThousands(pageInfo.amount):'--' }}（包含到账金额：<span>{{ pageInfo&&(pageInfo.dzAmount||pageInfo.dzAmount==0)?toThousands(pageInfo.dzAmount):'--' }}</span>，在途金额：{{ pageInfo&&(pageInfo.floatAmount||pageInfo.floatAmount==0)?toThousands(pageInfo.floatAmount):'--' }}）</p>
          <p v-if="pageInfo&&pageInfo.freezeRuleAmount">保证金：{{ toThousands(pageInfo.freezeRuleAmount) }}（已冻结金额：{{ pageInfo&&(pageInfo.freezeAmount||pageInfo.freezeAmount==0)?toThousands(pageInfo.freezeAmount):'--' }}）</p>
          <p style="margin-top:10px;">（提示：①提现手续费为0.5元/笔；②资金到账周期：线上支付订单出库后自然日+10天；③订单被审核不通过或修理厂取消订单后，将在1-3个工作日原路返回对应金额）</p>
        </div>
        <a-button
          id="withdrawal-tixian"
          v-if="$hasPermissions('B_withdrawalAudit')"
          type="primary"
          class="button-primary"
          @click="handleTX">申请提现</a-button>
        <a-button id="withdrawal-zhangdan" class="button-info" v-if="$hasPermissions('B_billFlow')" @click="showBillFlowModal=true">账单流水</a-button>
      </div>
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+77+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y:tableHeight }"
        :defaultLoadData="false"
        bordered>
      </s-table>
    </a-spin>
    <!-- 申请提现 -->
    <applyWithdrawal :pageInfo="pageInfo" :isOpenModal="showModal" @close="showModal=false" @refresh="handleSearch"></applyWithdrawal>
    <!-- 交易流水 -->
    <billFlowModal :openModal="showBillFlowModal" @close="showBillFlowModal=false"></billFlowModal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable } from '@/components'
import applyWithdrawal from './applyWithdrawal.vue'
import billFlowModal from './billFlowModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import Decimal from 'decimal.js'
// 接口
import { queryMerchantCashOutPage, merchantCashOutDetail } from '@/api/merchantNew'
export default {
  mixins: [commonMixin],
  components: { STable, applyWithdrawal, billFlowModal, rangeDate },
  data () {
    const _this = this
    return {
      spinning: false,
      disabled: false,
      tableHeight: 0, // 表格高度
      showModal: false, // 是否显示申请提现弹窗
      showBillFlowModal: false, // 打开交易流水 弹窗
      time: [], // 提现时间
      pageInfo: null, // 详情信息
      errorFlag: false, // 经销商未设置结算账户时，申请提现按钮不能点击
      queryParam: {
        beginDate: '', // 开始时间
        endDate: '' // 结束时间
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '提现单号', dataIndex: 'cashOutNo', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '提现时间', dataIndex: 'cashOutDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '申请提现金额', dataIndex: 'amount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '开户名', dataIndex: 'bankAccount', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '开户银行', dataIndex: 'bankName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '银行卡号', dataIndex: 'bankCard', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '提现人', dataIndex: 'operName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '状态', dataIndex: 'stateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备注', dataIndex: 'remarks', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const _this = this
        _this.disabled = true
        _this.spinning = true
        const paramsPage = Object.assign(parameter, this.queryParam) //  有分页
        paramsPage.merchantSn = this.pageInfo ? this.pageInfo.merchantSn : ''
        paramsPage.dealerSn = _this.$store.state.user.authOrgs[0].orgSn
        paramsPage.merchantType = 'DEALER'
        return queryMerchantCashOutPage(paramsPage).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    // 时间改变
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 获取详情信息
    getPageInfo () {
      merchantCashOutDetail({}).then(res => {
        if (res.status == 200) {
          this.pageInfo = res.data
          this.errorFlag = false
        } else {
          this.pageInfo = null
          this.errorFlag = true
        }
      })
    },
    // 查询
    handleSearch () {
      this.getPageInfo()
      this.$refs.table.refresh(true)
    },
    // 重置
    resetSearchForm () {
      this.time = []
      this.$refs.rangeDate.resetDate(this.time)
      this.$refs.table.refresh(true)
    },
    // 申请提现
    handleTX () {
      if (this.errorFlag) {
        this.$message.warning('请先设置结算账户！')
        return
      }
      this.showModal = true
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 330
    },
    // 页面初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      _this.getPageInfo()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      setTimeout(() => {
        _this.setTableH()
      }, 400)
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
