<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <a-tabs default-active-key="1" @change="handleChange" :tabBarStyle="{'background':'#fff'}">
        <a-tab-pane key="1" tab="促销销售单报表">
          <a-card size="small" :bordered="false" class="promotionSalesRealTimeReport-wrap searchBoxNormal">
            <div ref="tableSearch" class="table-page-search-wrapper newTableSearchName">
              <!-- 查询条件 -->
              <a-form-model
                layout="inline"
                ref="ruleForm"
                id="promotionSalesRealTimeReport-form"
                :rules="rules"
                :model="queryParam">
                <a-row :gutter="15">
                  <a-col :md="6" :sm="24">
                    <a-form-model-item label="销售审核时间" prop="salesDate">
                      <rangeDate ref="rangeDate" id="promotionSalesRealTimeReport-salesDate" :value="queryParam.salesDate" @change="salesDateChange" />
                    </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="queryParam.promoRuleReport.title" allowClear placeholder="请输入促销名称"/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-form-model-item label="促销类型">
                      <v-select
                        v-model="queryParam.promoRuleReport.promotionRuleType"
                        ref="ruleType"
                        id="promotionSalesRealTimeReport-ruleType"
                        code="PROMOTION_RULE_TYPE"
                        placeholder="请选择促销类型"
                        allowClear></v-select>
                    </a-form-model-item>
                  </a-col>
                  <template v-if="advanced">
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="销售单号">
                        <a-input id="promotionSalesRealTimeReport-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="促销开始时间">
                        <a-range-picker
                          id="promotionSalesRealTimeReport-time"
                          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-ruleInfo" v-model.trim="queryParam.promoRuleReport.ruleInfo" allowClear placeholder="请输入规则关键字"/>
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="客户级别">
                        <v-select
                          v-model="queryParam.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="queryParam.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>
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="采购额">
                        <v-select
                          v-model="queryParam.giveMoney"
                          ref="giveMoney"
                          id="promotionSalesRealTimeReport-giveMoney"
                          code="GIVE_MONEY"
                          placeholder="请选择采购额"
                          allowClear></v-select>
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                      <a-form-model-item label="客服">
                        <customerService id="promotionSalesRealTimeReport-customerName" ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="新/老客户">
                        <a-select id="promotionSalesRealTimeReport-dealerNewFlag" v-model="queryParam.dealerNewFlag" placeholder="请选择" allowClear>
                          <a-select-option value="1">新客户</a-select-option>
                          <a-select-option value="0">老客户</a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                  </template>
                  <a-col :md="!isShowCustomerSearch?24:6" :sm="24" style="margin-bottom: 10px;" :style="{textAlign: !isShowCustomerSearch?'center':''}">
                    <div class="table-page-search-submitButtons">
                      <a-button type="primary" id="promotionSalesRealTimeReport-refresh" :disabled="disabled" @click="testForm('search')" >查询</a-button>
                      <a-button style="margin-left: 8px" id="promotionSalesRealTimeReport-reset" :disabled="disabled" @click="resetSearchForm">重置</a-button>
                      <a-button
                        style="margin-left: 10px"
                        type="primary"
                        class="button-warning"
                        @click="testForm('export')"
                        :disabled="disabled"
                        :loading="exportLoading"
                        id="promotionSalesRealTimeReport-export"
                        v-if="$hasPermissions('B_promotionSalesExport')"
                      >导出</a-button>
                      <a @click="advanced=!advanced" style="margin-left: 8px">
                        {{ advanced ? '收起' : '展开' }}
                        <a-icon :type="advanced ? 'up' : 'down'"/>
                      </a>
                    </div>
                  </a-col>
                </a-row>
              </a-form-model>
            </div>
          </a-card>
          <!-- 列表 -->
          <a-card size="small" :bordered="false">
            <s-table
              class="sTable fixPagination"
              ref="table"
              size="small"
              :rowKey="(record) => record.no"
              rowKeyName="no"
              :columns="columns"
              :data="loadData"
              :pageSize="30"
              :style="{ height: tableHeight+84.5+'px' }"
              :scroll="{ x:1890,y: tableHeight-34}"
              :defaultLoadData="false"
              bordered>
              <!-- 促销时间 -->
              <template slot="promotionTime" slot-scope="text, record">
                <span v-if="record.promotion && record.promotion.promotionDateStart">{{ record.promotion.promotionDateStart }}-{{ record.promotion.promotionDateEnd }}</span>
                <span v-else>--</span>
              </template>
              <!-- 规则 -->
              <template slot="promotionDesc" slot-scope="text, record">
                <div v-if="record.ruleInfo" v-html="record.ruleInfo"></div>
                <span v-else>--</span>
              </template>
              <!-- 地区 -->
              <template slot="addressInfo" slot-scope="text, record">
                <span v-if="record.provinceName">{{ record.provinceName }}{{ record.cityName?'/'+record.cityName:'' }}{{ record.districtName?'/'+record.districtName :'' }}</span>
                <span v-else>--</span>
              </template>
              <template slot="footer">
                <a-row>
                  <a-col span="24">
                    <a-row>
                      <a-col span="4">数量（非促）：{{ (totalData && (totalData.notGiftQty || totalData.notGiftQty==0)) ? totalData.notGiftQty : '--' }}</a-col>
                      <a-col span="4">数量（促）：{{ (totalData && (totalData.giftQty || totalData.giftQty==0)) ? totalData.giftQty: '--' }}</a-col>
                      <a-col span="4">实售金额：{{ (totalData && (totalData.totalRealAmount || totalData.totalRealAmount==0)) ? toThousands(totalData.totalRealAmount) : '--' }}</a-col>
                      <a-col span="4">开单金额：{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? toThousands(totalData.totalAmount) : '--' }}</a-col>
                      <a-col span="4">成本金额：{{ (totalData && (totalData.totalRealCost || totalData.totalRealCost==0)) ? totalData.totalRealCost : '--' }}</a-col>
                      <a-col span="4">损失成本：{{ (totalData && (totalData.lossCost || totalData.lossCost==0)) ? toThousands(totalData.lossCost) : '--' }}</a-col>
                      <a-col span="4">损失费用：{{ (totalData && (totalData.lossAmount || totalData.lossAmount==0)) ? toThousands(totalData.lossAmount) : '--' }}</a-col>
                      <a-col span="4">采购额结余：{{ (totalData && (totalData.surplusPromoGiftsAmount || totalData.surplusPromoGiftsAmount==0)) ? toThousands(totalData.surplusPromoGiftsAmount) : '--' }}</a-col>
                      <a-col span="4">采购额超出：{{ (totalData && (totalData.outPromoGiftsAmount || totalData.outPromoGiftsAmount==0)) ? toThousands(totalData.outPromoGiftsAmount) : '--' }}</a-col>
                      <a-col span="4">转采购额数量：{{ (totalData && (totalData.convertPromoGiftsQty || totalData.convertPromoGiftsQty==0)) ? totalData.convertPromoGiftsQty : '--' }}</a-col>
                      <a-col span="4">转采购额金额：{{ (totalData && (totalData.convertPromoGiftsAmount || totalData.convertPromoGiftsAmount==0)) ? toThousands(totalData.convertPromoGiftsAmount) : '--' }}</a-col>
                      <a-col span="4">促销金额：{{ (totalData && (totalData.promoAmount || totalData.promoAmount==0)) ? toThousands(totalData.promoAmount) : '--' }}</a-col>
                    </a-row>
                  </a-col>
                </a-row>
              </template>
            </s-table>
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="2" tab="促销销售单实时报表" force-render>
          <gatherList></gatherList>
        </a-tab-pane>
      </a-tabs>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
    </a-spin>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import reportModal from '@/views/common/reportModal.vue'
