<template>
  <div class="receiptPrint-wrap">
    <a-card size="small" class="searchBoxNormal" :bordered="false">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="允许打印时间">
                <rangeDate ref="rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="收款单号">
                <a-input id="salesCollectionList-bookNo" v-model.trim="queryParam.bookNo" allowClear placeholder="请输入备货单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称">
                <dealerSearchList ref="payerName" id="alesCollectionList-payerName" @change="custChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-show="isShowWarehouse">
              <a-form-model-item label="仓库">
                <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn" :isPermission="true"></chooseWarehouse>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24" v-if="currentTab == 1">
              <a-form-item label="收款打印状态">
                <v-select
                  v-model="queryParam.printStatus"
                  ref="printStatus"
                  id="salesCollectionList-printStatus"
                  code="PRINT_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.fullPaymentFlag"
                  ref="fullPaymentFlag"
                  id="salesCollectionList-fullPaymentFlag"
                  code="FLAG"
                  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>
            <a-col :md="6" :sm="24">
              <a-form-item label="收款金额">
                <a-select allowClear placeholder="请选择" id="salesCollectionList-receiptAmount" v-model="queryParam.receiptAmountZeroFlag">
                  <a-select-option value="1">等于0</a-select-option>
                  <a-select-option value="0">不等于0</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="isShowCustomerSearch&&currentTab==1?24:6" :sm="24" :style="{textAlign:isShowCustomerSearch&&currentTab==1?'center':''}">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="disabled" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px;margin-bottom:10px;" :disabled="disabled" @click="resetSearchForm()">重置</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>
    </a-card>
    <a-card class="receiptPrint-body" size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <div>
          <a-tabs v-model="currentTab" @change="changeTab">
            <a-tab-pane :key="1" tab="全部">
            </a-tab-pane>
            <a-tab-pane :key="2" tab="待打印">
            </a-tab-pane>
          </a-tabs>
        </div>
        <!-- 操作按钮 -->
        <div class="table-operator" v-if="$hasPermissions('B_SkPrint')">
          <a-button type="primary" :loading="spinning" @click="handlePlPrint()">批量打印</a-button>
          <span style="margin:0 10px">
            <template v-if="rowSelectionInfo && rowSelectionInfo.selectedRowKeys.length>0">{{ `已选 ${rowSelectionInfo.selectedRowKeys.length} 项` }}</template>
          </span>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+85+'px' }"
          :row-selection="$hasPermissions('B_SkPrint')?{ columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: (record.printStatus !== 'NO_PRINT'&&record.printStatus !== 'PRINT') } })}:null"
          @rowSelection="rowSelectionFun"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y:tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 打印状态 -->
          <template slot="printStatus" slot-scope="text, record">
            <span v-if="record.printStatus=='NO_PRINT'" class="link-bule" @click="handlePrintStatus(record)">{{ record.printStatusDictValue }}</span>
            <span v-else>{{ record.printStatusDictValue }}</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                size="small"
                type="link"
                v-if="(record.printStatus == 'NO_PRINT'||record.printStatus == 'PRINT')&&$hasPermissions('B_SkPrint')"
                class="button-warning"
                @click="handlePrint(record,0,record)"
              >收款打印</a-button>
              <a-button
                size="small"
                type="link"
                class="button-success"
                v-if="record.printStatus == 'PRINT'&&$hasPermissions('B_SKPrintRecord')"
                @click="viewPrint(record)"
              >打印记录</a-button>
            </div>
          </template>
        </s-table>

        <!-- 收款打印 -->
        <commonModal modalTit="收款打印预览" width="700pt" :showFooter="false" :openModal="showTipModal" @cancel="closeTipModal">
          <printModel ref="printModel" @cancel="closeTipModal" @printOk="printOk"></printModel>
        </commonModal>
        <!-- 打印记录 -->
        <recordModal v-drag ref="recordModal" modalTit="打印记录" :openModal="showRecordModal" @cancel="showRecordModal=false"></recordModal>
        <!-- 操作提示 -->
        <commonModal modalTit="操作提示" okText="暂不打印" :openModal="showPrintModal" @cancel="canselModal" @ok="updatePrintStatus">
          <div style="display:flex;flex-direction: column;align-items: center;">
            <div style="margin-bottom: 15px;font-size: 14px;">如需将打印状态回退至<strong>【暂不打印】</strong>,请点击下方按钮</div>
            <div style="line-height: 24px;">
              <div>收款单号：{{ tipData&&tipData.bookNo }}</div>
              <div>客户名称：{{ tipData&&tipData.payerName }}</div>
            </div>
          </div>
        </commonModal>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import rangeDate from '@/views/common/rangeDate.vue'
