<template>
  <div>
    <a-card size="small" :bordered="false" class="hPriceDifferenceDetailList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="hPriceDifferenceDetailList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="日期" prop="time">
                <rangeDate ref="rangeDate" id="hPriceDifferenceDetailList-time" :value="queryParam.time" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="订单号">
                <a-input id="hPriceDifferenceDetailList-bizNo" v-model.trim="queryParam.bizNo" allowClear placeholder="请输入订单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户名称">
                <dealerSubareaScopeList id="hPriceDifferenceDetailList-custList" ref="custList" @change="custChange"></dealerSubareaScopeList>
              </a-form-model-item>
            </a-col>
            <a-col :md="7" :sm="24" v-if="isShowCustomerSearch">
              <a-form-model-item label="客户级别">
                <v-select
                  v-model="queryParam.dealer.dealerLevel"
                  ref="dealerLevel"
                  id="hPriceDifferenceDetailList-dealerLevel"
                  code="DEALER_LEVEL"
                  placeholder="请选择客户级别"
                  allowClear></v-select>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="7" :sm="24" v-if="!isShowCustomerSearch">
                <a-form-model-item label="客户级别">
                  <v-select
                    v-model="queryParam.dealer.dealerLevel"
                    ref="dealerLevel"
                    id="hPriceDifferenceDetailList-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="品牌分类">
                  <v-select code="BRAND_TYPE" id="hPriceDifferenceDetailList-brandType" v-model="queryParam.product.brandType" allowClear placeholder="请选择品牌分类"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="5" :sm="24">
                <a-form-model-item label="产品品牌">
                  <ProductBrand id="hPriceDifferenceDetailList-productBrandSn" v-model="queryParam.product.productBrandSn"></ProductBrand>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品分类">
                  <ProductType id="hPriceDifferenceDetailList-productType" v-model="productType" @change="changeProductType"></ProductType>
                </a-form-model-item>
              </a-col>
              <a-col :md="7" :sm="24">
                <a-form-model-item label="所在区域">
                  <subarea id="hPriceDifferenceDetailList-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="hPriceDifferenceDetailList-bizUserSn" v-model="queryParam.subareaArea.bizUserSn"></BizUser>
                </a-form-model-item>
              </a-col>
              <a-col :md="5" :sm="24">
                <a-form-model-item label="省份">
                  <Area id="hPriceDifferenceDetailList-provinceSn" v-model="queryParam.dealer.provinceSn" placeholder="请选择省份"></Area>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="单据类型" prop="bizType">
                  <a-select id="hPriceDifferenceDetailList-bizType" allowClear v-model="queryParam.bizType" placeholder="请选择单据类型">
                    <a-select-option v-for="item in bizTypeList" :value="item.value" :key="item.value">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="7" :sm="24" v-show="isShowCustomerSearch">
                <a-form-model-item label="客服">
                  <customerService id="hPriceDifferenceDetailList-customerName" ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="isShowCustomerSearch?24:6" :sm="24" style="margin-bottom: 10px;" :style="{textAlign: isShowCustomerSearch?'center':''}">
              <!-- <a-button
                type="primary"
                class="button-info"
                size="small"
                @click="handleStock"
                id="hPriceDifferenceDetailList-stockDate">盘点区间日期</a-button> -->
              <a-button style="margin-left: 5px" type="primary" @click="handleSearch" :disabled="disabled" id="hPriceDifferenceDetailList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="hPriceDifferenceDetailList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                id="hPriceDifferenceDetailList-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ 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"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :pageSize="30"
          :style="{ height: tableHeight+70+'px' }"
          :scroll="{ x: 1850 ,y: tableHeight-50 }"
          bordered>
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="6" :sm="24" >分公司金额：{{ (totalData && (totalData.wholesalePrice1 || totalData.wholesalePrice1==0)) ? toThousands(totalData.wholesalePrice1) : '--' }}</a-col>
              <a-col :md="6" :sm="24" >加盟商金额：{{ (totalData && (totalData.wholesalePrice2 || totalData.wholesalePrice2==0)) ? toThousands(totalData.wholesalePrice2) : '--' }}</a-col>
              <a-col :md="6" :sm="24" >特约加盟店金额：{{ (totalData && (totalData.wholesalePrice3 || totalData.wholesalePrice3==0)) ? toThousands(totalData.wholesalePrice3) : '--' }}</a-col>
              <a-col :md="6" :sm="24" >差价金额：{{ (totalData && (totalData.rebateAmount || totalData.rebateAmount==0)) ? toThousands(totalData.rebateAmount) : '--' }}</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 getDate from '@/libs/getDate.js'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import subarea from '@/views/common/subarea.js'
