<template>
  <a-card size="small" :bordered="false" class="financialCollectionList-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="经销商名称">
                <a-input id="financialCollectionList-buyerName" v-model.trim="queryParam.buyerName" allowClear placeholder="请输入经销商名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商户级别">
                <v-select
                  v-model="queryParam.dealerLevel"
                  ref="dealerLevel"
                  id="financialCollectionList-dealerLevel"
                  code="DEALER_LEVEL"
                  placeholder="请选择商户级别"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="收款方式">
                  <v-select
                    v-model="queryParam.settleStyleSn"
                    ref="settleStyleSn"
                    id="financialCollectionList-settleStyleSn"
                    code="SETTLE_STYLE"
                    placeholder="请选择收款方式"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="区域">
                  <subarea id="financialCollectionList-subarea" v-model="queryParam.subareaSn"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务状态">
                  <v-select
                    v-model="queryParam.billStatus"
                    ref="billStatus"
                    id="financialCollectionList-billStatus"
                    code="SALES_RECEIVE_LIST_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.financialStatus"
                    ref="financialStatus"
                    id="financialCollectionList-financialStatus"
                    code="FINANCIAL_RECEIVE_STATUS"
                    placeholder="请选择财务状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="收款时间">
                  <rangeDate ref="rangeSettleDate" @change="dateSettleChange" />
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-row>
                  <a-form-item label="经销商地区">
                    <a-col span="7">
                      <a-form-item prop="dealerProvinceSn" style="margin: 0;">
                        <a-select v-model="queryParam.dealerProvinceSn" allowClear @change="getCityList" placeholder="请选择省">
                          <a-select-option v-for="item in addrProvinceList" :value="item.id" :key="item.id + 'a'">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col span="7" offset="1">
                      <a-form-item prop="dealerCitySn" style="margin: 0;">
                        <a-select v-model="queryParam.dealerCitySn" allowClear @change="getAreaList" placeholder="请选择市">
                          <a-select-option v-for="item in addrCityList" :value="item.id" :key="item.id + 'b'">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col span="7" offset="1">
                      <a-form-item prop="dealerCountySn" style="margin: 0;">
                        <a-select v-model="queryParam.dealerCountySn" allowClear placeholder="请选择区/县">
                          <a-select-option v-for="item in addrDistrictList" :value="item.id" :key="item.id + 'c'">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                  </a-form-item>
                </a-row>
              </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>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1440, y: tableHeight }"
        bordered>
        <!-- 单号 -->
        <template slot="salesBillNo" slot-scope="text, record">
          <span :class="$hasPermissions('B_salesDetail')?'active':'common'" @click="handleDetail(record)">{{ record.salesBillNo }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="record.financialStatus=='WAIT' && $hasPermissions('B_financialCollection_receipt')"
            class="button-warning"
            @click="handleAudit(record)"
            id="financialCollectionList-audit-btn">收款</a-button>
          <span v-else>--</span>
        </template>
      </s-table>
    </a-spin>
  </a-card>
</template>

<script>
import moment from 'moment'
import getDate from '@/libs/getDate.js'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import subarea from '@/views/common/subarea.js'
import { getArea } from '@/api/data'
import { salesReceiptList, salesReceipt } from '@/api/sales'
export default {
  components: { STable, VSelect, subarea, rangeDate },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      queryParam: { //  查询条件
        beginAuditDate: getDate.getThreeMonthDays().starttime,
        endAuditDate: getDate.getCurrMonthDays().endtime,
        beginSettleDate: '',
        endSettleDate: '',
        buyerName: '',
        dealerLevel: undefined,
        settleStyleSn: undefined,
        subareaSn: undefined,
        billStatus: undefined,
        financialStatus: undefined,
        dealerProvinceSn: undefined,
        dealerCitySn: undefined,
        dealerCountySn: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      auditDate: [
        moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'),
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
      ], //  审核时间
      advanced: false,
      columns: [
        { title: '序号', dataIndex: 'no', width: 70, align: 'center' },
        { title: '审核时间', dataIndex: 'auditDate', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', scopedSlots: { customRender: 'salesBillNo' }, width: 180, align: 'center' },
        { title: '经销商名称', dataIndex: 'buyerName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '商户级别', dataIndex: 'dealerEntity.dealerLevelDictValue', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售数量', dataIndex: 'totalQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '订单金额', dataIndex: 'totalAmount', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '收款时间', dataIndex: 'settleDate', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '收款方式', dataIndex: 'settleStyleSnDictValue', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备注', dataIndex: 'remarks', width: 200, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'financialStatusDictValue', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 80, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return salesReceiptList(Object.assign(parameter, this.queryParam)).then(res => {
          const 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, // 合计
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [] //  区下拉
    }
  },
  methods: {
    //  审核时间  change
    dateAuditChange (date) {
      this.queryParam.beginAuditDate = date[0]
      this.queryParam.endAuditDate = date[1]
    },
    //  收款时间  change
    dateSettleChange (date) {
      this.queryParam.beginSettleDate = date[0]
      this.queryParam.endSettleDate = date[1]
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeAuditDate.resetDate(this.auditDate)
      if (this.advanced) { //  查询条件未展开时，该组件未渲染
        this.$refs.rangeSettleDate.resetDate()
      }
      this.queryParam.beginAuditDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endAuditDate = getDate.getCurrMonthDays().endtime
      this.queryParam.beginSettleDate = ''
      this.queryParam.endSettleDate = ''
      this.queryParam.buyerName = ''
      this.queryParam.dealerLevel = undefined
      this.queryParam.settleStyleSn = undefined
      this.queryParam.subareaSn = undefined
      this.queryParam.billStatus = undefined
      this.queryParam.financialStatus = undefined
      this.queryParam.dealerProvinceSn = undefined
      this.queryParam.dealerCitySn = undefined
      this.queryParam.dealerCountySn = undefined
      this.$refs.table.refresh(true)
    },
    // 详情
    handleDetail (row) {
      if (this.$hasPermissions('B_salesDetail')) {
        this.$router.push({ name: 'salesDetail', params: { sn: row.salesBillSn } })
      }
    },
    // 收款
    handleAudit (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要收款吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          salesReceipt({ sn: row.salesBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 获取城市列表
    getCityList (val) {
      this.addrCityList = []
      this.addrDistrictList = []
      this.queryParam.dealerCitySn = undefined
      this.queryParam.dealerCountySn = undefined
      if (val) {
        this.getArea('city', val)
      }
    },
    // 获取区县列表
    getAreaList (val) {
      this.addrDistrictList = []
      this.queryParam.dealerCountySn = undefined
      if (val) {
        this.getArea('district', val)
      }
    },
    //  省/市/区
    getArea (leve, sn) {
      let params
      if (leve == 'province') {
        params = { type: '2' }
      } else {
        params = { parentId: sn, type: leve == 'city' ? '3' : '4' }
      }
      getArea(params).then(res => {
        if (res.status == 200) {
          if (leve == 'province') {
            this.addrProvinceList = res.data || []
          } else if (leve == 'city') {
            this.addrCityList = res.data || []
          } else if (leve == 'district') {
            this.addrDistrictList = res.data || []
          }
        } else {
          if (leve == 'province') {
            this.addrProvinceList = []
          } else if (leve == 'city') {
            this.addrCityList = []
          } else if (leve == 'district') {
            this.addrDistrictList = []
          }
        }
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 195
    }
  },
  mounted () {
    const _this = this
    this.$nextTick(() => { // 页面渲染完成后的回调
      _this.setTableH()
    })
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      setTimeout(() => {
        _this.setTableH()
      }, 400)
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getArea('province')
    })
  }
}
</script>

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