import { STable, VSelect } from '@/components'
import dealerSearchList from '@/views/common/dealerSearchList.vue'
import commonModal from '@/views/common/commonModal.vue'
import recordModal from './recordModal.vue'
import printModel from './printModel.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import customerService from '@/views/common/customerService'
import { financeBookDetailList, updateFinanceBookDetail, checkPrintStatus } from '@/api/financeBook'
import { getProcessInstance } from '@/api/expenseManagement'
export default {
  name: 'ReceiptPrintList',
  mixins: [commonMixin],
  components: { STable, VSelect, dealerSearchList, rangeDate, commonModal, recordModal, printModel, chooseWarehouse, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0,
      time: [],
      currentTab: 2,
      // 查询参数
      queryParam: {
        beginDate: '',
        endDate: '',
        bookNo: '',
        payerName: '',
        dealerSn: undefined,
        subareaSn: undefined,
        billStatus: undefined,
        dealerProvinceSn: undefined,
        fullPaymentFlag: undefined,
        warehouseSn: undefined,
        printStatus: 'NO_PRINT',
        bizUserSn: undefined,
        receiptAmountZeroFlag: undefined
      },
      totalData: {
        totalAmount: 0,
        totalQty: 0,
        totalRecord: 0
      },
      showTipModal: false,
      showRecordModal: false,
      showPrintModal: false,
      showViewModal: false,
      tipData: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        if (this.currentTab == 1) {
          this.queryParam.isAll = '1'
          this.queryParam.status = 'AUDIT_PASS'
        }
        return financeBookDetailList(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.spinning = false
          return data
        })
      },
      rowSelectionInfo: null // 批量选择的数据
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '允许打印时间', dataIndex: 'allowPrintTime', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '收款单号', dataIndex: 'bookNo', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '收款日期', dataIndex: 'receiptDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'payerName', align: 'left', width: '20%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '财务编码', dataIndex: 'dealerEntity.kdMidCustomerFnumber', align: 'center', width: '10%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '订单金额', dataIndex: 'orderAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '收款金额', dataIndex: 'receiptAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '使用授信', dataIndex: 'useCreditAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '授信还款', dataIndex: 'payCreditAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '余款抵扣', dataIndex: 'balanceAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '跨月打款', dataIndex: 'nextMonthAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '特殊申请发货', dataIndex: 'specialSendAmount', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '户名', dataIndex: 'bankAccount', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '汇入银行', dataIndex: 'bankName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '足额打款', dataIndex: 'fullPaymentFlagDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '说明', dataIndex: 'explainInfo', width: '6%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '收款打印状态', dataIndex: 'printStatusDictValue', width: '6%', align: 'center', scopedSlots: { customRender: 'printStatus' } },
        { title: '打印次数', dataIndex: 'printNum', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '7%', align: 'center' }
      ]
      if (this.isShowWarehouse) {
        arr.splice(5, 0, { title: '仓库', dataIndex: 'warehouseName', align: 'center', width: '10%', customRender: function (text) { return text || '--' }, ellipsis: true })
      }
      return arr
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    changeTab (v) {
      this.currentTab = v
      this.pageInit()
      this.resetSearchForm()
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 批量打印
    async handlePlPrint () {
      const _this = this
      const rows = _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows || []
      const slen = rows.length
      if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && slen < 1)) {
        _this.$message.warning('请在列表勾选后再进行批量操作！')
        return false
      }
      this.spinning = true
      const bookSns = []
      const bookDetailSn = []
      rows.map(item => {
        if (bookSns.indexOf(item.bookSn) < 0) {
          bookSns.push(item.bookSn)
        }
        bookDetailSn.push(item.bookDetailSn)
      })

      // 检查是否有已打印数据
      if (this.currentTab == 2) {
        const hasPrintData = await checkPrintStatus(bookDetailSn).then(res => res.data)
        if (!hasPrintData) {
          _this.$info({
            title: '操作提示',
            centered: true,
            content: '您所选择的收款单，存在已打印的单子，请重新选择。',
            onOk () {
              _this.resetSearchForm()
            }
          })
          return
        }
      }

      const retArr = []
      for (let i = 0; i < bookSns.length; i++) {
        const item = bookSns[i]
        // 授信明细,还款明细
        const rs = rows.filter(a => a.bookSn == item)
        let detailItemUseStr = ''
        let detailPayUseStr = ''
        rs.map(b => {
          if (b.detailItemUseList) {
            detailItemUseStr += this.getUseDetailInfo(b.detailItemUseList)
          }
          if (b.detailItemPayList) {
            detailPayUseStr += this.getUseDetailInfo(b.detailItemPayList)
          }
        })
        const auditInfo = await getProcessInstance({ 'businessType': 'FINANCE_BOOK', 'businessSn': item }).then(res => (res.data[0] && res.data[0].opinionList) ? res.data[0].opinionList : [])
        // 审核信息
        const auditStr = auditInfo ? this.getAuditInfo(auditInfo) : ''
        retArr.push({ audit: auditStr, detail: detailItemUseStr, payDetail: detailPayUseStr, subList: rs })
      }
      this.handlePrint(retArr, 1, rows, bookSns)
    },
    // 获取授信西悉尼
    getUseDetailInfo (list) {
      let ret = ''
      list.map((k, i) => {
        ret = ret + k.itemName + '(' + k.itemAmount + ')' + (i == list.length - 1 ? '；' : '，')
      })
      return ret
    },
    // 获取审核信息
    getAuditInfo (auditList) {
      let auditStr = ''
      if (auditList && auditList.length) {
        const auditLists = auditList.filter(item => item.processTaskType == '审批人')
        auditLists.map((a, i) => {
          auditStr = auditStr + a.approvalName + '(' + a.approvalStateDictValue + ')' + (i == auditLists.length - 1 ? '；' : '，')
        })
      }
      return auditStr
    },
    // 收款打印
    async handlePrint (row, type, list, bookSns) {
      const _this = this
      let auditInfo = null
      if (type == 0) {
        // 是否已打印
        if (this.currentTab == 2) {
          const hasPrintData = await checkPrintStatus([list.bookDetailSn]).then(res => res.data)
          if (!hasPrintData) {
            _this.$info({
              title: '操作提示',
              centered: true,
              content: '您所选择的收款单已打印，请重新选择。',
              onOk () {
                _this.resetSearchForm()
              }
            })
            return
          }
        }
        auditInfo = await getProcessInstance({ 'businessType': 'FINANCE_BOOK', 'businessSn': list.bookSn }).then(res => (res.data[0] && res.data[0].opinionList) ? res.data[0].opinionList : [])
      }
      this.spinning = true
      this.showTipModal = true
      let detailItemUseStr = ''
      let detailPayUseStr = ''
      this.$nextTick(() => {
        // type == 0 单个打印时
        if (type == 0 && row.detailItemUseList) {
          detailItemUseStr = this.getUseDetailInfo(row.detailItemUseList)
        }
        if (type == 0 && row.detailItemPayList) {
          detailPayUseStr = this.getUseDetailInfo(row.detailItemPayList)
        }
        // 审核信息
        const auditStr = auditInfo ? this.getAuditInfo(auditInfo) : ''
        this.$refs.printModel.getData(type ? row : [{ audit: auditStr, detail: detailItemUseStr, payDetail: detailPayUseStr, subList: [row] }], type ? list : [list])
      })
    },
    printOk (res) {
      if (res) {
        this.spinning = false
        this.$refs.table.refresh()
        this.$refs.table.clearSelected()
      }
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0] ? date[0] : ''
      this.queryParam.endDate = date[1] ? date[1] : ''
    },
    custChange (val) {
      console.log(val)
      if (val.row) {
        this.queryParam.dealerSn = val.row.dealerSn
        this.queryParam.payerName = undefined
      } else {
        this.queryParam.dealerSn = undefined
        this.queryParam.payerName = val.key
      }
    },
    handlePrintStatus (row) {
      this.tipData = row
      this.showPrintModal = true
    },
    canselModal () {
      this.tipData = null
      this.showPrintModal = false
    },
    updatePrintStatus () {
      updateFinanceBookDetail({ id: this.tipData.id, printStatus: 'UNABLE_PRINT' }, 1).then(res => {
        if (res.status == 200) {
          this.canselModal()
          this.$message.info(res.message)
          this.$refs.table.refresh()
        }
      })
    },
    // 关闭打印预览
    closeTipModal () {
      this.showTipModal = false
      this.spinning = false
      this.$refs.printModel.clearData()
    },
    // 打印记录
    viewPrint (row) {
      this.showRecordModal = true
      this.$refs.recordModal.setData(row, {
        billType: 'FINANCE_BOOK_DETAIL',
        billSn: row.bookDetailSn,
        billNo: row.bookNo
      })
    },
    // 重置
    resetSearchForm () {
      this.time = []
      this.$refs.rangeDate.resetDate(this.time)
      this.$refs.payerName.resetForm()
      this.queryParam = {
        beginDate: '',
        endDate: '',
        bookNo: '',
        payerName: '',
        dealerSn: undefined,
        subareaSn: undefined,
        billStatus: undefined,
        dealerProvinceSn: undefined,
        fullPaymentFlag: undefined,
        warehouseSn: undefined,
        bizUserSn: undefined,
        printStatus: this.currentTab == 2 ? 'NO_PRINT' : undefined,
        receiptAmountZeroFlag: undefined
      }
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 295
    }
  },
  watch: {
    '$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">
  .receiptPrint-wrap{
    .ant-tabs-bar{
      margin-bottom: 10px;
    }
    .receiptPrint-body{
      .ant-card-body{
        padding-top:0;
      }
    }
  }
</style>
