<template>
  <div>
    <a-card size="small" :bordered="false" class="priceDifferenceDetailList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form-model
          id="priceDifferenceDetailList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="月份" prop="month">
                <a-month-picker
                  placeholder="请选择月份"
                  locale="zh-cn"
                  v-model="queryParam.month"
                  @change="onChange"
                  :disabled-date="disabledDate"
                  style="width: 100%;"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="省份">
                <Area id="priceDifferenceDetailList-provinceSn" v-model="queryParam.provinceSn" placeholder="请选择省"></Area>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="记账门店">
                <custList id="priceDifferenceDetailList-rebateDealer" ref="rebateDealerList" @change="rebateDealerChange"></custList>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户名称">
                <dealerSubareaScopeList id="priceDifferenceDetailList-custList" ref="custList" :itemSn="queryParam.buyerSn" @change="custChange"></dealerSubareaScopeList>
              </a-form-model-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-model-item label="所在区域">
                <subarea id="priceDifferenceDetailList-allocateTypeSn" placeholder="请选择区域" showLeve="1" ref="subarea" @change="subareaChange"></subarea>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
              <a-form-item label="单据类型">
                <v-select
                  v-model="queryParam.bizType"
                  ref="bizType"
                  id="priceDifferenceDetailList-bizType"
                  code="REBATE_BILL_BIZ_TYPE"
                  placeholder="请选择单据类型"
                  allowClear></v-select>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="priceDifferenceDetailList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="priceDifferenceDetailList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_priceDifferenceDetail_Export')"
                id="allocationDetailsList-export">导出</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <!-- 列表 -->
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :pageSize="30"
          :style="{ height: tableHeight+70+'px' }"
          :scroll="{ y: tableHeight-30 }"
          bordered>
          <template slot="footer">
            <table>
              <tr>
                <td width="16%" colspan="3">总计：</td>
                <td width="76%" colspan="8" style="display:flex;justify-content: space-between;">
                  <span>实售金额：{{ (totalData && (totalData.totalRealAmount || totalData.totalRealAmount==0)) ? toThousands(totalData.totalRealAmount) : '--' }}</span>
                  <span>开单金额：{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? toThousands(totalData.totalAmount) : '--' }}</span>
                  <span>销售一部差价金额：{{ (totalData && (totalData.directRebateAmount || totalData.directRebateAmount==0)) ? toThousands(totalData.directRebateAmount) : '--' }}</span>
                  <span>销售二部差价金额：{{ (totalData && (totalData.directRebateAmount || totalData.directRebateAmount==0)) ? toThousands(totalData.directRebateAmount) : '--' }}</span>
                  <span>差价金额：{{ (totalData && (totalData.directRebateAmount || totalData.directRebateAmount==0)) ? toThousands(totalData.directRebateAmount) : '--' }}</span>
                </td>
                <td width="8%"></td>
              </tr>
            </table>
          </template>
        </s-table>
      </a-spin>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import { STable, VSelect } from '@/components'
import custList from '@/views/common/custList.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import Area from '@/views/common/area.js'
import subarea from '@/views/common/subarea.js'
import rangeDate from '@/views/common/rangeDate.vue'
import reportModal from '@/views/common/reportModal.vue'
import customerService from '@/views/common/customerService.vue'
import { hdExportExcel } from '@/libs/exportExcel'
import { reportRebateReportList, reportRebateCount, reportRebateExport } from '@/api/reportData'
export default {
  name: 'PriceDifferenceDetailReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, custList, dealerSubareaScopeList, subarea, Area, rangeDate, reportModal, customerService },
  data () {
    return {
      spinning: false,
      exportLoading: false,
      showExport: false,
      queryParam: { //  查询条件
        month: moment().format('YYYY-MM'),
        provinceSn: undefined,
        parentDealerSn: undefined,
        buyerSn: undefined,
        bizUserSn: undefined,
        bizType: undefined, // 单据类型
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        }
      },
      rules: {
        'month': [{ required: true, message: '请选择月份', trigger: 'change' }],
        'provinceSn': [{ required: true, message: '请选择省份', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        if (params.month) {
          params.month = params.month + '-01'
        }
        this.spinning = true
        return reportRebateReportList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 总计
            this.getCount(params)
            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
        })
      },
      totalData: null,
      tableHeight: 0
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '月份', dataIndex: 'bizDate', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域', dataIndex: 'subareaArea.subareaName', show: true, width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', show: true, width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '省份', dataIndex: 'provinceName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '记账门店', dataIndex: 'parentDealerName', width: '14%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户名称', dataIndex: 'buyerName', width: '15%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品品牌+二级分类', dataIndex: 'productBrandAndType2', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单据类型', dataIndex: 'bizTypeDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      arr.splice(4, 0, { title: '实售金额', dataIndex: 'totalRealAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      arr.splice(5, 0, { title: '开单金额', dataIndex: 'totalAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      arr.splice(6, 0, { title: '差价金额', dataIndex: 'directRebateAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      arr.splice(7, 0, { title: '记账费用', dataIndex: 'rebateAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      return arr
    }
  },
  methods: {
    onChange (date, dateString) {
      this.queryParam.month = dateString
    },
    disabledDate (current) {
      return current && current > moment().endOf('day')
    },
    // 区域分区
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // 合计
    getCount (params) {
      reportRebateCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择月份')
          return false
        }
      })
    },
    rebateDealerChange (val) {
      this.queryParam.parentDealerSn = val.key
    },
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    //  重置
    resetSearchForm () {
      this.queryParam.month = moment().format('YYYY-MM')
      this.queryParam.provinceSn = undefined
      this.queryParam.parentDealerSn = undefined
      this.queryParam.buyerSn = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.bizType = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.$refs.rebateDealerList.resetForm()
      this.totalData = null
      this.$refs.custList.resetForm()
      this.$refs.subarea.clearData()
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'B_priceDifferenceDetail_Export'
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(reportRebateExport, params, '差价明细报表', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 200
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.resetSearchForm()
      this.setTableH()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.resetSearchForm()
      this.setTableH()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
