<template>
  <a-card size="small" :bordered="false" class="finacialPay-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 标签页 -->
      <a-tabs type="card" size="small" v-model="queryParam.bizType" @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="searchForm">
          <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="createDate" @change="createDateChange" />
                </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="searchForm()" :disabled="disabled" id="finacialPay-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm()" :disabled="disabled" id="finacialPay-reset">重置</a-button>
                <a @click="advanced = !advanced" style="margin-left: 5px">
                  {{ 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="enableFundAccount ? handleSettleAcountPay(null,1) : handlePayment()">批量付款</a-button>
        <span style="margin-left: 8px" v-if="$hasPermissions('B_financialPaymentPl')">
          <template v-if="rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length>0">{{ `已选 ${rowSelectionInfo.selectedRowKeys.length} 项` }}</template>
          <template v-if="selectTotalAmount">，合计￥{{ selectTotalAmount }}</template>
        </span>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="record => record.id"
        :row-selection="$hasPermissions('B_financialPaymentPl') ? { columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: record.settleState == 'SETTLED' } }) } : null"
        @rowSelection="rowSelectionFun"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered
      >
        <!-- 关联单号 -->
        <template slot="bizNo" slot-scope="text, record">
          <span class="table-td-link" @click="handleDetail(record)">{{ record.bizNo }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-primary"
            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-error"
            :loading="loading"
            v-else-if="record.settleState != 'SETTLED' && $hasPermissions('B_financialPaymentSing')"
            @click="enableFundAccount ? handleSettleAcountPay(record,0) : 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" />
    <!-- 收付款弹框 -->
    <settleModal ref="settleModal" @ok="settleAcountPay" :openModal="openSettleModal" @close="openSettleModal=false"></settleModal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { mapActions } from 'vuex'
import { STable, VSelect } from '@/components'
import detailModal from './detailModal.vue'
import settleModal from '../settleModal/settleModal.vue'
import { settlePayQuery, queryByTypeSum, settlePayMoney, settlePayQuerySum } from '@/api/settlePay.js'
import rangeDate from '@/views/common/rangeDate.vue'
export default {
  name: 'FinancialPaymentList',
  components: { STable, VSelect, detailModal, rangeDate, settleModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, //  高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 详情弹框
      openSettleModal: false, // 打开付款弹框
      enableFundAccount: false, // 是否开启资金账户管理
      tableHeight: 0,
      curBizType: 'ALL',
      // 查询参数
      queryParam: {
        bizType: 'ALL',
        settleNo: '',
        bizNo: '',
        settleClientName: '',
        billState: '',
        auditBeginDate: '',
        auditEndDate: ''
      },
      // 总计
      totalData: {
        settledAmount: 0,
        totalAmount: 0,
        unsettleAmount: 0,
        count: 0
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '付款单号', dataIndex: 'settleNo', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '关联单号', dataIndex: 'bizNo', scopedSlots: { customRender: 'bizNo' }, width: '14%', align: 'center' },
        { title: '商户名称', dataIndex: 'settleClientName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '应付金额', dataIndex: 'totalAmount', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '已付金额', dataIndex: 'settledAmount', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '待付金额', dataIndex: 'unsettleAmount', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '单据类型', dataIndex: 'bizName', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '付款方式', dataIndex: 'settleStyleName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '创建时间', dataIndex: 'createDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '付款时间', dataIndex: 'settleTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '5%', align: 'center' }
      ],
      loading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return settlePayQuery(Object.assign(parameter, this.queryParam)).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.totalData.count = data.count || 0
            // 查询总计
            this.settlePayQuerySum(Object.assign(parameter, this.queryParam))
          }
          this.spinning = false
          return data
        })
      },
      tabPaneData: [],
      rowSelectionInfo: null
    }
  },
  computed: {
    selectTotalAmount () {
      let ret = 0
      if (this.rowSelectionInfo && this.rowSelectionInfo.selectedRows) {
        this.rowSelectionInfo.selectedRows.map(item => {
          ret = ret + item.unsettleAmount
        })
      }
      return ret ? Number(ret).toFixed(2) : 0
    }
  },
  methods: {
    handleDetail (row) {

    },
    ...mapActions(['GetSettleAccountState']),
    // 表格选中项
    rowSelectionFun (obj) {
      console.log(obj)
      this.rowSelectionInfo = obj || null
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.auditBeginDate = date[0]
      this.queryParam.auditEndDate = date[1]
    },
    createDateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 总计
    settlePayQuerySum (params) {
      settlePayQuerySum(params).then(res => {
        if (res.status == 200) {
          this.totalData = Object.assign(this.totalData, res.data)
          const tab = this.tabPaneData.find(item => item.bizType == this.queryParam.bizType)
          tab.countNum = this.totalData.count || 0
        }
      })
    },
    // 获取类型
    queryByTypeSum () {
      queryByTypeSum({}).then(res => {
        if (res.data && res.status == 200) {
          this.tabPaneData = res.data
          if (this.curBizType == 'ALL') {
            this.queryParam.bizType = res.data[0].bizType
          }
          this.$refs.table.refresh(true)
        }
      })
    },
    //  凭证弹框
    handleVoucher (row) {
      this.$refs.detailModal.getDetail(row.id)
      this.openModal = true
    },
    // 开启结算账户功能付款, type:0 单条付款，1 批量付款
    handleSettleAcountPay (row, type) {
      this.openSettleModal = true
      const data = {
        totalAmount: type ? this.selectTotalAmount : row && row.unsettleAmount || 0,
        settleClientName: type ? '' : row && row.settleClientName || '',
        title: '付款',
        type,
        row
      }
      this.$nextTick(() => {
        this.$refs.settleModal.setData(data)
      })
    },
    // 去付款
    settleAcountPay (form, data) {
      const _this = this
      const params =
      {
        'settleIds': data.type ? _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys : [data.row.id]
      }
      // 资金管理开启
      if (this.enableFundAccount) {
        params.settleStyleSn = form.settleStyleSn
        params.settleAccountSn = form.settleAccountSn
      }

      _this.loading = true
      _this.spinning = true
      settlePayMoney(params).then(res => {
        _this.loading = false
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
          _this.$refs.table.clearSelected() // 清空表格选中项
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    // 付款
    handlePay (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认付款吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.settleAcountPay(null, { type: 0, row: row })
        }
      })
    },
    // 选择类型
    handleTabChange (key) {
      this.queryParam.bizType = key
      this.$refs.table.refresh(true)
      this.curBizType = key
    },
    // 批量付款
    handlePayment () {
      if (!this.rowSelectionInfo || (this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      const _this = this
      this.$confirm({
        title: '提示',
        content: <div><p style="margin-top:20px;">合计金额￥{ this.selectTotalAmount } </p><p>确认批量付款吗？</p></div>,
        centered: true,
        closable: true,
        onOk () {
          _this.settleAcountPay(null, { type: 1, row: null })
        }
      })
    },
    // 查询
    searchForm () {
      this.$refs.table.clearSelected() // 清空表格选中项
      this.$refs.table.refresh(true)
    },
    //  重置
    resetSearchForm () {
      this.resetData()
      this.$refs.table.refresh(true)
    },
    // 重置数据
    resetData () {
      if (this.advanced) {
        this.$refs.rangeDate.resetDate()
        this.$refs.createDate.resetDate()
      }
      this.$refs.table.clearSelected() // 清空表格选中项
      this.queryParam = {
        bizType: this.curBizType,
        settleNo: '',
        bizNo: '',
        settleClientName: '',
        billState: '',
        beginDate: '',
        endDate: '',
        auditBeginDate: '',
        auditEndDate: ''
      }
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.queryByTypeSum()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 330
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.resetData()
      this.pageInit()
    }
  },
  activated () {
    // 是否从首页点击进入
    const isHomeNav = this.getIsHomeNav()[this.$route.name]
    console.log(this.getIsHomeNav(), isHomeNav, this.$route.name)
    // 待办查询
    if (isHomeNav && isHomeNav.type == 'todo') {
      this.curBizType = isHomeNav.pageParams.bizType
      this.resetData()
      this.queryParam = Object.assign(this.queryParam, isHomeNav.pageParams)
      this.$refs.createDate.resetDate([this.queryParam.beginDate, this.queryParam.endDate])
      this.pageInit()
    } else {
      // 如果是新页签打开，则重置当前页面
      if (this.$store.state.app.isNewTab) {
        this.curBizType = 'ALL'
        this.resetData()
        this.pageInit()
      }
    }

    // 结算账户状态查询
    if (this.$hasPermissions('M_fundAccountList') && this.$hasPermissions('B_fundAccountEnable')) {
    	this.GetSettleAccountState().then(res => {
    	  if (res.status == 200) {
    		 this.enableFundAccount = res.data.functionEnableFlag == 1
    	  }
    	})
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less">
	.finacialPay-wrap{
		.finacialPay-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-nav-container{
      height: 30px!important;
		}
    .finacialPay-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active{
      height: 30px!important;
    }
    .finacialPay-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab{
      line-height: 26px!important;
      height: 30px!important;
    }
	}
</style>
