<template>
  <div>
    <a-card size="small" :bordered="false" class="incSubSidyYear-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="incSubSidyYear-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="bizYear">
                <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-select
                  id="yearQueryList-time"
                  style="width: 100%"
                  placeholder="请选择年份"
                  :value="queryParam.bizYear"
                  @change="changeYear"
                  allowClear>
                  <a-select-option v-for="item in years" :value="item" :key="item">
                    {{ item }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :flex="1">
              <a-form-item label="所在区域">
                <subarea id="incSubSidyYear-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-item>
            </a-col>
            <a-col :flex="1">
              <a-form-model-item label="地区">
                <AreaList id="incSubSidyYear-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="incSubSidyYear-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="incSubSidyYear-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="incSubSidyYear-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="incSubSidyYear-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="settleAmountWait" slot-scope="text, record">
            <span v-if="record.settleAmountWait||record.settleAmountWait==0">
              <span style="color:#ED1C24;" v-if="record.settleAmountWait>0">{{ toThousands(record.settleAmountWait) }}</span>
              <span v-else>{{ toThousands(record.settleAmountWait) }}</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.settleAmountFinish || totalData.settleAmountFinish==0)) ? toThousands(totalData.settleAmountFinish): '--' }}</a-col>
              <a-col :md="4" :sm="24">剩余增量补贴金额：{{ (totalData && (totalData.settleAmountWait || totalData.settleAmountWait==0)) ? toThousands(totalData.settleAmountWait): '--' }}</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 { subsidyStepList, subsidyStepCount, subsidyStepExport } from '@/api/reportData'
export default {
  name: 'QuarterQueryList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, AreaList, custList },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      exportLoading: false, // 导出按钮加载状态
      toYears: new Date().getFullYear(), // 今年
      //  查询条件
      queryParam: {
        subsidyType: 'YEAR', // 轮胎年度费用报表
        bizYear: moment().year(), // 选择年份
        subareaArea: {
          subareaSn: '', // 区域
          subareaAreaSn: '' // 分区
        },
        customSn: undefined, // 客户sn
        dealer: {
          dealerName: undefined, // 客户名称
          provinceSn: undefined, // 省
          citySn: undefined, // 市
          districtSn: undefined // 区
        }
      },
      totalData: null, // 合计
      rules: {
        'bizYear': [{ required: true, message: '请选择查询年份', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        // 获取列表数据  有分页
        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
            }
            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: {
    // 获取年份数据
    years () {
      const years = []
      const lens = (this.toYears - 2023) + 1
      for (let i = 0; i < lens; i++) {
        years.push(this.toYears - i)
      }
      return years
    },
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { 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' } },
        { title: '增量已补金额', dataIndex: 'settleAmountFinish', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '剩余增量补贴金额', dataIndex: 'settleAmountWait', width: '11%', align: 'right', scopedSlots: { customRender: 'settleAmountWait' } }
      ]
      return arr
    }
  },
  methods: {
    // 选择查询年份  change
    changeYear (val) {
      if (!val) {
        this.queryParam.bizYear = void 0
      } else {
        this.queryParam.bizYear = val
      }
    },
    // 查询
    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
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : ''
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : ''
    },
    //  重置
    resetSearchForm () {
      this.queryParam.subsidyType = 'YEAR'
      this.queryParam.bizYear = moment().year()
      this.queryParam.dealer.provinceSn = undefined
      this.queryParam.dealer.citySn = undefined
      this.queryParam.dealer.districtSn = undefined
      this.queryParam.dealerName = undefined
      this.queryParam.belongDealerSn = undefined
      this.queryParam.subareaArea.subareaSn = ''
      this.queryParam.subareaArea.subareaAreaSn = ''
      this.$refs.subarea.clearData()
      this.$refs.custList.resetForm()
      this.totalData = null
      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
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(subsidyStepExport, _this.queryParam, '增量补贴报表(' + this.queryParam.bizYear + '年度)-', 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>
