<template>
  <div>
    <a-card size="small" :bordered="false" class="promotionSalesList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper newTableSearchName" ref="tableSearch">
        <a-form-model
          id="promotionSalesList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="form"
          :rules="rules"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="统计月份" prop="monthInfo">
                <div class="monthBox" style="display:flex;align-item:center;">
                  <a-month-picker
                    id="promotionSalesList-startValue"
                    :disabled-date="disabledStartDate"
                    format="YYYY-MM"
                    v-model="startValue"
                    placeholder="开始月份"
                    @openChange="handleStartOpenChange"
                    @change="getStartDate"
                  />
                  <span>~</span>
                  <a-month-picker
                    id="promotionSalesList-endValue"
                    :disabled-date="disabledEndDate"
                    format="YYYY-MM"
                    v-model="endValue"
                    placeholder="结束月份"
                    :open="endOpen"
                    @openChange="handleEndOpenChange"
                    @change="getEndDate"
                  />
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="区域/分区">
                <subarea id="promotionSalesList-subareaSn" ref="subarea" @change="subareaChange"></subarea>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="区域负责人">
                <BizUser id="promotionSalesList-bizUserSn" v-model="queryParam.subareaArea.bizUserSn"></BizUser>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-form-model-item label="省份">
                <Area id="promotionSalesList-provinceSn" v-model="queryParam.provinceSn" placeholder="请选择省"></Area>
              </a-form-model-item>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户名称">
                  <dealerSubareaScopeList ref="custList" id="salesAmountReportList-dealerSn" @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="promotionSalesList-dealerLevel"
                    code="DEALER_LEVEL"
                    placeholder="请选择客户级别"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品品牌">
                  <ProductBrand id="productInfoList-productBrand" v-model="queryParam.productBrand"></ProductBrand>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品分类">
                  <productTypeAll
                    expandType="click"
                    :changeOnSelect="false"
                    placeholder="请选择产品分类"
                    :level="2"
                    @change="changeProductType"
                    v-model="productType"
                    id="productInfoList-productType"></productTypeAll>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="新/老客户">
                  <a-select id="productInfoList-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="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="promotionSalesList-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="promotionSalesList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_brandTypeReportExport')"
                id="promotionSalesList-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 8px">
                {{ 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"
          :defaultLoadData="true"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ x:1890,y: tableHeight-136 }"
          bordered>
          <!-- 品牌-->
          <template slot="brandName" slot-scope="text, record">
            {{ record.allProductBrandFlag==1?'全品牌':record.brandName?record.brandName:'--' }}
          </template>
          <!-- 分类 -->
          <template slot="brandtypeName" slot-scope="text, record">
            {{ record.allProductTypeFlag==1?'全分类':record.brandtypeName?record.brandtypeName:'--' }}
          </template>
          <template slot="footer" v-if="totalData">
            <a-row>
              <a-col span="24">
                <a-row>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_salesPrice')">销售额：{{ (totalData.totalSaleAmount || totalData.totalSaleAmount==0) ? toThousands(totalData.totalSaleAmount) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_costPrice')">促销成本费用：{{ (totalData.promoCostFee || totalData.promoCostFee==0) ? toThousands(totalData.promoCostFee) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_costPrice')">促销成本费用比：{{ totalData.promoCostFeeRate ? (totalData.promoCostFeeRate*100).toFixed(2)+'%' : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_salesPrice')">促销销售费用：{{ (totalData.promoSaleFee || totalData.promoSaleFee==0) ? toThousands(totalData.promoSaleFee) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_salesPrice')">促销销售费用比：{{ totalData.promoSaleFeeRate ? (totalData.promoSaleFeeRate*100).toFixed(2)+'%' : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_salesPrice')">参与活动销售额：{{ (totalData.promoSaleAmount || totalData.promoSaleAmount==0) ? toThousands(totalData.promoSaleAmount) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_salesPrice')">未参与活动销售额：{{ (totalData.notpromotionSale || totalData.notpromotionSale==0) ? toThousands(totalData.notpromotionSale) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_costPrice')">产品赠品成本费用：{{ (totalData.allocateGiftCost || totalData.allocateGiftCost==0) ? toThousands(totalData.allocateGiftCost) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_salesPrice')">产品赠品销售费用：{{ (totalData.allocateGiftAmount || totalData.allocateGiftAmount==0) ? toThousands(totalData.allocateGiftAmount) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_costPrice')">物料赠品成本费用：{{ (totalData.allocateCost || totalData.allocateCost==0) ? toThousands(totalData.allocateCost) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_salesPrice')">物料赠品销售费用：{{ (totalData.allocateSaleAmount || totalData.allocateSaleAmount==0) ? toThousands(totalData.allocateSaleAmount) : '--' }}</a-col>

                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_costPrice')">成本费用合计（促销+产品+物料）：{{ (totalData.promoCostFeeAndAllocateCost || totalData.promoCostFeeAndAllocateCost==0)? toThousands(totalData.promoCostFeeAndAllocateCost) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_costPrice')">成本合计占比：{{ totalData.totalCostRate ? (totalData.totalCostRate*100).toFixed(2)+'%' : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_salesPrice')">销售费用合计（促销+产品+物料）：{{ (totalData.promoSaleFeeAndAllocateAmount || totalData.promoSaleFeeAndAllocateAmount==0) ? toThousands(totalData.promoSaleFeeAndAllocateAmount) : '--' }}</a-col>
                  <a-col
                    span="4"
                    v-if="$hasPermissions('M_promotionSalesOrderReportList_salesPrice')">销售合计占比：{{ totalData.totalSaleRate ? (totalData.totalSaleRate*100).toFixed(2)+'%' : '--' }}</a-col>
                </a-row>
              </a-col>
            </a-row>
          </template>
        </s-table>
      </a-spin>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import ProductBrand from '@/views/common/productBrand.js'
import productTypeAll from '@/views/common/productType.js'
import subarea from '@/views/common/subarea.js'
import reportModal from '@/views/common/reportModal.vue'
import Area from '@/views/common/area.js'
import BizUser from '@/views/common/bizUser.js'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
// 接口
import { brandTypeReportList, brandTypeReportCount, brandTypeReportExport } from '@/api/reportData'
export default {
  name: 'PromotionSalesOrderReport',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, dealerSubareaScopeList, reportModal, Area, BizUser, ProductBrand, productTypeAll },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      showExport: false, // 导出弹窗
      //  查询条件
      queryParam: {
        brandTypeBeginDate: moment().format('YYYYMM'), // 开始月份
        brandTypeEndDate: moment().format('YYYYMM'), // 结束月份
        dealerSn: undefined, // 客户 sn
        provinceSn: undefined, // 省份
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined, // 分区
          bizUserSn: undefined// 区域负责人
        },
        productBrand: undefined, // 产品品牌
        productTypeSn1: '', //  产品一级分类
        productType: '', //  产品二级分类
        dealerLevel: undefined, // 客户等级
        dealerNewFlag: undefined
      },
      productType: [], // 产品分类
      form: {
        monthInfo: [moment().format('YYYY-MM'), moment().format('YYYY-MM')]
      },
      rules: {
        monthInfo: [{ required: true, message: '请选择统计月份', trigger: 'change' }]
      },
      startValue: moment().format('YYYY-MM'), // 统计月份 开始
      endValue: moment().format('YYYY-MM'), // 统计月份 结束
      endOpen: false, // 打开结束月份弹窗
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const newParamsPage = Object.assign(this.queryParam, { pageNo: parameter.pageNo, pageSize: parameter.pageSize }) //  有分页
        const paramsPage = JSON.parse(JSON.stringify(newParamsPage))
        delete paramsPage.productTypeSn1
        if (!paramsPage.subareaArea.subareaSn && !paramsPage.subareaArea.subareaAreaSn && !paramsPage.subareaArea.bizUserSn) {
          delete paramsPage.subareaArea
        }
        // 获取列表数据  有分页
        return brandTypeReportList(paramsPage).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            this.getCount(paramsPage)
            // 计算列表序号
            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
        })
      },
      totalData: null
    }
  },
  computed: {
    columns () {
      const _this = this
      const isCostFlag = this.$hasPermissions('M_promotionSalesOrderReportList_costPrice')
      const isSellFlag = this.$hasPermissions('M_promotionSalesOrderReportList_salesPrice')
      const arr = [
        { title: '区域', dataIndex: 'subareaArea.subareaName', show: true, width: '70px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', show: true, width: '70px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域负责人', dataIndex: 'bizUserName', show: true, width: '70px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '省份', dataIndex: 'dealerInfo.provinceName', show: true, width: '70px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerInfo.dealerName', show: true, width: '150px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户级别', dataIndex: 'dealerInfo.dealerLevelDictValue', show: true, width: '80px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'brandName', show: true, width: '80px', align: 'center', scopedSlots: { customRender: 'brandName' } },
        { title: '二级分类', dataIndex: 'brandtypeName', show: true, width: '90px', align: 'center', scopedSlots: { customRender: 'brandtypeName' } },
        { title: '销售额', dataIndex: 'totalSaleAmount', show: true, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '促销成本费用', dataIndex: 'promoCostFee', show: true, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '促销成本费用比', dataIndex: 'promoCostFeeRate', show: true, width: '60px', align: 'center', customRender: text => (text ? (text * 100).toFixed(2) + '%' : '--') },
        { title: '促销销售费用', dataIndex: 'promoSaleFee', show: true, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '促销销售费用比', dataIndex: 'promoSaleFeeRate', show: true, width: '60px', align: 'center', customRender: text => (text ? (text * 100).toFixed(2) + '%' : '--') },
        { title: '参与活动销售额', dataIndex: 'promoSaleAmount', show: true, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '未参与活动销售额', dataIndex: 'notpromotionSale', show: true, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '产品赠品成本费用', dataIndex: 'allocateGiftCost', show: isCostFlag, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '产品赠品销售费用', dataIndex: 'allocateGiftAmount', show: isSellFlag, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '物料赠品成本费用', dataIndex: 'allocateCost', show: isCostFlag, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '物料赠品销售费用', dataIndex: 'allocateSaleAmount', show: isSellFlag, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '成本费用合计（促销+产品+物料）', dataIndex: 'promoCostFeeAndAllocateCost', show: isCostFlag, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '成本合计占比', dataIndex: 'totalCostRate', show: isCostFlag, width: '60px', align: 'center', customRender: text => (text ? (text * 100).toFixed(2) + '%' : '--') },
        { title: '销售费用合计（促销+产品+物料）', dataIndex: 'promoSaleFeeAndAllocateAmount', show: isSellFlag, width: '80px', align: 'right', customRender: text => ((text || text == 0) ? _this.toThousands(text) : '--') },
        { title: '销售合计占比', dataIndex: 'totalSaleRate', show: isSellFlag, width: '60px', align: 'center', customRender: text => (text ? (text * 100).toFixed(2) + '%' : '--') }
      ]

      return arr.filter(item => item.show)
    }
  },
  watch: {
    // 展开关闭
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    // 统计月份  选择月份限制
    disabledStartDate (current) {
      const endValue = this.endValue
      const md = moment(current).startOf('month').valueOf()
      const cd = moment().startOf('month').valueOf() // 当前月份
      if (!current || !endValue) {
        return md > cd
      }
      const ed = moment(endValue).startOf('month').valueOf()
      return md > ed || md > cd
    },
    disabledEndDate (current) {
      const startValue = this.startValue
      const md = moment(current).startOf('month').valueOf()
      const cd = moment().startOf('month').valueOf() // 当前月份
      if (!current || !startValue) {
        return md > cd
      }
      const sd = moment(startValue).startOf('month').valueOf()
      return md < sd || md > cd
    },
    // 开始时间
    handleStartOpenChange (open) {
      if (!open) {
        this.endOpen = true
      }
    },
    getStartDate (date, dateString) {
      this.form.monthInfo[0] = dateString
      this.queryParam.brandTypeBeginDate = date ? moment(dateString).startOf('month').format('YYYYMM') : ''
    },
    // 结束时间
    handleEndOpenChange (open) {
      this.endOpen = open
    },
    getEndDate (date, dateString) {
      this.form.monthInfo[1] = dateString
      this.queryParam.brandTypeEndDate = date ? moment(dateString).endOf('month').format('YYYYMM') : ''
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          _this.$store.state.app.curActionPermission = 'B_brandTypeReportExport'
          hdExportExcel(brandTypeReportExport, params, '促销销售单报表（统计）', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    // 总计
    getCount (params) {
      brandTypeReportCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data || null
        } else {
          this.totalData = null
        }
      })
    },
    // 查询
    handleSearch () {
      const _this = this
      if (!_this.form.monthInfo[0] || !_this.form.monthInfo[1]) {
        _this.$message.error('请选择统计月份')
        return
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择统计月份')
          return false
        }
      })
    },
    // 客户名称
    custChange (val) {
      this.queryParam.dealerSn = val.key
    },
    // 区域分区
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productType = val[1] ? val[1] : ''
    },
    //  重置
    resetSearchForm () {
      this.form.monthInfo = [moment().format('YYYY-MM'), moment().format('YYYY-MM')]
      this.startValue = moment().format('YYYY-MM')
      this.endValue = moment().format('YYYY-MM')
      this.queryParam.brandTypeBeginDate = moment().format('YYYYMM')
      this.queryParam.brandTypeEndDate = moment().format('YYYYMM')
      this.queryParam.dealerSn = undefined
      this.queryParam.provinceSn = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.subareaArea.bizUserSn = undefined
      this.queryParam.productBrand = undefined
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productType = undefined
      this.queryParam.dealerLevel = undefined
      this.queryParam.dealerNewFlag = undefined

      this.productType = []
      this.totalData = null
      if (this.advanced) {
        this.$refs.custList.resetForm()
      }
      this.$refs.subarea.clearData()
      this.$refs.ruleForm.resetFields()
      this.$refs.table.refresh()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 215
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.setTableH()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.setTableH()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less" scoped>
  .monthBox{
    /deep/.ant-calendar-picker-icon{
      display:none !important;
    }
    /deep/.ant-calendar-picker input{
      text-align:center;
    }
  }
</style>
