<template>
  <div>
    <a-card size="small" :bordered="false" class="incSubSidy-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="incSubSidy-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>
                <quarterDate ref="quarterDate" id="incSubSidy-time" :value="timeInfo" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :flex="1">
              <a-form-item label="所在区域">
                <subarea id="incSubSidy-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-item>
            </a-col>
            <a-col :flex="1">
              <a-form-model-item label="地区">
                <AreaList id="incSubSidy-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="incSubSidy-dealerName" dataAuthFlag="0" placeholder="请输入客户名称" ref="custList" @change="custChange" />
              </a-form-model-item>
            </a-col>
            <a-col :flex="2">
              <a-button
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="incSubSidy-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="incSubSidy-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="incSubSidy-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="30"
          :defaultLoadData="false"
          bordered>
          <!-- 季度增量补贴金额 -->
          <template slot="subsidyAmount" slot-scope="text, record">
            <span v-if="record.subsidyAmount||record.subsidyAmount==0">
              <span v-if="record.subsidyAmount>=0">{{ toThousands(record.subsidyAmount) }}</span>
              <span style="color:#ED1C24;" v-else>{{ toThousands(record.subsidyAmount) }}</span>
            </span>
            <span v-else>--</span>
          </template>
          <!-- 统计 -->
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="4" :sm="24">总部合计数量:{{ (totalData && (totalData.headTotalQty || totalData.headTotalQty==0)) ? totalData.headTotalQty: '--' }}</a-col>
              <a-col :md="4" :sm="24">合计订货数量:{{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ? totalData.totalQty: '--' }}</a-col>
              <a-col :md="4" :sm="24">增量补贴金额:{{ (totalData && (totalData.subsidyAmount || totalData.subsidyAmount==0)) ? toThousands(totalData.subsidyAmount): '--' }}</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 quarterDate from '@/views/common/quarterDate.vue'
import subarea from '@/views/common/subarea.js'
import AreaList from '@/views/common/areaList.js'
import custList from '@/views/common/custList.vue'
// 接口
import { subsidyStepList, subsidyStepCount, subsidyStepExport } from '@/api/reportData'
export default {
  name: 'QuarterQueryList',
  mixins: [commonMixin],
  components: { STable, VSelect, quarterDate, subarea, AreaList, custList },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      exportLoading: false, // 导出按钮加载状态
      timeInfo: [], // 日期
      //  查询条件
      queryParam: {
        subsidyType: 'QUARTER', // 轮胎季度费用报表
        queryDate: undefined, // 选择年份+季度
        subareaArea: {
          subareaSn: '', // 区域
          subareaAreaSn: '' // 分区
        },
        belongDealerSn: undefined, // 客户sn
        dealer: {
          provinceSn: undefined, // 省
          citySn: undefined, // 市
          districtSn: undefined // 区
        }
      },
      totalData: null, // 合计
      rules: {
        'queryDate': [{ required: true, message: '请选择查询年度', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const dateStr = this.queryParam.queryDate
        const year = dateStr.substr(0, 4)
        const quarter = dateStr.substr(5, 1)
        const params = Object.assign(parameter, this.queryParam, { bizYear: year, bizQuarter: quarter == 'u' ? undefined : quarter })
        console.log(params)
        // 获取列表数据  有分页
        return subsidyStepList(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
              data.list[i].quarter = ['一', '二', '三', '四'][data.list[i].bizQuarter - 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: 'bizYear', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '季度', dataIndex: 'quarter', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '省份', dataIndex: 'provinceName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerName', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '总部订货数量', dataIndex: 'salesQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总部退货数量', dataIndex: 'returnQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总部合计数量', dataIndex: 'headTotalQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '转单订货数量', dataIndex: 'transferQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '轮胎省仓销售数量', dataIndex: 'qplsSalesQty', width: '11%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '合计订货数量', dataIndex: 'totalQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '季度目标', dataIndex: 'subsidyTarget', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '季度增量补贴', dataIndex: 'subsidyValue', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '增量补贴金额', dataIndex: 'subsidyAmount', width: '10%', align: 'right', scopedSlots: { customRender: 'subsidyAmount' } }
      ]
      return arr
    }
  },
  methods: {
    // 获取季度默认值
    getQuarterVal () {
      // 获取当月是今年的第几季度
      const lastQuarter = moment().quarter()
      // 获取今年年份
      const thisYear = moment().year()
      this.timeInfo = [thisYear, lastQuarter]
      this.queryParam.queryDate = thisYear + '0' + lastQuarter
    },
    // 查询
    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.dealerName = val.name
      this.queryParam.belongDealerSn = val.key
    },
    // 统计
    getCount (params) {
      subsidyStepCount(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
    dateChange (date, valStr) {
      console.log(date)
      this.timeInfo = date[0] && date[1] ? date : []
      if (date && date.length && date[0]) {
        this.queryParam.queryDate = date[0] + '0' + date[1]
      } else {
        this.queryParam.queryDate = undefined
      }
    },
    // 区域分区  change
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : ''
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : ''
    },
    //  重置
    resetSearchForm () {
      this.queryParam.subsidyType = 'QUARTER'
      this.queryParam.queryDate = undefined
      this.queryParam.dealer.provinceSn = undefined
      this.queryParam.dealer.citySn = undefined
      this.queryParam.dealer.districtSn = undefined
      this.queryParam.subareaArea.subareaSn = ''
      this.queryParam.subareaArea.subareaAreaSn = ''
      this.queryParam.belongDealerSn = undefined // 客户sn
      this.queryParam.dealerName = undefined
      this.$refs.subarea.clearData()
      this.$refs.custList.resetForm()
      this.totalData = null
      this.$refs.areaList.clearData()
      this.$refs.table.clearTable()
      this.$refs.ruleForm.resetFields()
      this.getQuarterVal()
    },
    //  导出  必填判断
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.exportList()
        } else {
          _this.$message.error('请选择查询季度')
          return false
        }
      })
    },
    // 导出
    exportList () {
      const _this = this
      _this.exportLoading = true
      _this.spinning = true
      const dateStr = this.queryParam.queryDate
      const year = dateStr.substr(0, 4)
      const quarter = dateStr.substr(5, 1)
      const params = Object.assign(this.queryParam, { bizYear: year, bizQuarter: quarter == 'u' ? undefined : quarter })
      hdExportExcel(subsidyStepExport, 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>