<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="经销商名称/商户别名">
                <a-input id="accountStatementBill-dealerName" v-model.trim="queryParam.nameLike" allowClear placeholder="请输入经销商名称/商户别名"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="区域">
                <subarea id="accountStatementBill-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商户级别">
                <v-select code="DEALER_LEVEL" id="accountStatementBill-dealerLevel" v-model="queryParam.dealerLevel" allowClear placeholder="请选择商户级别"></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商户类型">
                <dealerType id="accountStatementBill-dealerType" changeOnSelect v-model="dealerType" @change="getDealerType" allowClear></dealertype>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客服">
                <customerService ref="customerName" id="matchSendOutOrderList-bizUserSn" v-model="queryParam.subareaArea.kfSn"></customerService>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="财务编码">
                <a-input id="accountStatementBill-bookNo" v-model.trim="queryParam.kdMidCustomerFnumber" allowClear placeholder="请输入财务编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="月度有业务客户" prop="beginDate">
                <a-month-picker
                  id="accountStatementBill-monthBox"
                  class="monthBox"
                  :disabled-date="disabledDate"
                  v-model="monthVal"
                  placeholder="请选择月份"
                  @change="onChangeMonth" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="accountStatementBill-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="accountStatementBill-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                id="conFrontModal-export"
                v-if="$hasPermissions('B_asb_export')"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
              >导出</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false" class="accountStatementBill-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator">
          <div class="tongji-bar">
            总余额：{{ toThousands(countData&&countData.totalBalance||0) }}；
            已对单余额：{{ toThousands(countData&&countData.confirmBalance||0) }}；
            待对单余额：{{ toThousands(countData&&countData.waitConfirmBalance||0) }}；
            待选余额：{{ toThousands(countData&&countData.newBizBalance||0) }}；
            待选单数：{{ countData&&countData.newBizCount||0 }}；
          </div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+80+'px' }"
          size="small"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :pageSize="30"
          :defaultLoadData="false"
          bordered>
          <template slot="totalBalance" slot-scope="text, record">
            <span v-if="$hasPermissions('B_asb_detail')" class="link-bule" @click="handleDetail(record,0)">{{ toThousands(record.totalBalance) }}</span>
            <span v-else>{{ toThousands(record.totalBalance) }}</span>
          </template>
          <template slot="confirmBalance" slot-scope="text, record">
            <span v-if="$hasPermissions('B_asb_detail')" class="link-bule" @click="handleDetail(record,1)">{{ toThousands(record.confirmBalance) }}</span>
            <span v-else>{{ toThousands(record.confirmBalance) }}</span>
          </template>
          <template slot="waitConfirmBalance" slot-scope="text, record">
            <span v-if="$hasPermissions('B_asb_detail')" class="link-bule" @click="handleDetail(record,2)">{{ toThousands(record.waitConfirmBalance) }}</span>
            <span v-else>{{ toThousands(record.waitConfirmBalance) }}</span>
          </template>
          <template slot="newBizBalance" slot-scope="text, record">
            <span v-if="$hasPermissions('B_asb_detail')" class="link-bule" @click="handleDetail(record,3)">{{ toThousands(record.newBizBalance) }}</span>
            <span v-else>{{ toThousands(record.newBizBalance) }}</span>
          </template>
          <template slot="dealerType" slot-scope="text, record">
            <span v-if="record.dealer">
              {{ record.dealer.dealerTypeName1 }}{{ record.dealer.dealerTypeName2?'>':'' }}{{ record.dealer.dealerTypeName2 }}
            </span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                v-if="$hasPermissions('B_asb_newOrder')"
                size="small"
                type="link"
                class="button-info"
                @click="handleAdd(record)"
              >
                创建对账单
              </a-button>
            </div>
          </template>
        </s-table>
      </a-spin>
    </a-card>
    <baseModal v-drag ref="baseModal" :show="openModal" @cancel="openModal=false" @refashData="creatOrder"></baseModal>
  </div>
</template>