import gatherList from './list'
import rangeDate from '@/views/common/rangeDate.vue'
import subarea from '@/views/common/subarea.js'
import AreaList from '@/views/common/areaList.js'
import customerService from '@/views/common/customerService'
// 接口
import { salesPromoReportList, salesPromoReportQueryCount, exportSalesPromoReport } from '@/api/reportData'
export default {
  name: 'PriceDifferenceDetailReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, gatherList, reportModal, AreaList, rangeDate, subarea, customerService },
  data () {
    const _this = this
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      time: undefined, // 促销开始时间
      queryParam: {
        // 促销审核时间默认值
        salesDate: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginAuditDate: getDate.getCurrMonthDays().starttime, // 审核开始时间
        endAuditDate: getDate.getCurrMonthDays().endtime, // 审核结束时间
        promoRuleReport: {
          promotionDateStart: undefined, // 促销时间-开始
          promotionDateEnd: undefined, // 促销时间-结束
          title: '', // 促销名称
          promotionRuleType: undefined, // 促销类型
          ruleInfo: ''// 规则
        },
        salesBillNo: '', // 销售单号
        buyerLevel: undefined, // 客户级别
        buyerName: '', // 客户名称
        subareaArea: {
          subareaSn: '', // 区域
          subareaAreaSn: ''// 分区
        },
        dealerProvinceSn: undefined, // 省份编码
        dealerCitySn: undefined, // 城市编码
        dealerDistrictSn: undefined, // 区域编码
        giveMoney: undefined, // 采购额
        bizUserSn: undefined, // 客服
        dealerNewFlag: undefined // 客户类型
      },
      rules: {
        salesDate: [{ required: true, message: '请选择销售审核时间', trigger: 'change' }]
      },
      dateFormat: 'YYYY-MM-DD', // 时间格式
      tabVal: 1, // tab值  1促销销售单报表 2促销销售单实时报表
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      totalData: null, //  合计
      exportLoading: false, // 导出按钮加载状态
      showExport: false, // 导出弹窗
      columns: [
        { title: '促销名称', dataIndex: 'promotion.title', width: '160px', align: 'left', 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.ruleInfo', width: '180px', align: 'left', 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: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '开单金额', dataIndex: 'totalAmount', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '成本金额', dataIndex: 'totalRealCost', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '损失成本', dataIndex: 'lossCost', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '损失费用', dataIndex: 'lossAmount', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: <a-tooltip placement='top' title='即在下推时促销产品已转采购额的数量'>转采购额数量&nbsp;<a-icon type="question-circle" /></a-tooltip>, dataIndex: 'convertPromoGiftsQty', width: '100px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: <a-tooltip placement='top' title='即促销产品转采购额金额，促销产品转采购额数量*销售价'>转采购额金额&nbsp;<a-icon type="question-circle" /></a-tooltip>, dataIndex: 'convertPromoGiftsAmount', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '采购额结余', dataIndex: 'surplusPromoGiftsAmount', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '采购额超出', dataIndex: 'outPromoGiftsAmount', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '促销金额', dataIndex: 'promoAmount', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '促销品费用归属品牌', dataIndex: 'promoProductBrandName', width: '120px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '促销品费用归属分类', dataIndex: 'promoProductTypeName', width: '120px', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        const newParams = JSON.parse(JSON.stringify(params))
        delete newParams.salesDate
        this.spinning = true
        // 促销销售单报表  列表  有分页
        return salesPromoReportList(newParams).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.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    // 销售审核时间  change
    salesDateChange (date) {
      if (date[0] && date[1]) {
        this.queryParam.salesDate = date
      } else {
        this.queryParam.salesDate = []
      }
      this.queryParam.beginAuditDate = date[0] || ''
      this.queryParam.endAuditDate = date[1] || ''
    },
    // 促销开始时间  change
    dateChange (date, dateString) {
      this.time = date
      if (dateString[0] != '' && dateString[1] != '') {
        this.queryParam.promoRuleReport.promotionDateStart = dateString[0] + ' 00:00:00'
        this.queryParam.promoRuleReport.promotionDateEnd = dateString[1] + ' 23:59:59'
      } else {
        this.$set(this.queryParam.promoRuleReport, 'promotionDateStart', undefined)
        this.$set(this.queryParam.promoRuleReport, 'promotionDateEnd', undefined)
      }
    },
    // 统计
    getCount (params) {
      salesPromoReportQueryCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 区域分区
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // tab 切换 change
    handleChange (val) {
      this.tabVal = val
    },
    // 导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      _this.exportLoading = true
      _this.spinning = true
      const ajaxUrl = _this.tabVal == 1 ? exportSalesPromoReport : exportSalesPromoRealReport
      const ajaxName = _this.tabVal == 1 ? '促销销售单报表导出' : '促销销售单实时报表导出'
      hdExportExcel(ajaxUrl, params, ajaxName, function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.showExport = true
      })
    },
    // 验证表单 type值  search查询 export导出
    testForm (type) {
      const _this = this
      if (!_this.queryParam.salesDate[0] || !_this.queryParam.salesDate[1]) {
        _this.$message.error('请选择销售审核时间')
        return
      }
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (type == 'search') {
            _this.handleSearch()
          } else {
            _this.handleExport()
          }
        } else {
          _this.$message.error('请选择销售审核时间')
          return false
        }
      })
    },
    // 地区
    areaChange (val) {
      this.queryParam.dealerProvinceSn = val[0] ? val[0] : ''
      this.queryParam.dealerCitySn = val[1] ? val[1] : ''
      this.queryParam.dealerDistrictSn = val[2] ? val[2] : ''
    },
    // 查询
    handleSearch () {
      const _this = this
      const paramData = JSON.parse(JSON.stringify(this.queryParam))
      delete paramData.salesDate
      // 获取统计数据
      _this.getCount(paramData)
      _this.$refs.table.refresh(true)
    },
    // 重置
    resetSearchForm () {
      this.$refs.ruleForm.resetFields()
      this.queryParam = {
        salesDate: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginAuditDate: getDate.getCurrMonthDays().starttime, // 审核开始时间
        endAuditDate: getDate.getCurrMonthDays().endtime, // 审核结束时间
        promoRuleReport: {
          promotionDateStart: undefined, // 促销时间-开始
          promotionDateEnd: undefined, // 促销时间-结束
          title: '', // 促销名称
          promotionRuleType: undefined, // 促销类型
          ruleInfo: ''// 规则
        },
        salesBillNo: '', // 销售单号
        buyerLevel: undefined, // 客户级别
        buyerName: '', // 客户名称
        subareaArea: {
          subareaSn: '',
          subareaAreaSn: ''
        },
        dealerProvinceSn: undefined, // 省份编码
        dealerCitySn: undefined, // 城市编码
        dealerDistrictSn: undefined, // 区域编码
        giveMoney: undefined,
        bizUserSn: undefined, // 客服
        dealerNewFlag: undefined // 自定义
      }
      this.time = undefined
      this.$refs.subarea.clearData()
      this.$refs.areaList.clearData()
      this.$refs.rangeDate.resetDate(this.queryParam.salesDate)
      this.$refs.table.clearTable()
      this.totalData = null
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 260
    }
  },
  watch: {
    // 展开关闭
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  }
}

</script>

<style lang="less" scoped>
  .monthBox{
    /deep/.ant-calendar-picker-icon{
      display:none !important;
    }
    /deep/.ant-calendar-picker input{
      text-align:center;
    }
  }
  .promotionSalesRealTimeReport-wrap{
    /deep/ .ant-card-body:first-child{
      padding-bottom: 0;
    }
  }
  .ant-tabs-tabpane.ant-tabs-tabpane-active{
    margin-top:-11px !important;
  }
</style>
