<template>
  <div>
    <a-card size="small" :bordered="false" class="quarterQueryList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="quarterQueryList-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 label="查询季度" prop="queryDate">
                <quarterDate ref="quarterDate" id="quarterQueryList-time" :value="timeInfo" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="地区">
                <AreaList id="quarterQueryList-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="区域/分区">
                <subarea id="quarterQueryList-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户名称">
                  <dealerSubareaScopeList ref="dealerSubareaScopeList" id="quarterQueryList-dealerName" @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="quarterQueryList-dealerLevel"
                    code="DEALER_LEVEL"
                    placeholder="请选择客户级别"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="quarterQueryList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="quarterQueryList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_tireFeeExport')"
                id="quarterQueryList-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"
          :scroll="{ y: tableHeight-120}"
          :defaultLoadData="false"
          bordered>
          <!-- 地区 -->
          <template slot="addressInfo" slot-scope="text, record">
            <span v-if="record.dealerEntity&&record.dealerEntity.provinceName">
              {{ record.dealerEntity.provinceName }}{{ '/'+record.dealerEntity.cityName }}{{ '/'+record.dealerEntity.districtName }}
            </span>
            <span v-else>--</span>
          </template>
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="4" :sm="24">平台出库数量：{{ (totalData && (totalData.outQty || totalData.outQty==0)) ? totalData.outQty: '--' }}</a-col>
              <a-col :md="4" :sm="24">平台返利点数：{{ (totalData && (totalData.rebatePointsSys || totalData.rebatePointsSys==0)) ? (totalData.rebatePointsSys*100).toFixed(2)+'%': '--' }}</a-col>
              <a-col :md="4" :sm="24">开单金额：{{ (totalData && (totalData.outAmount || totalData.outAmount==0)) ? toThousands(totalData.outAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">平台返利金额：{{ (totalData && (totalData.rebateAmountSys || totalData.rebateAmountSys==0)) ? toThousands(totalData.rebateAmountSys): '--' }}</a-col>
              <a-col :md="4" :sm="24"><a-tooltip placement="top" title="开单金额合计*1.5%">广宣品费用&nbsp;<a-icon type="question-circle" /></a-tooltip>：{{ (totalData && (totalData.posterAmount || totalData.posterAmount==0)) ? toThousands(totalData.posterAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">轮胎省仓返利金额：{{ (totalData && (totalData.rebateAmountProvince || totalData.rebateAmountProvince==0)) ? toThousands(totalData.rebateAmountProvince): '--' }}</a-col>
            </a-row>
          </template>
        </s-table>
      </a-spin>
    </a-card>
    <!-- 导出提示框 -->
    <reportModal :visible="showExport" @close="showExport=false"></reportModal>
  </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 reportModal from '@/views/common/reportModal.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
// 接口
import { tireFeeReportList, tireFeeReportCount, tireFeeListExport } from '@/api/reportData'
export default {
  name: 'QuarterQueryList',
  mixins: [commonMixin],
  components: { STable, VSelect, quarterDate, subarea, AreaList, dealerSubareaScopeList, reportModal },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      exportLoading: false, // 导出按钮加载状态
      showExport: false, // 导出弹窗
      timeInfo: [], // 日期
      //  查询条件
      queryParam: {
        queryType: 'quarter', // 轮胎季度费用报表
        queryDate: undefined, // 选择年份+季度
        dealerLevel: undefined, // 客户级别
        subareaArea: {
          subareaSn: '', // 区域
          subareaAreaSn: '' // 分区
        },
        customSn: undefined, // 客户sn
        dealerEntity: {
          dealerName: undefined, // 客户名称
          provinceSn: undefined, // 省
          citySn: undefined, // 市
          districtSn: undefined // 区
        },
        provinceFlag: '1'// 是轮胎省仓
      },
      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)
        // 获取列表数据  有分页
        return tireFeeReportList(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: '5%', align: 'center' },
        { title: '地区', scopedSlots: { customRender: 'addressInfo' }, width: '15%', align: 'center' },
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerEntity.dealerName', width: '14%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户级别', dataIndex: 'dealerEntity.dealerLevelDictValue', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: <a-tooltip placement='top' title='平台销售给该轮胎省仓及轮胎省仓差价绑定的加盟商的数量合计'>平台出库数量&nbsp;<a-icon type="question-circle" /></a-tooltip>, dataIndex: 'outQty', width: '14%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '开单金额', dataIndex: 'outAmount', width: '14%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '轮胎省仓返利点数', dataIndex: 'rebatePointProvince', width: '14%', align: 'center', customRender: function (text) { return ((text || text == 0) ? (text * 100).toFixed(2) + '%' : '--') } },
        { title: '轮胎省仓返利金额', dataIndex: 'rebateAmountProvince', width: '14%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } }
      ]
      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.dealerEntity.dealerName = val.name
      this.queryParam.customSn = val.key
    },
    // 统计
    getCount (params) {
      tireFeeReportCount(params).then(res => {
        if (res.status == 200 && res.data) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 地区
    areaChange (val) {
      this.queryParam.dealerEntity.provinceSn = val[0] ? val[0] : undefined
      this.queryParam.dealerEntity.citySn = val[1] ? val[1] : undefined
      this.queryParam.dealerEntity.districtSn = val[2] ? val[2] : undefined
    },
    //  日期选择  change
    dateChange (date, valStr) {
      this.timeInfo = date[0] && date[1] ? date : []
      if (date && date.length > 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.queryType = 'quarter'
      this.queryParam.queryDate = undefined
      this.queryParam.dealerEntity.provinceSn = undefined
      this.queryParam.dealerEntity.citySn = undefined
      this.queryParam.dealerEntity.districtSn = undefined
      this.queryParam.dealerEntity.dealerName = undefined
      this.queryParam.customSn = undefined
      this.queryParam.subareaArea.subareaSn = ''
      this.queryParam.subareaArea.subareaAreaSn = ''
      this.queryParam.dealerLevel = undefined
      this.queryParam.provinceFlag = '1'
      this.$refs.subarea.clearData()
      if (this.advanced) {
        this.$refs.dealerSubareaScopeList.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
      _this.showExport = true
      hdExportExcel(tireFeeListExport, _this.queryParam, '轮胎季度费用报表', 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 - 280
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  }
}
</script>
