<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <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="创建时间">
                <rangeDate ref="rangeDate" :value="creatDate" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="收款单号">
                <a-input id="financialCollectionList-bookNo" v-model.trim="queryParam.bookNo" allowClear placeholder="请输入收款单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="申请人">
                <employee style="width: 100%;" id="financialCollectionList-Employee" placeholder="请选择申请人" v-model="queryParam.applyPersonSn"></employee>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="收款事由">
                  <a-input id="financialCollectionList-bookReason" v-model.trim="queryParam.bookReason" allowClear placeholder="请输入收款事由"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="审核时间">
                  <rangeDate ref="rangeAuditDate" :value="auditDate" @change="dateAuditChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="关联单据单号">
                  <a-input id="financialCollectionList-dispatchBillNo" v-model.trim="queryParam.dispatchBillNo" allowClear placeholder="请输入关联单据单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="付款方类型">
                  <v-select
                    v-model="queryParam.payerType"
                    ref="payType"
                    code="PAYER_TYPE"
                    placeholder="请选择付款方式类型"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="付款方">
                  <a-input id="financialCollectionList-payerNames" v-model.trim="queryParam.payerName" allowClear placeholder="请输入付款方"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="状态">
                  <v-select
                    v-model="queryParam.status"
                    ref="status"
                    id="financialCollectionList-status"
                    code="FINANCE_BOOK_STATE"
                    placeholder="请选择状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-item label="客服">
                  <customerService ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="financialCollectionList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="financialCollectionList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false" class="financialCollectionList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator">
          <div class="flex-center">
            <a-button type="primary" v-if="$hasPermissions('B_fc_new')" @click="handleAdd">新增</a-button>
            <div class="tongji-bar">
              订单总金额：{{ toThousands(countData&&countData.orderTotalAmount||0) }}；
              收款总金额：{{ toThousands(countData&&countData.receiptTotalAmount||0) }}；
              使用授信总金额：{{ toThousands(countData&&countData.useTotalAmount||0) }}；
              授信还款总金额：{{ toThousands(countData&&countData.payTotalAmount||0) }}；
              余款抵扣总金额：{{ toThousands(countData&&countData.balanceTotalAmount||0) }}；
              跨月打款总金额：{{ toThousands(countData&&countData.nextMonthTotalAmount||0) }}；
              特殊申请发货总金额：{{ toThousands(countData&&countData.specialTotalAmount||0) }}；
            </div>
          </div>
          <div></div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+80+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :pageSize="30"
          :defaultLoadData="false"
          bordered>
          <!-- 单号 -->
          <template slot="bookNo" slot-scope="text, record">
            <span v-if="$hasPermissions('B_fc_detail')" class="link-bule" @click="handleDetail(record)">{{ record.bookNo }}</span>
            <span v-else>{{ record.bookNo }}</span>
          </template>
          <!-- 关联备货单 -->
          <template slot="dispatchNum" slot-scope="text, record">
            <span v-if="$hasPermissions('B_glDispatch')&&record.dispatchNum" class="link-bule" @click="handleBhDetail(record)">{{ record.dispatchNum }}单</span>
            <span v-else>--</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              v-if="record.status=='WAIT_SUBMIT'&&$hasPermissions('B_fc_edit')"
              size="small"
              type="link"
              class="button-info"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-button
              v-if="record.status=='WAIT_SUBMIT'&&$hasPermissions('B_fc_del')"
              size="small"
              type="link"
              class="button-error"
              @click="handleDel(record)"
            >
              删除
            </a-button>
            <a-button
              v-if="record.status!='WAIT_SUBMIT'&&$hasPermissions('B_fc_Audit')"
              size="small"
              type="link"
              class="button-info"
              @click="handleSH(record)"
            >
              审核进度
            </a-button>
            <a-button
              v-if="record.status=='AUDIT_REJECT'&&$hasPermissions('B_againEditFc')"
              size="small"
              type="link"
              class="button-info"
              @click="againEdit(record)"
            >
              再次编辑
            </a-button>
            <a-button
              v-if="record.status=='AUDIT_PASS'&&$hasPermissions('B_editFcDetail')"
              size="small"
              type="link"
              class="button-info"
              @click="editDetail(record)"
            >
              修改明细
            </a-button>
          </template>
        </s-table>
      </a-spin>
      <!-- 审核进度 -->
      <verifyModal v-drag :openModal="openModal" :itemId="itemId" :itemSn="itemSn" @close="openModal=false"></verifyModal>
      <!-- 基础信息 -->
      <baseModal v-drag :show="baseModal" @cancel="baseModal=false"></baseModal>
      <!-- 关联备货单 -->
      <dispatchModal v-drag ref="openDisModal" :openModal="openDisModal" :itemSn="itemSn" @close="openDisModal=false"></dispatchModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import baseModal from './baseModal.vue'
