<template>
  <a-card size="small" :bordered="false" class="finacialPay-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 标签页 -->
      <a-tabs type="card" default-active-key="0" @change="handleTabChange" class="finacialPay-tabs">
        <a-tab-pane v-for="item in tabPaneData" :key="item.bizType">
          <span slot="tab">{{ item.bizName }}({{ item.countNum }})</span>
        </a-tab-pane>
      </a-tabs>
      <!-- 搜索条件 -->
      <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 :md="6" :sm="24">
              <a-form-item label="付款单号"><a-input id="finacialPay-settleNo" v-model.trim="queryParam.settleNo" allowClear placeholder="请输入付款单号" /></a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="关联单号"><a-input id="finacialPay-bizNo" v-model.trim="queryParam.bizNo" allowClear placeholder="请输入关联单号" /></a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商户名称">
                <a-input id="finacialPay-settleClientName" v-model.trim="queryParam.settleClientName" allowClear placeholder="请输入商户名称" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="单据状态">
                  <v-select
                    v-model="queryParam.billState"
                    ref="settleState"
                    id="finacialPay-settleState"
                    code="SETTLE_PAY_STATUS"
                    placeholder="请选择单据状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="审核时间">
                  <rangeDate ref="rangeDate" @change="dateChange" />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="finacialPay-refresh">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm()" :disabled="disabled" id="finacialPay-reset">重置</a-button>
                <a @click="advanced = !advanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          共
          <strong>{{ totalData&&(totalData.count || totalData.count==0) ? totalData.count : '--' }}</strong>
          条记录，应付金额合计
          <strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? '￥'+totalData.totalAmount : '--' }}</strong>
          ，其中已付金额
          <strong>{{ totalData&&(totalData.settledAmount || totalData.settledAmount==0) ? '￥'+totalData.settledAmount : '--' }}</strong>
          ，待付金额
          <strong>{{ totalData&&(totalData.unsettleAmount || totalData.unsettleAmount==0) ? '￥'+totalData.unsettleAmount : '--' }}</strong>
        </div>
      </a-alert>
      <div v-if="$hasPermissions('B_financialPaymentPl')" style="margin-bottom: 10px">
        <a-button type="primary" id="finacialPay-export" :loading="loading" @click="handlePayment">批量付款</a-button>
        <span style="margin-left: 8px" v-if="$hasPermissions('B_financialPaymentPl')">
          <template v-if="hasSelected">
            {{ `已选 ${selectedRowKeys.length} 项` }}
          </template>
        </span>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :row-selection="$hasPermissions('B_financialPaymentPl') ? rowSelection : null"
        :rowKey="record => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1660, y: tableHeight }"
        bordered
      >
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-info"
            v-if="record.settleState == 'SETTLED' && $hasPermissions('B_financialPaymentDetail')"
            @click="handleVoucher(record)"
            id="finacialPay-voucher-btn">凭证</a-button>
          <a-button
            size="small"
            type="link"
            class="button-warning"
            :loading="loading"
            v-else-if="record.settleState != 'SETTLED' && $hasPermissions('B_financialPaymentSing')"
            @click="handlePay(record)"
            id="finacialPay-pay-btn">付款</a-button>
          <span v-else>--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 详情 -->
    <detail-modal :openModal="openModal" ref="detailModal" @close="openModal = false" />
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import detailModal from './detailModal.vue'
import { settlePayQuery, queryByTypeSum, settlePayMoney, settlePayQuerySum } from '@/api/settlePay.js'
import rangeDate from '@/views/common/rangeDate.vue'
export default {
  components: { STable, VSelect, detailModal, rangeDate },
  data () {
    return {
      spinning: false,
      advanced: true, //  高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 详情弹框
      tableHeight: 0,
      curBizType: '',
      // 查询参数
      queryParam: {
        bizType: 'ALL',
        settleNo: '',
        bizNo: '',
        settleClientName: '',
        billState: '',
        auditBeginDate: '',
        auditEndDate: ''
      },
      // 总计
      totalData: {
        settledAmount: 0,
        totalAmount: 0,
        unsettleAmount: 0,
        count: 0
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '付款单号', dataIndex: 'settleNo', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '关联单号', dataIndex: 'bizNo', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户名称', dataIndex: 'settleClientName', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '应付金额', dataIndex: 'totalAmount', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '已付金额', dataIndex: 'settledAmount', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '待付金额', dataIndex: 'unsettleAmount', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '付款类型', dataIndex: 'bizName', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '付款方式', dataIndex: 'settleStyleName', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditTime', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '付款时间', dataIndex: 'settleTime', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, align: 'center', fixed: 'right' }
      ],
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return settlePayQuery(Object.assign(parameter, this.queryParam)).then(res => {
          const 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
          this.totalData.count = data.count || 0
          // 查询总计
          this.settlePayQuerySum(Object.assign(parameter, this.queryParam))
          return data
        })
      },
      tabPaneData: []
    }
  },
  computed: {
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    rowSelection () {
      if (this.$hasPermissions('B_financialPaymentPl')) {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: (selectedRowKeys, selectedRows) => {
            this.selectedRowKeys = selectedRowKeys
          },
          onSelect: (record, selected, selectedRows, nativeEvent) => {
            this.onSelectChange(record, selected, selectedRows, nativeEvent)
          },
          onSelectAll: (selected, selectedRows, changeRows) => {
            this.onSelectAllChange(selected, selectedRows, changeRows)
          },
          getCheckboxProps: record => ({
            props: {
              disabled: record.settleState == 'SETTLED'
            }
          })
        }
      } else {
        return null
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.queryByTypeSum()
    })
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.auditBeginDate = date[0]
      this.queryParam.auditEndDate = date[1]
    },
    // 总计
    settlePayQuerySum (params) {
      settlePayQuerySum(params).then(res => {
        if (res.status == 200) {
          this.totalData = Object.assign(this.totalData, res.data)
        }
      })
    },
    // 获取类型
    queryByTypeSum () {
      queryByTypeSum({}).then(res => {
        if (res.data && res.status == 200) {
          this.tabPaneData = res.data
          this.queryParam.bizType = res.data[0].bizType
        }
      })
    },
    //  凭证弹框
    handleVoucher (row) {
      this.$refs.detailModal.getDetail(row.id)
      this.openModal = true
    },
    // 付款
    handlePay (row) {
      this.loading = true
      this.spinning = true
      settlePayMoney([row.id]).then(res => {
        this.loading = false
        if (res.status == 200) {
          this.$message.success(res.message)
          this.selectedRowKeys = []
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 选择类型
    handleTabChange (key) {
      this.queryParam.bizType = key
      this.$refs.table.refresh(true)
      this.curBizType = key
    },
    // 批量付款
    handlePayment () {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      this.loading = true
      this.spinning = true
      settlePayMoney(this.selectedRowKeys).then(res => {
        this.loading = false
        if (res.status == 200) {
          this.$message.success(res.message)
          this.selectedRowKeys = []
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    //  重置
    resetSearchForm () {
      if (this.advanced) {
        this.$refs.rangeDate.resetDate()
      }
      this.queryParam = {
        bizType: this.curBizType,
        settleNo: '',
        bizNo: '',
        settleClientName: '',
        billState: '',
        auditBeginDate: '',
        auditEndDate: ''
      }
      this.$refs.table.refresh(true)
    },
    onSelectChange (record, selected, selectedRows, nativeEvent) {
      if (selected) { //  选择
        this.selectedRows.push(record)
      } else { //  取消
        this.selectedRows = selectedRows
      }
    },
    // 本页全选/取消全选
    onSelectAllChange (selected, selectedRows, changeRows) {
      const _this = this
      if (selected) { //  选择
        this.selectedRows = [...this.selectedRows, ...changeRows]
      } else { //  取消
        const arrId = []
        this.selectedRows.map((item, index) => {
          this.selectedRows.map((subItem, ind) => {
            if (item.id == subItem.id) {
              arrId.push(index)
            }
          })
        })
        arrId.map((item, index) => {
          _this.selectedRows = _this.selectedRows.slice(item, item + 1)
        })
      }
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 330
    }
  },
  mounted () {
    const _this = this
    this.$nextTick(() => { // 页面渲染完成后的回调
      _this.setTableH()
      _this.queryByTypeSum()
    })
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      setTimeout(() => {
        _this.setTableH()
      }, 400)
    }
  }
}
</script>