import reportModal from '@/views/common/reportModal.vue'
import Area from '@/views/common/area.js'
import ProductBrand from '@/views/common/productBrand.js'
import ProductType from '@/views/common/productType.js'
import BizUser from '@/views/common/bizUser.js'
import customerService from '@/views/common/customerService'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
// 接口
import { headRebateDetailReportList, headRebateDetailReportCount, headRebateDetailReportExport } from '@/api/reportData'
export default {
  name: 'HPriceDifferenceDetailReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, dealerSubareaScopeList, subarea, Area, rangeDate, ProductBrand, ProductType, reportModal, BizUser, customerService },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      showExport: false, // 导出弹窗提示
      //  查询条件
      queryParam: {
        // 日期 默认值
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime, // 开始日期
        endDate: getDate.getCurrMonthDays().endtime, // 结束日期
        bizNo: '', // 订单号
        dealer: {
          dealerSn: undefined,
          dealerLevel: undefined,
          provinceSn: undefined
        },
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined,
          bizUserSn: undefined
        },
        product: {
          brandType: undefined,
          productBrandSn: undefined, //  产品品牌
          productTypeSn1: '', //  产品一级分类
          productTypeSn2: '', //  产品二级分类
          productTypeSn3: '' //  产品三级分类
        },
        bizType: undefined,
        bizUserSn: undefined
      },
      rules: {
        'time': [{ required: true, message: '请选择日期', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        if (!params.dealer.dealerSn && !params.dealer.dealerLevel && !params.dealer.subareaSn && !params.dealer.provinceSn) {
          delete params.dealer
        }
        delete params.time
        this.spinning = true
        return headRebateDetailReportList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 总计
            this.getCount(params)
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              if (data.list[i].bizType) {
                data.list[i].bizTypeValue = data.list[i].bizType == 'SALES' ? '采购差价' : data.list[i].bizType == 'SALES_RETURN' ? '退货差价' : ''
              }
              if (data.list[i].rebateRate || data.list[i].rebateRate == 0) {
                data.list[i].rebateRate = data.list[i].rebateRate * 100 + '%'
              }
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      productType: [],
      bizTypeList: [
        { value: 'SALES', name: '采购差价' },
        { value: 'SALES_RETURN', name: '退货差价' }
      ],
      totalData: null,
      tableHeight: 0
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域负责人', dataIndex: 'subareaArea.bizUserName', width: 100, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '订单号', dataIndex: 'bizNo', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '日期', dataIndex: 'bizDate', width: 90, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '省份', dataIndex: 'provinceName', width: 90, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '差价归属方', dataIndex: 'parentDealerName', width: 120, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '百分比', dataIndex: 'rebateRate', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '差价归属类型', dataIndex: 'rebateParentTypeDictValue', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', width: 120, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户级别', dataIndex: 'buyerLevelDictValue', width: 120, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'productBrandName', width: 130, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '二级分类', dataIndex: 'productTypeName2', width: 130, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '数量', dataIndex: 'qty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '分公司金额', dataIndex: 'wholesalePrice1', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '加盟商金额', dataIndex: 'wholesalePrice2', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '特约加盟店金额', dataIndex: 'wholesalePrice3', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '差价金额', dataIndex: 'rebateAmount', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单据类型', dataIndex: 'bizTypeValue', width: 100, align: 'center', customRender: function (text) { return text || '--' } }
      ]
      arr.splice(11, 0, { title: '分公司金额', dataIndex: 'wholesalePrice1', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      arr.splice(12, 0, { title: '加盟商金额', dataIndex: 'wholesalePrice2', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      arr.splice(13, 0, { title: '特约加盟店金额', dataIndex: 'wholesalePrice3', width: 100, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      arr.splice(14, 0, { title: '差价金额', dataIndex: 'rebateAmount', width: 80, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      return arr
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'M_hPriceDifferenceDetailReportList'
          _this.showExport = true
          _this.spinning = true
          hdExportExcel(headRebateDetailReportExport, params, '总部差价明细报表', function () {
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    // 盘点库存日期
    handleStock () {
      this.$message.info('无盘点区间的起始/终止时间，请自行选择日期区间查询！')
    },
    //  创建时间  change
    dateChange (date) {
      if (date[0] && date[1]) {
        this.queryParam.time = date
      } else {
        this.queryParam.time = []
      }
      this.queryParam.beginDate = date[0] || ''
      this.queryParam.endDate = date[1] || ''
    },
    // 合计
    getCount (params) {
      headRebateDetailReportCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择日期')
          return false
        }
      })
    },
    custChange (val) {
      this.queryParam.dealer.dealerSn = val.key
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.product.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.product.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.product.productTypeSn3 = val[2] ? val[2] : ''
    },
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    resetSearchForm () {
      this.queryParam.time = [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ]
      this.$refs.rangeDate.resetDate(this.queryParam.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.bizNo = ''
      this.queryParam.dealer.dealerSn = undefined
      this.queryParam.dealer.dealerLevel = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.subareaArea.bizUserSn = undefined
      this.queryParam.dealer.provinceSn = undefined
      this.queryParam.product.brandType = ''
      this.queryParam.product.productBrandSn = undefined
      this.queryParam.product.productTypeSn1 = ''
      this.queryParam.product.productTypeSn2 = ''
      this.queryParam.product.productTypeSn3 = ''
      this.queryParam.bizType = undefined
      this.queryParam.bizUserSn = undefined
      this.productType = []
      this.totalData = null
      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.$refs.custList.resetForm()
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 200
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.resetSearchForm()
      this.setTableH()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.resetSearchForm()
      this.setTableH()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
