<template>
  <div>
    <a-card size="small" :bordered="false" class="serviceFreight-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="serviceFreight-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :rules="rules"
          :model="queryParam">
          <a-row :gutter="15" type="flex">
            <a-col :flex="1">
              <a-form-model-item prop="queryDate">
                <div style="display: inline;" slot="label">
                  <a-popover placement="top">
                    <template slot="content">
                      <p>1、销售单（非转单）的下推时间</p>
                      <p>2、销售单（转单）的转单完结时间</p>
                      <p>3、销售退货单的客服确认时间</p>
                    </template>
                    查询月份 <a-icon type="question-circle" />
                  </a-popover>
                </div>
                <a-month-picker
                  id="serviceFreight-monthBox"
                  class="monthBox"
                  :disabled-date="disabledDate"
                  v-model="monthVal"
                  placeholder="请选择月份"
                  @change="onChangeMonth" />
              </a-form-model-item>
            </a-col>
            <a-col :flex="1">
              <a-form-item label="所在区域">
                <subarea id="serviceFreight-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-item>
            </a-col>
            <a-col :flex="1">
              <a-form-model-item label="地区">
                <AreaList id="serviceFreight-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
              </a-form-model-item>
            </a-col>
            <a-col :flex="2">
              <a-form-model-item label="记账主体">
                <custList id="serviceFreight-belongDealer" dataAuthFlag="0" placeholder="请输入记账主体" ref="belongDealer" @change="belongDealerChange" />
              </a-form-model-item>
            </a-col>
            <a-col :flex="2">
              <a-button
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="serviceFreight-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="serviceFreight-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="serviceFreight-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"
          :style="{ height: tableHeight+20+'px' }"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight-80}"
          :pageSize="50"
          :pagination="{pageSizeOptions: ['20','50','100','200','500']}"
          :defaultLoadData="false"
          bordered>
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="6" :sm="24">服务费金额合计：{{ (totalData && (totalData.subsidyServiceTotal || totalData.subsidyServiceTotal==0)) ? toThousands(totalData.subsidyServiceTotal): '--' }}</a-col>
              <a-col :md="6" :sm="24">运费补贴金额合计：{{ (totalData && (totalData.subsidyShippingTotal || totalData.subsidyShippingTotal==0)) ? toThousands(totalData.subsidyShippingTotal): '--' }}</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 AreaList from '@/views/common/areaList.js'
import custList from '@/views/common/custList.vue'
// 接口
import { subsidyMonthList, subsidyMonthCount, subsidyMonthExport } from '@/api/reportData'
export default {
  name: 'MonthQueryList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, AreaList, custList },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      exportLoading: false, // 导出按钮加载状态
      monthVal: moment().format('YYYY-MM'), // 初始化月份值
      //  查询条件
      queryParam: {
        queryDate: moment().format('YYYY-MM'), // 选择月份
        dealer: {
          provinceSn: undefined, // 省
          citySn: undefined, // 市
          districtSn: undefined // 区
        },
        belongDealerSn: undefined, // 记账主体
        subareaArea: {
          subareaSn: '', // 区域
          subareaAreaSn: '' // 分区
        }
      },
      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)
        params.bizYear = params.queryDate.split('-')[0]
        params.bizMonth = params.queryDate.split('-')[1]
        delete params.queryDate
        // 获取列表数据  有分页
        return subsidyMonthList(params).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(params)
          }
          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: '4%', align: 'center' },
        { title: '月份', dataIndex: 'mothDay', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '省份', dataIndex: 'provinceName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '记账主体', dataIndex: 'belongDealerName', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '服务费(记)', dataIndex: 'subsidyServiceSales', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '服务费(扣)', dataIndex: 'subsidyServiceReturn', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '服务费合计', dataIndex: 'subsidyServiceTotal', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '运费补贴(总部记)', dataIndex: 'subsidyShippingSales', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '运费补贴(总部扣)', dataIndex: 'subsidyShippingReturn', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '运费补贴(转单记)', dataIndex: 'subsidyShippingTransferAdd', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '运费补贴(转单扣)', dataIndex: 'subsidyShippingTransferSub', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '运费补贴合计', dataIndex: 'subsidyShippingTotal', width: '10%', 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.queryDate = dateString
      } else {
        this.queryParam.queryDate = void 0
      }
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择查询月份')
          return false
        }
      })
    },
    // 记账主体
    belongDealerChange (val) {
      this.queryParam.belongDealerName = val.name
      this.queryParam.belongDealerSn = val.key
    },
    // 统计
    getCount (params) {
      subsidyMonthCount(params).then(res => {
        if (res.status == 200 && res.data) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 地区
    areaChange (val) {
      this.queryParam.dealer.provinceSn = val[0] ? val[0] : undefined
      this.queryParam.dealer.citySn = val[1] ? val[1] : undefined
      this.queryParam.dealer.districtSn = val[2] ? val[2] : undefined
    },
    // 区域分区  change
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : ''
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : ''
    },
    //  重置
    resetSearchForm () {
      this.monthVal = moment().format('YYYY-MM')
      this.queryParam.queryDate = moment().format('YYYY-MM')
      this.queryParam.dealer.provinceSn = undefined
      this.queryParam.dealer.citySn = undefined
      this.queryParam.dealer.districtSn = undefined
      this.queryParam.dealer.dealerName = undefined
      this.queryParam.subareaArea.subareaSn = ''
      this.queryParam.subareaArea.subareaAreaSn = ''
      this.queryParam.dealerLevel = undefined
      this.queryParam.belongDealerSn = undefined
      this.$refs.belongDealer.resetForm()
      this.totalData = null
      this.$refs.subarea.clearData()
      this.$refs.areaList.clearData()
      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.exportLoading = true
      _this.spinning = true
      hdExportExcel(subsidyMonthExport, params, '轮胎服务费运费报表(' + this.queryParam.queryDate + '月份)-', function () {
        _this.exportLoading = false
        _this.spinning = false
      })
    },
    // 初始化
    pageInit () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        this.setTableH()
      })
      this.resetSearchForm()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 230
    }
  },
  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>
