<template>
  <div>
    <a-card size="small" :bordered="false" class="sRebateList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="sRebateList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :rules="rules"
          :model="queryParam">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item prop="queryDate">
                <div style="display: inline;" slot="label">
                  <a-popover placement="top">
                    <template slot="content">
                      <p>1、销售单（非转单）下推时间</p>
                    </template>
                    查询月份 <a-icon type="question-circle" />
                  </a-popover>
                </div>
                <a-month-picker
                  id="sRebateList-monthBox"
                  class="monthBox"
                  :disabled-date="disabledDate"
                  v-model="queryParam.queryDate"
                  placeholder="请选择月份"
                  @change="onChangeMonth" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="销售单号">
                <a-input id="sRebateList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="备货单号">
                <a-input id="sRebateList-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-model-item label="客户名称">
                  <custList id="sRebateList-dealerName" dataAuthFlag="0" placeholder="请输入客户名称" ref="custList" @change="custChange" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户级别">
                  <v-select
                    v-model="queryParam.dealerLevel"
                    ref="dealerLevel"
                    id="sRebateList-dealerLevel"
                    code="DEALER_LEVEL"
                    placeholder="请选择客户级别"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="所在区域">
                  <subarea id="sRebateList-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区">
                  <Area id="sRebateList-provinceSn" v-model="queryParam.provinceSn" placeholder="请选择省份"></Area>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="sRebateList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="sRebateList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('M_tireSubsidyExport')"
                id="sRebateList-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'" />
              </a>
            </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"
          :style="{ height: tableHeight+70+'px' }"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :scroll="{ x: 2200, y: tableHeight-50}"
          :defaultLoadData="false"
          bordered>
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="6" :sm="24">下推数量：{{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ?totalData.totalQty: '--' }}</a-col>
              <a-col :md="6" :sm="24" v-if="$hasPermissions('M_tireSubsidyList_costPrice')">平均成本公斤单价：{{ (totalData && (totalData.averageCost || totalData.averageCost==0)) ? toThousands(totalData.averageCost): '--' }}</a-col>
              <a-col :md="6" :sm="24" v-if="$hasPermissions('M_tireSubsidyList_costPrice')">成本金额：{{ (totalData && (totalData.totalCost || totalData.totalCost==0)) ? toThousands(totalData.totalCost): '--' }}</a-col>
              <a-col :md="6" :sm="24">合计重量(kg)：{{ (totalData && (totalData.totalWeight || totalData.totalWeight==0)) ?totalData.totalWeight: '--' }}</a-col>
              <a-col :md="6" :sm="24" v-if="$hasPermissions('M_tireSubsidyList_salesPrice')">实售金额：{{ (totalData && (totalData.totalRealAmount || totalData.totalRealAmount==0)) ? toThousands(totalData.totalRealAmount): '--' }}</a-col>
              <a-col :md="6" :sm="24" v-if="$hasPermissions('M_tireSubsidyList_salesPrice')">平均售价公斤单价：{{ (totalData && (totalData.averageRealAmount || totalData.averageRealAmount==0)) ? toThousands(totalData.averageRealAmount): '--' }}</a-col>
              <a-col :md="6" :sm="24" v-if="$hasPermissions('M_tireSubsidyList_costPrice')">返利金额：{{ (totalData && (totalData.totalFactoryRebate || totalData.totalFactoryRebate==0)) ? toThousands(totalData.totalFactoryRebate): '--' }}</a-col>
            </a-row>
          </template>
        </s-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
