<template>
  <a-card size="small" :bordered="false" class="salesCollectionList-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 :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="客户名称">
                <dealerSubareaScopeList ref="settleClientName" id="salesCollectionList-settleClientName" @change="custChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="销售单号">
                <a-input id="salesCollectionList-bizNo" v-model.trim="queryParam.bizNo" allowClear placeholder="请输入销售单号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="备货单号">
                  <a-input id="salesCollectionList-dispatchBillNo" v-model.trim="queryParam.dispatchBillNo" allowClear placeholder="请输入备货单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="收货客户名称">
                  <dealerSubareaScopeList ref="receiverName" id="salesCollectionList-receiverName" @change="receiverChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="收款类型">
                  <v-select
                    v-model="queryParam.keepType"
                    ref="keepType"
                    id="salesCollectionList-keepType"
                    code="KEEP_TYPE"
                    placeholder="请选择收款类型"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="收款时间">
                  <rangeDate ref="rangeSettleDate" :value="settleDate" @change="dateSettleChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="收款方式">
                  <v-select
                    v-model="queryParam.settleStyle"
                    ref="settleStyle"
                    id="salesCollectionList-settleStyle"
                    code="SETTLE_STYLE"
                    placeholder="请选择收款方式"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务状态">
                  <v-select
                    v-model="queryParam.billStatus"
                    ref="billStatus"
                    id="salesCollectionList-billStatus"
                    code="DISPATCH_BILL_STATUS"
                    placeholder="请选择业务状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="财务状态">
                  <v-select
                    v-model="queryParam.settleState"
                    ref="settleState"
                    id="salesCollectionList-settleState"
                    code="FINANCIAL_RECEIVE_STATUS"
                    placeholder="请选择财务状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="单据状态">
                  <v-select
                    v-model="queryParam.voidFlag"
                    ref="voidFlag"
                    id="salesCollectionList-voidFlag"
                    code="VOID_FLAG"
                    placeholder="请选择单据状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="对单状态">
                  <v-select
                    v-model="queryParam.checkStatus"
                    ref="checkStatus"
                    id="salesCollectionList-checkStatus"
                    code="CHECK_STATUS"
                    placeholder="请选择对单状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="所在区域">
                  <subarea id="salesCollectionList-subarea" v-model="queryParam.subareaSn"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="地区" prop="dealerProvinceSn" style="margin: 0;">
                  <Area id="salesCollectionList-dealerProvinceSn" v-model="queryParam.dealerProvinceSn" placeholder="请选择省"></Area>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="searchTable" :disabled="disabled" id="salesCollectionList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="salesCollectionList-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>
      <!-- 操作按钮 -->
      <div class="table-operator" v-if="$hasPermissions('B_salesCollection_receipt')">
        <a-button type="primary" @click="handlePlColle()" class="button-error">批量收款</a-button>
        <span style="margin-left: 8px">
          <template v-if="rowSelectionInfo && rowSelectionInfo.selectedRowKeys.length>0">{{ `已选 ${rowSelectionInfo.selectedRowKeys.length} 项` }}</template>
        </span>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :row-selection="showSelect?{ columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: record.settleState=='FINISH' } })}:null"
        @rowSelection="rowSelectionFun"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 单号 -->
        <template slot="bizNo" slot-scope="text, record">
          <span v-if="$hasPermissions('B_salesDetail')" class="link-bule" @click="handleDetail(record,0)">{{ record.bizNo }}</span>
          <span v-else>{{ record.bizNo }}</span>
        </template>
        <!-- 下推单号 -->
        <template slot="dispatchBillNo" slot-scope="text, record">
          <span v-if="$hasPermissions('B_dispatchDetail')" class="link-bule" @click="handleDetail(record,1)">{{ record.dispatchBillNo }}</span>
          <span v-else>{{ record.dispatchBillNo || '--' }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="record.settleState=='WAIT' && record.voidFlag!=1 && $hasPermissions('B_salesCollection_receipt')"
            class="button-warning"
            @click="handleColle(record)"
            id="financialCollectionList-audit-btn">收款</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.settleState=='FINISH' && $hasPermissions('B_salesCollection_record')"
            class="button-success"
            @click="handleVoucher(record)"
            id="financialCollectionList-voucher-btn">凭证</a-button>
          <span v-if="record.settleState=='WAIT' && record.voidFlag==1">--</span>
        </template>
      </s-table>

      <!-- 销售收款凭证 -->
      <voucherModal v-drag ref="voucherModal" modalTit="销售收款凭证" :openModal="showVoucher" @cancel="closeVoucherModal"></voucherModal>

      <!-- 销售收款弹框 -->
      <commonModal
        :openModal="showSkModal"
        modalTit="销售收款"
        @cancel="closeColleModal"
        @ok="handleSaveColle"
      >
        <div style="text-align: center;line-height: 24px;">
          <div v-if="handlePlData.length">{{ handlePlData[0].settleClientName }}，共 {{ handlePlData && handlePlData.length }} 个备货单，合计 {{ $hasPermissions('B_salesCollection_receipt_salesPrice') ? toThousands(totalAmount) : '--' }} 元</div>
          <div style="padding: 15px 0;font-weight: bold;font-size:14px;">请确认收款类型变更为标记收款吗？</div>
        </div>
      </commonModal>

      <!-- 查看销售单或备货单详情 -->
      <commonModal
        :modalTit="detailType?'备货单详情':'销售单详情'"
        bodyPadding="10px"
        width="70%"
        :showFooter="false"
        :openModal="showDetailModal"
        @cancel="cancelDetail">
        <salesDetail v-if="detailType==0" ref="salesDetail" :bizSn="bizSn"></salesDetail>
        <dispatchDetail v-if="detailType==1" ref="dispatchDetail" :bizSn="bizSn"></dispatchDetail>
      </commonModal>
    </a-spin>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import commonModal from '@/views/common/commonModal.vue'
import salesDetail from '@/views/salesManagement/salesQuery/detail.vue'
import dispatchDetail from '@/views/salesManagement/pushOrderManagement/detail.vue'
import voucherModal from './voucherModal.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import { settleReceiptList, settleReceiptBatch } from '@/api/settleReceipt'

export default {
  name: 'SalesCollectionList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, rangeDate, commonModal, Area, voucherModal, dealerSubareaScopeList, salesDetail, dispatchDetail },
  data () {
    return {
      spinning: false,
      showDetail: false,
      showSkModal: false,
      showVoucher: false,
      showDetailModal: false,
      detailType: 2,
      bizSn: null,
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: '',
        endDate: '',
        bizNo: '',
        dispatchBillNo: '',
        beginDateSettle: '',
        endDateSettle: '',
        settleClientName: '',
        receiverName: '',
        dealerLevel: undefined,
        settleStyle: undefined,
        keepType: undefined,
        subareaSn: undefined,
        billStatus: undefined,
        settleState: undefined,
        voidFlag: undefined,
        dealerProvinceSn: undefined,
        dealerCitySn: undefined,
        dealerCountySn: undefined,
        checkStatus: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      auditDate: [], //  审核时间
      settleDate: [],
      advanced: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return settleReceiptList(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.total = data.count || 0
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      total: 0, // 合计
      rowSelectionInfo: null, // 批量选择的数据
      handlePlData: [], // 收款临时数据
      collectionType: 0 // 收款类型
    }
  },
  // 根据权限显示列表字段
  computed: {
    // 是否显示table选择框
    showSelect () {
      return this.$hasPermissions('B_salesCollection_receipt')
    },
    totalAmount () {
      let ret = 0
      this.handlePlData.map(item => {
        ret = ret + item.totalAmount
      })
      return ret.toFixed(2)
    },
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', scopedSlots: { customRender: 'bizNo' }, width: '9%', align: 'center' },
        { title: '备货单号', scopedSlots: { customRender: 'dispatchBillNo' }, width: '9%', align: 'center' },
        { title: '发货编号', dataIndex: 'sendNo', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '客户名称', dataIndex: 'settleClientName', align: 'left', width: '10%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '收货客户名称', dataIndex: 'receiverName', align: 'left', width: '10%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品款数', dataIndex: 'totalCategory', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品数量', dataIndex: 'qty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '总售价', dataIndex: 'totalAmount', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '收款类型', dataIndex: 'keepTypeDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '收款时间', dataIndex: 'settleTime', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '收款方式', dataIndex: 'settleStyleDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'settleStateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据状态', dataIndex: 'voidFlagDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '对单状态', dataIndex: 'checkStatusDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '4%', align: 'center' }
      ]
      if (this.$hasPermissions('M_salesCollectionList_salesPrice')) { //  售价权限
        arr.splice(9, 0, { title: '总售价', dataIndex: 'totalAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  methods: {
    custChange (val) {
      this.queryParam.settleClientName = val.name
    },
    receiverChange (val) {
      this.queryParam.receiverName = val.name
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    //  审核时间  change
    dateAuditChange (date) {
      this.queryParam.beginDate = date[0] ? date[0] : ''
      this.queryParam.endDate = date[1] ? date[1] : ''
    },
    //  收款时间  change
    dateSettleChange (date) {
      this.queryParam.beginDateSettle = date[0] ? date[0] : ''
      this.queryParam.endDateSettle = date[1] ? date[1] : ''
    },
    searchTable () {
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    //  重置
    resetSearchForm () {
      this.auditDate = []
      this.$refs.rangeAuditDate.resetDate(this.auditDate)
      this.$refs.settleClientName.resetForm()
      if (this.advanced) { //  查询条件未展开时，该组件未渲染
        this.settleDate = []
        this.$refs.rangeSettleDate.resetDate()
        this.$refs.receiverName.resetForm()
      }
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.bizNo = ''
      this.queryParam.dispatchBillNo = ''
      this.queryParam.beginDateSettle = ''
      this.queryParam.endDateSettle = ''
      this.queryParam.settleClientName = ''
      this.queryParam.receiverName = ''
      this.queryParam.dealerLevel = undefined
      this.queryParam.settleStyle = undefined
      this.queryParam.keepType = undefined
      this.queryParam.subareaSn = undefined
      this.queryParam.billStatus = undefined
      this.queryParam.settleState = undefined
      this.queryParam.voidFlag = undefined
      this.queryParam.dealerProvinceSn = undefined
      this.queryParam.dealerCitySn = undefined
      this.queryParam.dealerCountySn = undefined
      this.queryParam.checkStatus = undefined
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    handleDetail (row, type) {
      this.detailType = type
      this.bizSn = type == 0 ? row.bizSn : row.dispatchBillSn
      this.$store.state.app.curActionPermission = type == 0 ? 'B_salesDetail' : 'B_dispatchDetail'
      this.showDetailModal = true
    },
    cancelDetail () {
      this.showDetailModal = false
      this.detailType = 2
      this.bizSn = null
      this.$store.state.app.curActionPermission = ''
    },
    // 点击批量收款
    handlePlColle () {
      const _this = this
      const slen = _this.rowSelectionInfo.selectedRowKeys.length
      if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && slen < 1)) {
        _this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      // 判断是否选择相同的客户
      const settleClientName = _this.rowSelectionInfo.selectedRows[0].settleClientName
      const haseq = _this.rowSelectionInfo.selectedRows.filter(item => item.settleClientName == settleClientName)
      if (haseq.length == slen) {
        this.handlePlData = _this.rowSelectionInfo.selectedRows
        this.showSkModal = true
      } else {
        this.$info({
          title: '操作提示',
          centered: true,
          content: '您所选择的备货单，不属于同一个客户，无法收款，请重新选择。只能针对一个客户的备货单进行批量收款。',
          onOk () {}
        })
      }
    },
    // 凭证
    handleVoucher (row) {
      this.$store.state.app.curActionPermission = 'B_salesCollection_record'
      this.showVoucher = true
      this.$nextTick(() => {
        this.$refs.voucherModal.getData(row)
      })
    },
    closeVoucherModal(){
      this.showVoucher = false
      this.$store.state.app.curActionPermission = ''
    },
    // 点击收款
    handleColle (row) {
      this.handlePlData = [row]
      this.$store.state.app.curActionPermission = 'B_salesCollection_receipt'
      this.showSkModal = true
    },
    closeColleModal(){
      this.showSkModal = false
      this.$store.state.app.curActionPermission = ''
    },
    // 批量/单个收款
    handleSaveColle (row) {
      const _this = this
      const snList = []
      this.handlePlData.map(item => {
        snList.push(item.accountReceiptSn)
      })
      // 仅标记收款
      _this.spinning = true
      _this.showSkModal = false
      settleReceiptBatch({ snList: snList }).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
          _this.spinning = false
          _this.collectionType = 0
        } else {
          _this.spinning = false
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 235
    }
  },
  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">
  .salesCollectionList-wrap{
    .active{
      color: #ed1c24;
      cursor: pointer;
    }
    .common{
      color: rgba(0, 0, 0);
    }
  }
</style>
