<template>
  <a-spin :spinning="spinning" tip="Loading...">
    <div class="productInfoList-wrap">
      <div ref="tableSearch" class="table-page-search-wrapper newTableSearchName">
        <a-form-model layout="inline" ref="ruleForm" :rules="rules" :model="newQueryParam">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="销售审核日期" prop="salesDate">
                <rangeDate ref="rangeDate" :value="newQueryParam.salesDate" @change="salesDateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <!-- :disabledDate="disabledDate" -->
              <a-form-model-item label="促销开始时间">
                <a-range-picker
                  style="width:100%"
                  v-model="time"
                  :format="dateFormat"
                  :placeholder="['开始时间', '结束时间']"
                  @change="dateChange"></a-range-picker>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="促销名称">
                <a-input
                  id="promotionSalesRealTimeReport-title"
                  v-model.trim="newQueryParam.promoRuleReport.title"
                  allowClear
                  placeholder="请输入促销名称" />
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="促销类型">
                  <v-select
                    v-model="newQueryParam.promoRuleReport.promotionRuleType"
                    ref="ruleType"
                    id="promotionSalesRealTimeReport-ruleType"
                    code="PROMOTION_RULE_TYPE"
                    placeholder="请选择促销类型"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="规则">
                  <a-input
                    id="promotionSalesRealTimeReport-description"
                    v-model.trim="newQueryParam.promoRuleReport.description"
                    allowClear
                    placeholder="请输入规则关键字" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="销售单号">
                  <a-input
                    id="promotionSalesRealTimeReport-salesBillNo"
                    v-model.trim="newQueryParam.salesBillNo"
                    allowClear
                    placeholder="请输入销售单号" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户级别">
                  <v-select
                    v-model="newQueryParam.buyerLevel"
                    ref="buyerLevel"
                    id="promotionSalesRealTimeReport-buyerLevel"
                    code="DEALER_LEVEL"
                    placeholder="请选择客户级别"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户名称">
                  <a-input
                    id="promotionSalesRealTimeReport-buyerName"
                    v-model.trim="newQueryParam.buyerName"
                    allowClear
                    placeholder="请输入客户名称" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所在区域">
                  <subarea ref="subarea" id="promotionSalesRealTimeReport-subarea" @change="subareaChange"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区">
                  <AreaList id="promotionSalesRealTimeReport-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="disabled" @click="testForm('search')">查询</a-button>
                <a-button style="margin-left: 8px" :disabled="disabled" @click="resetSearchForm">重置</a-button>
                <a-button
                  style="margin-left: 10px"
                  type="primary"
                  class="button-warning"
                  @click="testForm('export')"
                  :disabled="disabled"
                  :loading="exportLoading"
                  v-if="$hasPermissions('B_promotionSalesExport')">导出</a-button>
                <a @click="advanced=!advanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.no"
        rowKeyName="no"
        :columns="columns"
        :data="loadData"
        :style="{ height: tableHeight+84.5+'px' }"
        :scroll="{ y: tableHeight-40,x:1890}"
        :defaultLoadData="false"
        bordered>
        <!-- 促销时间 -->
        <template slot="promotionTime" slot-scope="text, record">
          <span>{{ record.promotion.promotionDateStart }}-{{ record.promotion.promotionDateEnd }}</span>
        </template>
        <!-- 规则 -->
        <template slot="promotionDesc" slot-scope="text, record">
          <span v-if="record.promotionRule.promotionRuleType=='PROMO_PROD'">{{ record.promotionRule.promotionRuleTypeDictValue }}</span>
          <span v-else-if="record.promotionRule.promotionRuleType=='RATIO_AMOUNT'">{{ record.promotionRule.regularSameFlag==1?'同款':'不同款' }}产品购买满{{ record.promotionRule.regularQty }}个正价产品，送{{ record.promotionQty }}个促销产品</span>
          <span v-else>购买满{{ record.promotionRule.regularAmount }}元正价产品，送{{ record.promotionRule.giveAmount }}元促销品采购额{{ record.promotionRule.accrualFlag&&record.promotionRule.accrualFlag==1?'(金额叠加)':'(金额不叠加)' }}</span>
        </template>
        <!-- 地区 -->
        <template slot="addressInfo" slot-scope="text, record">
          <span>{{ record.provinceName }}{{ record.cityName?'/'+record.cityName:'' }}{{ record.districtName?'/'+record.districtName :'' }}</span>
        </template>
        <template slot="footer">
          <a-row>
            <a-col span="24">
              <a-row>
                <a-col
                  span="3">实时数量（非促）：{{ (totalData && (totalData.notGiftQty || totalData.notGiftQty==0)) ? totalData.notGiftQty : '--' }}</a-col>
                <a-col
                  span="3">实时数量（促）：{{ (totalData && (totalData.giftQty || totalData.giftQty==0)) ? totalData.giftQty : '--' }}</a-col>
                <a-col
                  span="3">实时实售金额：{{ (totalData && (totalData.totalRealAmount || totalData.totalRealAmount==0)) ? toThousands(totalData.totalRealAmount) : '--' }}</a-col>
                <a-col
                  span="3">实时开单金额：{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? toThousands(totalData.totalAmount) : '--' }}</a-col>
                <a-col
                  span="3">实时成本金额：{{ (totalData && (totalData.totalRealCost || totalData.totalRealCost==0)) ? toThousands(totalData.totalRealCost) : '--' }}</a-col>
                <a-col
                  span="4">实时损失成本：{{ (totalData && (totalData.lossCost || totalData.lossCost==0)) ? toThousands(totalData.lossCost) : '--' }}</a-col>
                <a-col
                  span="5">实时损失费用：{{ (totalData && (totalData.lossAmount || totalData.lossAmount==0)) ? toThousands(totalData.lossAmount) : '--' }}</a-col>
              </a-row>
            </a-col>
          </a-row>
        </template>
      </s-table>
    </div>
    <!-- 导出提示框 -->
    <reportModal :visible="showExport" @close="showExport=false"></reportModal>
  </a-spin>
