<template>
  <a-card size="small" :bordered="false" class="orderStatisticsList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate id="orderStatisticsList-time" ref="rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
                <custList ref="custList" id="orderStatisticsList-buyerSn" @change="custChange"></custList>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="销售单号">
                <a-input id="orderStatisticsList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="促销名称">
                  <promoList ref="promoList" id="orderStatisticsList-promoActiveSn" @change="promoChange"></promoList>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务状态">
                  <v-select
                    v-model="queryParam.billStatus"
                    ref="billStatus"
                    id="orderStatisticsList-billStatus"
                    code="SALES_BILL_STATUS"
                    placeholder="请选择业务状态"
                    allowClear
                  ></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="orderStatisticsList-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm()" :disabled="disabled" id="orderStatisticsList-reset">重置</a-button>
                <a @click="advanced=!advanced" style="margin-left: 5px" id="orderStatisticsList-advanced">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          <span>促销品原价总额：<strong>{{ productTotal && (productTotal.totalOrigAmount || productTotal.totalOrigAmount==0) ? toThousands(productTotal.totalOrigAmount) : '--' }}</strong>，</span>
          <span>促销品促销价总额：<strong>{{ productTotal && (productTotal.totalAmount || productTotal.totalAmount==0) ? toThousands(productTotal.totalAmount) : '--' }}</strong>，</span>
          <span>节省总额：<strong>{{ productTotal && (productTotal.totalEconomizeAmount || productTotal.totalEconomizeAmount==0) ? toThousands(productTotal.totalEconomizeAmount) : '--' }}</strong>，</span>
          总单数：<strong>{{ productTotal && (productTotal.totalRecord || productTotal.totalRecord==0) ? productTotal.totalRecord : '--' }}</strong>，
          总款数：<strong>{{ productTotal && (productTotal.totalCategory || productTotal.totalCategory==0) ? productTotal.totalCategory : '--' }}</strong>，
          总数量：<strong>{{ productTotal && (productTotal.totalQty || productTotal.totalQty==0) ? productTotal.totalQty : '--' }}</strong>
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="$hasPermissions('B_orderStatistics_detail')"
            @click="handleDetail(record)"
            class="button-success"
            :id="'orderStatisticsList-detail-'+record.id">详情</a-button>
          <span v-else>--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 详情 -->
    <orderStatisticsDetailModal v-drag :openModal="openModal" :itemSn="itemSn" :nowData="nowData" @close="closeModal" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import custList from '@/views/common/custList.vue'
import promoList from '@/views/common/promoList.vue'
import orderStatisticsDetailModal from './detailModal.vue'
import { salesPromoList, salesPromoCount } from '@/api/sales'
export default {
  name: 'OrderStatisticsList',
  mixins: [commonMixin],
  components: { STable, VSelect, orderStatisticsDetailModal, custList, promoList, rangeDate },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      // 查询参数
      queryParam: {
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        buyerSn: undefined, // 客户名称
        promoActiveSn: undefined, // 促销名称
        salesBillNo: '', // 销售单号
        billStatus: undefined // 业务状态
      },
      time: [ // 时间默认值
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return salesPromoList(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            this.getTotal(Object.assign(parameter, this.queryParam))
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              const promotionActivityNameList = data.list[i].promotionActivityNameList || []
              data.list[i].promoName = promotionActivityNameList.join(',')
              const totalPromoAmount = data.list[i].totalPromoAmount || 0
              const totalEconomizeAmount = data.list[i].totalEconomizeAmount || 0
              data.list[i].promoTotal = Number(totalPromoAmount) + Number(totalEconomizeAmount)
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      openModal: false, //  弹框是否显示
      itemSn: '', //  当前sn
      nowData: null, // 当前操作数据
      productTotal: null // 合计
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据来源', dataIndex: 'salesBillSourceDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', dataIndex: 'salesBillNo', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '促销名称', dataIndex: 'promoName', align: 'center', width: '9%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户名称', dataIndex: 'buyerName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '促销品款数', dataIndex: 'totalPromoCategory', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '促销品数量', dataIndex: 'totalPromoQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '原价总额', dataIndex: 'promoTotal', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '促销品总额', dataIndex: 'totalPromoAmount', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '节省总额', dataIndex: 'totalEconomizeAmount', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '4%', align: 'center' }
      ]
      arr.splice(8, 0, { title: '原价总额', dataIndex: 'promoTotal', width: '7%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      arr.splice(9, 0, { title: '促销品总额', dataIndex: 'totalPromoAmount', width: '7%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      arr.splice(10, 0, { title: '节省总额', dataIndex: 'totalEconomizeAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      return arr
    }
  },
  methods: {
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 客户选择
    custChange (obj) {
      this.queryParam.buyerSn = obj.key
    },
    // 促销规则选择
    promoChange (obj) {
      this.queryParam.promoActiveSn = obj.key
    },
    // 合计
    getTotal (param) {
      salesPromoCount(param).then(res => {
        if (res.status == 200 && res.data) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  详情
    handleDetail (row) {
      this.itemSn = row.salesBillSn
      this.nowData = row
      this.openModal = true
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.buyerSn = undefined
      this.queryParam.promoActiveSn = undefined
      this.queryParam.salesBillNo = ''
      this.queryParam.billStatus = undefined
      this.$refs.custList.resetForm()
      if (this.advanced) {
        this.$refs.promoList.resetForm()
      }
      this.$refs.table.refresh(true)
    },
    // 关闭弹框
    closeModal () {
      this.openModal = false
      this.itemSn = ''
      this.nowData = null
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 表格高度计算
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 236
    }
  },
  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()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
