<template>
  <a-spin :spinning="spinning" tip="Loading...">
    <div class="productInfoList-wrap">
      <a-card size="small" :bordered="false" class="promotionSalesRealTimeReport-wrap searchBox">
        <!-- 查询 -->
        <div ref="tableSearch" class="table-page-search-wrapper newTableSearchName">
          <a-form-model id="promotionSalesRealTimeList-form" 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 id="promotionSalesRealTimeList-salesDate" ref="rangeDate" :value="newQueryParam.salesDate" @change="salesDateChange" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="促销名称">
                  <a-input
                    id="promotionSalesRealTimeList-title"
                    v-model.trim="newQueryParam.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="newQueryParam.promoRuleReport.promotionRuleType"
                    ref="ruleType"
                    id="promotionSalesRealTimeList-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="promotionSalesRealTimeList-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="促销开始时间">
                    <a-range-picker
                      style="width:100%"
                      v-model="time"
                      :format="dateFormat"
                      id="promotionSalesRealTimeList-time"
                      :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="promotionSalesRealTimeList-ruleInfo"
                      v-model.trim="newQueryParam.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="newQueryParam.buyerLevel"
                      ref="buyerLevel"
                      id="promotionSalesRealTimeList-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="promotionSalesRealTimeList-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="promotionSalesRealTimeList-subarea" @change="subareaChange"></subarea>
                  </a-form-model-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-model-item label="地区">
                    <AreaList id="promotionSalesRealTimeList-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
                  </a-form-model-item>
                </a-col>
                <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                  <a-form-model-item label="客服">
                    <customerService ref="customerName" id="promotionSalesRealTimeList-customerName" v-model="newQueryParam.bizUserSn"></customerService>
                  </a-form-model-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-model-item label="新/老客户">
                    <a-select id="promotionSalesRealTimeList-dealerNewFlag" v-model="newQueryParam.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&&advanced?24:6" :sm="24" style="margin-bottom: 10px;" :style="{textAlign: isShowCustomerSearch&&advanced?'center':''}">
                <span class="table-page-search-submitButtons">
                  <a-button type="primary" id="promotionSalesRealTimeList-refresh":disabled="disabled" @click="testForm('search')">查询</a-button>
                  <a-button style="margin-left: 8px" id="promotionSalesRealTimeList-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="promotionSalesRealTimeList-export"
                    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>
      </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="{ y: tableHeight-20,x:1890}"
          :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.promotionRule.ruleInfo" v-html="record.promotionRule.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="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>
      </a-card>
    </div>
    <!-- 导出提示框 -->
    <reportModal :visible="showExport" @close="showExport=false"></reportModal>
  </a-spin>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
import getDate from '@/libs/getDate.js'
// 组件
import { STable, VSelect } from '@/components'
import reportModal from '@/views/common/reportModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import customerService from '@/views/common/customerService.vue'
import subarea from '@/views/common/subarea.js'
import AreaList from '@/views/common/areaList.js'
// 接口
import { salesPromoRealReportList, salesPromoRealReportCount, exportSalesPromoRealReport } from '@/api/reportData'
export default {
  name: 'PromotionSalesRealTimeList',
  mixins: [commonMixin],
  components: { STable, VSelect, reportModal, AreaList, rangeDate, subarea, customerService },
  data () {
    const _this = this
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      exportLoading: false, // 导出按钮加载状态
      showExport: false, // 导出弹窗
      time: undefined, // 促销开始时间
      // 查询条件
      newQueryParam: {
        // 下推时间 默认值
        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, // 区域编码
        bizUserSn: undefined, // 客服
        dealerNewFlag: undefined // 客户类型
      },
      rules: {
        salesDate: [{ required: true, message: '请选择下推时间', trigger: 'change' }]
      },
      dateFormat: 'YYYY-MM-DD', // 时间格式
      totalData: null, //  统计合计
      // 表格列
      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) : '--')
        }
      }
      ],
      // 加载数据方法 必须为 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: {
    // 下推时间 change
    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, // 促销类型
          ruleInfo: '' // 规则
        },
        salesBillNo: '', // 销售单号
        buyerLevel: undefined, // 客户级别
        buyerName: '', // 客户名称
        subareaArea: {
          subareaSn: '',
          subareaAreaSn: ''
        },
        dealerProvinceSn: undefined, // 省份编码
        dealerCitySn: undefined, // 城市编码
        dealerDistrictSn: undefined, // 区域编码
        bizUserSn: undefined,
        dealerNewFlag: 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()
      this.totalData = null
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 270
    }
  },
  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>