import employee from '../../expenseManagement/expenseReimbursement/employee.js'
import verifyModal from './verifyModal.vue'
import dispatchModal from './dispatchModal.vue'
import customerService from '@/views/common/customerService'
import { financeBookQueryPage, financeBookDeleteBySn, financeBookDgainEditBySn, financeBookQueryCount } from '@/api/financeBook.js'
export default {
  name: 'FinancialCollectionList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, baseModal, employee, verifyModal, dispatchModal, customerService },
  data () {
    return {
      spinning: false,
      openModal: false,
      openDisModal: false,
      baseModal: false,
      tableHeight: 0,
      queryParam: { //  查询条件
        payerType: '',
        beginDate: '',
        endDate: '',
        bookNo: '',
        dispatchBillNo: '',
        auditBeginDate: '',
        auditEndDate: '',
        applyPersonSn: undefined,
        bookReason: '',
        status: undefined,
        payerName: '',
        bizUserSn: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      creatDate: [], //  创建时间
      auditDate: [], // 审核时间
      advanced: true,
      itemSn: null,
      itemId: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return financeBookQueryPage(params).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.total = data.count || 0
            this.disabled = false
          }
          this.spinning = false
          this.getCount(params)
          return data
        })
      },
      total: 0, // 合计
      countData: null
    }
  },
  // 根据权限显示列表字段
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '收款单号', scopedSlots: { customRender: 'bookNo' }, width: '8%', align: 'center' },
        { title: '关联单据', scopedSlots: { customRender: 'dispatchNum' }, width: '6%', align: 'center' },
        { title: '申请人', dataIndex: 'applyPersonName', align: 'center', width: '5%', customRender: function (text) { return text || '--' } },
        { title: '收款事由', dataIndex: 'bookReason', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '付款方', dataIndex: 'payerName', width: '9%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '订单总金额', dataIndex: 'orderTotalAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '收款总金额', dataIndex: 'receiptTotalAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '使用授信总金额', dataIndex: 'useTotalAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '授信还款总金额', dataIndex: 'payTotalAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '余款抵扣总金额', dataIndex: 'balanceTotalAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '跨月打款总金额', dataIndex: 'nextMonthTotalAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '特殊申请发货总金额', dataIndex: 'specialTotalAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '审核时间', dataIndex: 'auditDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '状态', dataIndex: 'statusDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    getCount (params) {
      financeBookQueryCount(params).then(res => {
        this.countData = res.data
      })
    },
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0] ? date[0] : ''
      this.queryParam.endDate = date[1] ? date[1] : ''
    },
    //  审核时间  change
    dateAuditChange (date) {
      this.queryParam.auditBeginDate = date[0] ? date[0] : ''
      this.queryParam.auditEndDate = date[1] ? date[1] : ''
    },
    //  重置
    resetSearchForm () {
      this.creatDate = []
      this.$refs.rangeDate.resetDate(this.creatDate)
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.auditDate = []
      if (this.advanced) {
        this.$refs.rangeAuditDate.resetDate(this.auditDate)
      }
      this.queryParam.payerName = ''
      this.queryParam.auditBeginDate = ''
      this.queryParam.auditEndDate = ''
      this.queryParam.bookNo = ''
      this.queryParam.dispatchBillNo = ''
      this.queryParam.applyPersonSn = undefined
      this.queryParam.bookReason = ''
      this.queryParam.status = undefined
      this.queryParam.payerType = undefined
      this.queryParam.bizUserSn = undefined
      this.$refs.table.refresh(true)
    },
    // 新增
    handleAdd () {
      this.baseModal = true
    },
    // 查看关联备货单
    handleBhDetail (row) {
      this.openDisModal = true
      this.itemSn = row.bookSn
      this.$nextTick(() => {
        this.$refs.openDisModal.setDetail(row)
      })
    },
    // 详情
    handleDetail (row) {
      this.$router.push({ name: 'financialCollectionDetail', params: { sn: row.bookSn } })
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({ name: 'financialCollectionEdit', params: { sn: row.bookSn, type: 0 } })
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          financeBookDeleteBySn({ bookSn: row.bookSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 审核进度
    handleSH (row) {
      this.openModal = true
      this.itemSn = row.bookSn
      this.itemId = row.id
    },
    // 修改明细
    editDetail (row) {
      this.$router.push({ name: 'financialCollectionEdit', params: { sn: row.bookSn, type: 1 } })
    },
    // 再次编辑
    againEdit (row) {
      const _this = this
      this.$confirm({
        title: '操作提示',
        content: '系统将自动生成一个新的财务收款单，与原审核不通过的单据内容相同。您可以对新单据进行编辑、提交等操作，原单据保持不变，确认操作吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          financeBookDgainEditBySn({ bookSn: row.bookSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
            _this.spinning = false
          })
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 250
    }
  },
  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.pageInit()
      this.resetSearchForm()
    }
  },
  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>

<style lang="less">
  .financialCollectionList-wrap{
    .active{
      color: #ed1c24;
      cursor: pointer;
    }
    .common{
      color: rgba(0, 0, 0);
    }
  }
</style>