<script>
import moment from 'moment'
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { hdExportExcel } from '@/libs/exportExcel'
import subarea from '@/views/common/subarea.js'
import dealerType from '@/views/common/dealerType.js'
import customerService from '@/views/common/customerService.vue'
import baseModal from './baseModal.vue'
import { verifyAccountBalanceQueryPage, verifyAccountBalanceExport, verifyAccountBalanceQueryCount } from '@/api/verifyAccountChange.js'
export default {
  name: 'AccountStatementBillList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, dealerType, customerService, baseModal },
  data () {
    return {
      spinning: false,
      exportLoading: false,
      tableHeight: 0,
      openModal: false,
      dealerType: [], // 商户类型
      monthVal: '', // 初始化月份值
      queryParam: { //  查询条件
        nameLike: '', // 经销商名称/别名
        dealerType1: undefined, //  商户类型
        dealerType2: undefined, //  商户类型
        dealerLevel: null, // 商户级别
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined, // 分区
          kfSn: undefined // 客服
        },
        kdMidCustomerFnumber: '' // 财务编码
      },
      disabled: false, //  查询、重置按钮是否可操作
      advanced: true,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = this.queryParam
        parameter.sortOrder = parameter.sortOrder == 'ascend' ? 'asc' : parameter.sortOrder == 'descend' ? 'desc' : ''
        const fileds = { 'lastBizDate': 'last_biz_date', 'totalBalance': 'total_balance', 'confirmBalance': 'confirm_balance', 'waitConfirmBalance': 'wait_confirm_balance', 'newBizBalance': 'new_biz_balance' }
        parameter.sortField = fileds[parameter.sortField]
        const params1 = {
          dealer: {
            nameLike: params.nameLike,
            dealerType1: params.dealerType1,
            dealerType2: params.dealerType2,
            dealerLevel: params.dealerLevel,
            subareaArea: params.subareaArea,
            kdMidCustomerFnumber: params.kdMidCustomerFnumber
          },
          bizMonth: this.monthVal ? this.monthVal + '-01' : '',
          ...parameter
        }
        return verifyAccountBalanceQueryPage(params1).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
              if (data.list[i].lastBizDate) {
                data.list[i].lastBizDate = moment(data.list[i].lastBizDate).format('YYYY-MM')
              }
            }
            this.total = data.count || 0
            this.disabled = false
          }
          this.spinning = false
          this.getCount(params1)
          return data
        })
      },
      total: 0, // 合计
      countData: null
    }
  },
  // 根据权限显示列表字段
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '财务编码', dataIndex: 'dealer.kdMidCustomerFnumber', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '经销商名称', dataIndex: 'dealer.dealerName', width: '14%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '商户别名', dataIndex: 'dealer.dealerAlias', width: '13%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '总余额', scopedSlots: { customRender: 'totalBalance' }, dataIndex: 'totalBalance', width: '6%', align: 'center', sorter: true },
        { title: '已对单余额', scopedSlots: { customRender: 'confirmBalance' }, dataIndex: 'confirmBalance', width: '7%', align: 'center', sorter: true },
        { title: '待对单余额', scopedSlots: { customRender: 'waitConfirmBalance' }, dataIndex: 'waitConfirmBalance', width: '7%', align: 'center', sorter: true },
        { title: '待选余额', scopedSlots: { customRender: 'newBizBalance' }, dataIndex: 'newBizBalance', width: '6%', align: 'center', sorter: true },
        { title: '待选单数', dataIndex: 'newBizCount', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '最新业务月份', dataIndex: 'lastBizDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, sorter: true },
        { title: '客服', dataIndex: 'kfName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域', dataIndex: 'dealer.subareaArea.subareaName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'dealer.subareaArea.subareaAreaName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '省份', dataIndex: 'dealer.provinceName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户级别', dataIndex: 'dealer.dealerLevelDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户类型', scopedSlots: { customRender: 'dealerType' }, width: '14%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    // 选择月份  禁用选择当月以后日期
    disabledDate (current) {
      return current && current >= moment().endOf('day')
    },
    // 选择月份 change
    onChangeMonth (date, dateString) {
      this.monthVal = dateString
    },
    // 区域分区
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // 商户类型 change
    getDealerType (v, o) {
      this.queryParam.dealerType1 = v[0]
      this.queryParam.dealerType2 = v[1]
    },
    // 统计信息
    getCount (params) {
      verifyAccountBalanceQueryCount(params).then(res => {
        this.countData = res.data
      })
    },
    //  重置
    resetSearchForm () {
      this.monthVal = ''
      this.queryParam.nameLike = ''
      this.queryParam.dealerType1 = undefined
      this.queryParam.dealerType2 = undefined
      this.queryParam.dealerLevel = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.kfSn = undefined
      this.dealerType = []
      this.$refs.subarea.clearData()
      this.queryParam.kdMidCustomerFnumber = ''
      this.$refs.table.refresh(true)
    },
    // 导出
    handleExport () {
      const _this = this
      _this.exportLoading = true
      const params = this.queryParam
      const params1 = {
        dealer: {
          nameLike: params.nameLike,
          dealerType1: params.dealerType1,
          dealerType2: params.dealerType2,
          dealerLevel: params.dealerLevel,
          subareaArea: params.subareaArea,
          kdMidCustomerFnumber: params.kdMidCustomerFnumber
        },
        bizMonth: this.monthVal ? this.monthVal + '-01' : ''
      }
      hdExportExcel(verifyAccountBalanceExport, params1, '经销商对账单据余额-', function () {
        _this.exportLoading = false
      })
    },
    // 新增
    handleAdd (row) {
      this.openModal = true
      this.$refs.baseModal.pageInit(row)
    },
    // 创建对账单成功
    creatOrder (data) {
      this.$refs.table.refresh()
      this.$router.push({ name: 'accountStatementEdit', params: { sn: data.verifyAccountBillSn } })
    },
    // 详情
    handleDetail (row, type) {
      this.$router.push({ name: 'accountStatementBillDetail', params: { sn: row.dealer.dealerSn, name: row.dealer.dealerName, type: type } })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    }
  },
  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">
  .accountStatementBill-wrap{
    .active{
      color: #ed1c24;
      cursor: pointer;
    }
    .common{
      color: rgba(0, 0, 0);
    }
  }
  .monthBox{
    width: 100%;
    /deep/.ant-calendar-picker-icon{
      display:none !important;
    }
    /deep/.ant-calendar-picker input{
      text-align:center;
    }
  }
</style>