import moment from 'moment'
// 组件
import { STable, VSelect } from '@/components'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import custList from '@/views/common/custList.vue'
// 接口
import { subsidyTireList, subsidyTireCount, subsidyTireExport } from '@/api/reportData'
export default {
  name: 'SupplierRebateList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, Area, custList },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      exportLoading: false, // 导出按钮加载状态
      //  查询条件
      queryParam: {
        beginDate: moment().startOf('month').format('YYYY-MM-DD') + ' 00:00:00', // 开始月份
        endDate: moment().endOf('month').format('YYYY-MM-DD') + ' 23:59:59', // 结束月份
        queryDate: moment().format('YYYY-MM'), // 选择月份
        salesBillNo: undefined, // 销售单号
        dispatchBillNo: undefined, // 备货单号
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined // 分区
        },
        provinceSn: undefined, // 省份sn
        dealerName: undefined, // 客户名称
        dealerSn: undefined, // 客户名称sn
        dealerLevel: undefined// 客户等级
      },
      totalData: null, // 合计
      rules: {
        'queryDate': [{ required: true, message: '请选择查询月份', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        const newParams = JSON.parse(JSON.stringify(params))
        delete newParams.queryDate
        // 获取列表数据  有分页
        return subsidyTireList(newParams).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.getCount(newParams)
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '40px', align: 'center' },
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: '90px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: '90px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', dataIndex: 'salesBillNo', width: '110px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备货单号', dataIndex: 'dispatchBillNo', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '省份', dataIndex: 'provinceName', width: '80px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerName', width: '150px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户级别', dataIndex: 'dealerLevelDictValue', width: '80px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '下推时间', dataIndex: 'pushedDate', width: '110px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '下推数量', dataIndex: 'totalQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单重（kg）', dataIndex: 'weight', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '合计重量(kg)', dataIndex: 'totalWeight', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      // 成本权限
      if (_this.$hasPermissions('M_tireSubsidyList_costPrice')) {
        arr.push({ title: '成本金额', dataIndex: 'totalCost', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.push({ title: '平均成本公斤单价', dataIndex: 'averageCost', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      // 售价权限
      if (_this.$hasPermissions('M_tireSubsidyList_salesPrice')) {
        arr.push({ title: '实售金额', dataIndex: 'totalRealAmount', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.push({ title: '平均售价公斤单价', dataIndex: 'averageRealAmount', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (_this.$hasPermissions('M_tireSubsidyList_costPrice')) {
        arr.push({ title: '返利金额', dataIndex: 'totalFactoryRebate', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 选择月份  禁用选择当月以后日期
    disabledDate (current) {
      return current && current >= moment().endOf('day')
    },
    // 选择月份 change
    onChangeMonth (date, dateString) {
      this.monthVal = dateString
      if (date && dateString != '') {
        this.queryParam.beginDate = moment(dateString).startOf('month').format('YYYY-MM-DD') + ' 00:00:00'
        this.queryParam.endDate = moment(dateString).endOf('month').format('YYYY-MM-DD') + ' 23:59:59'
      } else {
        this.queryParam.beginDate = void 0
        this.queryParam.endDate = void 0
      }
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择查询月份')
          return false
        }
      })
    },
    // 客户名称 change
    custChange (val) {
      this.queryParam.dealerSn = val.key
      this.queryParam.dealerName = val && val.label ? val.label.replace(/\s+/g, '') : undefined
    },
    // 统计
    getCount (params) {
      subsidyTireCount(params).then(res => {
        if (res.status == 200 && res.data) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 区域分区  change
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    resetSearchForm () {
      this.queryParam.beginDate = moment().startOf('month').format('YYYY-MM-DD') + ' 00:00:00' // 开始月份
      this.queryParam.endDate = moment().endOf('month').format('YYYY-MM-DD') + ' 23:59:59' // 结束月份
      this.queryParam.queryDate = moment().format('YYYY-MM')// 选择月份
      this.queryParam.salesBillNo = undefined
      this.queryParam.dispatchBillNo = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.provinceSn = undefined
      this.queryParam.dealerName = undefined
      this.queryParam.dealerSn = undefined
      this.queryParam.dealerLevel = undefined
      if (this.advanced) {
        this.$refs.custList.resetForm()
        this.$refs.subarea.clearData()
      }
      this.totalData = null
      this.$refs.table.clearTable()
      this.$refs.ruleForm.resetFields()
    },
    //  导出  必填判断
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.exportList()
        } else {
          _this.$message.error('请选择查询月份')
          return false
        }
      })
    },
    // 导出
    exportList () {
      const _this = this
      const params = JSON.parse(JSON.stringify(_this.queryParam))
      _this.$store.state.app.curActionPermission = 'M_tireSubsidyExport'
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(subsidyTireExport, params, '供应商轮胎补贴返利报表-', function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.$store.state.app.curActionPermission = ''
      })
    },
    // 初始化
    pageInit () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        this.setTableH()
      })
      this.resetSearchForm()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 280
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  }
}
</script>
<style lang="less" scoped>
  .monthBox{
    width: 100%;
    /deep/.ant-calendar-picker-icon{
      display:none !important;
    }
    /deep/.ant-calendar-picker input{
      text-align:center;
    }
  }
</style>
