<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="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>
            <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="收款时间">
                <rangeDate ref="rangeSettleDate" :value="settleDate" @change="dateSettleChange" />
              </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="备货单号">
                <a-input id="salesCollectionList-dispatchBillNo" v-model.trim="queryParam.dispatchBillNo" 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.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.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.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.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="对单状态">
                  <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" ref="subarea" @change="subareaChange"></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>
              <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">
              <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>
    </a-card>

    <a-card size="small" :bordered="false" class="salesCollectionList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator" v-if="$hasPermissions('B_salesCollection_receipt')">
          <a-button type="primary" @click="handlePlColle()">批量收款</a-button>
          <span style="margin-left: 8px">
            <template v-if="rowSelectionInfo && rowSelectionInfo.selectedRowKeys.length>0">{{ `已选 ${rowSelectionInfo.selectedRowKeys.length} 项` }}</template>
          </span>
        </div>
        <!-- 列表 -->
        <v-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+36+'px' }"
          size="small"
          :row-selection="showSelect?{ columnWidth: 40 }:null"
          @rowSelection="rowSelectionFun"
          :disableSelectedRowKeys="disableSelectedRowKeys"
          :rowKey="(record) => record.id"
          :columns="columns"
          :pagination="{pageSize:20}"
          :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>
        </v-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="0"
          width="70%"
          :showFooter="false"
          :openModal="showDetailModal"
          @cancel="cancelDetail">
          <salesDetail v-if="detailType==0" ref="salesDetail" :bizSn="bizSn" @close="cancelDetail"></salesDetail>
          <dispatchDetail v-if="detailType==1" ref="dispatchDetail" :bizSn="bizSn" @close="cancelDetail"></dispatchDetail>
        </commonModal>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VTable, 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/salesQueryNew/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'
import customerService from '@/views/common/customerService'
export default {
  name: 'SalesCollectionList',
  mixins: [commonMixin],
  components: { VTable, VSelect, subarea, rangeDate, commonModal, Area, voucherModal, dealerSubareaScopeList, salesDetail, dispatchDetail, customerService },
  data () {
    return {
      spinning: false,
      showDetail: false, // 详情弹框
      showSkModal: false, // 收款弹框
      showVoucher: false, // 凭证弹框
      showDetailModal: false, // 详情弹框
      detailType: 2, // 详情类型
      bizSn: null, // 单据sn
      tableHeight: 0, // 表格高度
      queryParam: { //  查询条件
        beginDate: '', // 开始时间
        endDate: '', // 结束时间
        bizNo: '', // 单据号
        dispatchBillNo: '', // 配送单号
        beginDateSettle: '', // 收款开始时间
        endDateSettle: '', // 收款结束时间
        settleClientName: '', // 结算客户
        receiverName: '', // 收货人
        dealerLevel: undefined, // 客户级别
        settleStyle: undefined, // 收款方式
        keepType: undefined, // 收款类型
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined // 分区
        },
        billStatus: undefined, // 业务状态
        settleState: undefined, // 财务状态
        voidFlag: undefined, // 单据状态
        dealerProvinceSn: undefined, // 地区 省
        dealerCitySn: undefined, // 市
        dealerCountySn: undefined, // 县
        checkStatus: undefined, // 对单状态
        bizUserSn: undefined // 客服
      },
      disabled: false, //  查询、重置按钮是否可操作
      auditDate: [], //  审核时间
      settleDate: [], // 收款时间默认值
      advanced: true, // 收起展开
      // 加载数据方法 必须为 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
            this.disableSelectedRowKeys = []
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              if (data.list[i].settleState == 'FINISH') {
                this.disableSelectedRowKeys.push(data.list[i].id)
              }
            }
            this.total = data.count || 0
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      disableSelectedRowKeys: [],
      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: '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) {
      console.log(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()
    },
    // 区域分区
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置查询
    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.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = 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.queryParam.bizUserSn = undefined
      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      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.$refs.table.clearSelected()
          _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 - 205
    }
  },
  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>