</template>

<script>
import {
  commonMixin
} from '@/utils/mixin'
import {
  salesPromoRealReportList,
  salesPromoRealReportCount,
  exportSalesPromoRealReport
} from '@/api/reportData'
import {
  hdExportExcel
} from '@/libs/exportExcel'
import {
  STable,
  VSelect
} from '@/components'
import reportModal from '@/views/common/reportModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import subarea from '@/views/common/subarea.js'
import AreaList from '@/views/common/areaList.js'
import getDate from '@/libs/getDate.js'
export default {
  name: 'QueryPart',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    reportModal,
    AreaList,
    rangeDate,
    subarea
  },
  data () {
    const _this = this
    return {
      advanced: true, // 高级搜索 展开/关闭
      time: undefined,
      spinning: false,
      disabled: false,
      tableHeight: 0,
      newQueryParam: { // 查询条件
        salesDate: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginAuditDate: getDate.getCurrMonthDays().starttime, // 审核开始时间
        endAuditDate: getDate.getCurrMonthDays().endtime, // 审核结束时间
        promoRuleReport: {
          promotionDateStart: undefined, // 促销时间-开始
          promotionDateEnd: undefined, // 促销时间-结束
          title: '', // 促销名称
          promotionRuleType: undefined, // 促销类型
          description: '' // 规则
        },
        salesBillNo: '', // 销售单号
        buyerLevel: undefined, // 客户级别
        buyerName: '', // 客户名称
        subareaArea: {
          subareaSn: '',
          subareaAreaSn: ''
        },
        dealerProvinceSn: undefined, // 省份编码
        dealerCitySn: undefined, // 城市编码
        dealerDistrictSn: undefined // 区域编码
      },
      rules: {
        salesDate: [{
          required: true,
          message: '请选择销售审核日期',
          trigger: 'change'
        }]
      },
      dateFormat: 'YYYY-MM-DD',
      totalData: null, //  合计
      exportLoading: false,
      showExport: false,
      columns: [{
        title: '促销名称',
        dataIndex: 'promotion.title',
        width: '160px',
        align: 'center',
        customRender: function (text) {
          return text || '--'
        },
        fixed: 'left',
        ellipsis: true
      },
      {
        title: '促销时间',
        scopedSlots: {
          customRender: 'promotionTime'
        },
        width: '130px',
        align: 'center',
        fixed: 'left'
      },
      {
        title: '费用所属部门',
        dataIndex: 'departmentName',
        width: '160px',
        align: 'center',
        customRender: function (text) {
          return text || '--'
        },
        ellipsis: true,
        fixed: 'left'
      },
      {
        title: '促销类型',
        dataIndex: 'promotionRule.promotionRuleTypeDictValue',
        width: '100px',
        align: 'center',
        customRender: function (text) {
          return text || '--'
        },
        fixed: 'left'
      },
      { title: '规则', dataIndex: 'promotionRule.description', width: '180px', align: 'center', scopedSlots: { customRender: 'promotionDesc' }, fixed: 'left' },
      {
        title: '销售单号',
        dataIndex: 'salesBillNo',
        width: '120px',
        align: 'center',
        customRender: function (text) {
          return text || '--'
        },
        fixed: 'left'
      },
      {
        title: '区域',
        dataIndex: 'subareaArea.subareaName',
        width: '80px',
        align: 'center',
        customRender: function (text) {
          return text || '--'
        }
      },
      {
        title: '分区',
        dataIndex: 'subareaArea.subareaAreaName',
        width: '80px',
        align: 'center',
        customRender: function (text) {
          return text || '--'
        }
      },
      {
        title: '地区',
        dataIndex: 'provinceName',
        width: '160px',
        align: 'center',
        scopedSlots: { customRender: 'addressInfo' }
      },
      {
        title: '客户名称',
        dataIndex: 'buyerName',
        width: '140px',
        align: 'center',
        customRender: function (text) {
          return text || '--'
        },
        ellipsis: true
      },
      {
        title: '客户级别',
        dataIndex: 'buyerLevelDictValue',
        width: '80px',
        align: 'center',
        customRender: function (text) {
          return text || '--'
        }
      },
      {
        title: '销售审核日期',
        dataIndex: 'auditDate',
        width: '120px',
        align: 'center',
        customRender: function (text) {
          return text || '--'
        }
      },
      {
        title: '实时数量(非促)',
        dataIndex: 'notGiftQty',
        width: '100px',
        align: 'center',
        customRender: function (text) {
          return ((text || text == 0) ? text : '--')
        }
      },
      {
        title: '实时数量(促)',
        dataIndex: 'giftQty',
        width: '100px',
        align: 'center',
        customRender: function (text) {
          return ((text || text == 0) ? text : '--')
        }
      },
      {
        title: '实时实售金额',
        dataIndex: 'totalRealAmount',
        width: '100px',
        align: 'center',
        customRender: function (text) {
          return ((text || text == 0) ? _this.toThousands(text) : '--')
        }
      },
      {
        title: '实时开单金额',
        dataIndex: 'totalAmount',
        width: '100px',
        align: 'center',
        customRender: function (text) {
          return ((text || text == 0) ? _this.toThousands(text) : '--')
        }
      },
      {
        title: '实时成本金额',
        dataIndex: 'totalRealCost',
        width: '100px',
        align: 'center',
        customRender: function (text) {
          return ((text || text == 0) ? _this.toThousands(text) : '--')
        }
      },
      {
        title: '实时损失成本',
        dataIndex: 'lossCost',
        width: '100px',
        align: 'center',
        customRender: function (text) {
          return ((text || text == 0) ? _this.toThousands(text) : '--')
        }
      },
      {
        title: '实时损失费用',
        dataIndex: 'lossAmount',
        width: '100px',
        align: 'center',
        customRender: function (text) {
          return ((text || text == 0) ? _this.toThousands(text) : '--')
        }
      }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        this.disabled = true
        const params = Object.assign(parameter, this.newQueryParam)
        return salesPromoRealReportList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            for (var i = 0; i < data.length; i++) {
              data[i].no = i + 1
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    salesDateChange (date) {
      if (date[0] && date[1]) {
        this.newQueryParam.salesDate = date
      } else {
        this.newQueryParam.salesDate = []
      }
      this.newQueryParam.beginAuditDate = date[0] || ''
      this.newQueryParam.endAuditDate = date[1] || ''
    },
    areaChange (val) {
      this.newQueryParam.dealerProvinceSn = val[0] ? val[0] : ''
      this.newQueryParam.dealerCitySn = val[1] ? val[1] : ''
      this.newQueryParam.dealerDistrictSn = val[2] ? val[2] : ''
    },
    dateChange (date, dateString) {
      this.time = date
      if (dateString[0] != '' && dateString[1] != '') {
        this.newQueryParam.promoRuleReport.promotionDateStart = dateString[0] + ' 00:00:00'
        this.newQueryParam.promoRuleReport.promotionDateEnd = dateString[1] + ' 23:59:59'
      } else {
        this.$set(this.newQueryParam.promoRuleReport, 'promotionDateStart', undefined)
        this.$set(this.newQueryParam.promoRuleReport, 'promotionDateEnd', undefined)
      }
    },
    subareaChange (val) {
      this.newQueryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.newQueryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // 查询
    testForm (type) {
      const _this = this
      if (!_this.newQueryParam.salesDate && (!_this.newQueryParam.salesDate[0] || !_this.newQueryParam.salesDate[1])) {
        _this.$message.error('请选择销售审核日期')
        return
      }
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (type == 'search') {
            _this.resetCurForm()
          } else {
            _this.handleExport()
          }
        } else {
          _this.$message.error('请选择销售审核日期')
          return false
        }
      })
    },
    // 统计
    getCount (params) {
      salesPromoRealReportCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 刷新当前页面
    resetCurForm () {
      const params = JSON.parse(JSON.stringify(this.newQueryParam))
      delete params.salesDate
      this.$nextTick(() => {
        this.getCount(params)
        this.$refs.table.refresh()
      })
    },
    // 导出
    handleExport () {
      const _this = this
      const params = this.newQueryParam
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(exportSalesPromoRealReport, params, '促销销售单实时报表导出', function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.showExport = true
      })
    },
    resetSearchForm () {
      this.$refs.ruleForm.resetFields()
      this.newQueryParam = {
        beginAuditDate: getDate.getCurrMonthDays().starttime, // 审核开始时间
        endAuditDate: getDate.getCurrMonthDays().endtime, // 审核结束时间
        promoRuleReport: {
          promotionDateStart: undefined, // 促销时间-开始
          promotionDateEnd: undefined, // 促销时间-结束
          title: '', // 促销名称
          promotionRuleType: undefined, // 促销类型
          description: '' // 规则
        },
        salesBillNo: '', // 销售单号
        buyerLevel: undefined, // 客户级别
        buyerName: '', // 客户名称
        subareaArea: {
          subareaSn: '',
          subareaAreaSn: ''
        },
        dealerProvinceSn: undefined, // 省份编码
        dealerCitySn: undefined, // 城市编码
        dealerDistrictSn: undefined // 区域编码
      }
      this.$set(this.newQueryParam, 'salesDate', [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ])
      this.time = undefined
      this.$refs.subarea.clearData()
      this.$refs.areaList.clearData()
      this.$refs.rangeDate.resetDate(this.newQueryParam.salesDate)
      this.$refs.table.clearTable()
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 260
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  }
}
</script>
<style lang="less" scoped>
  .productInfoList-wrap {
    .ellipsisCon {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .ellipsisText {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        display: box;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
    }
  }
</style>
