<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch1">
        <a-form-model
          id="productRebateDetailList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          @keyup.enter.native="handleSearch" >
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="日期" prop="time">
                <rangeDate id="productRebateDetailList-time" ref="rangeDate" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="订单号">
                <a-input id="productRebateDetailList-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="备货单号">
                <a-input id="productRebateDetailList-bizSubNo" v-model.trim="queryParam.bizSubNo" allowClear placeholder="请输入备货单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户名称">
                <dealerSearchList ref="dealer" id="productRebateDetailList-buyerName" @change="dealerChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="差价归属方">
                <dealerSearchList ref="parentDealer" id="productRebateDetailList-parentDealer" @change="parentDealerChange" placeholder="请输入差价归属方"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="差价归属类型">
                <v-select code="RELATION_REBATE_PARENT_TYPE" id="productRebateDetailList-rebateParentType" v-model="queryParam.rebateParentType" allowClear placeholder="请选择差价归属类型"></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="单据类型">
                <v-select
                  v-model="queryParam.bizType"
                  ref="bizType"
                  id="productRebateDetailList-bizType"
                  code="REBATE_BILL_BIZ_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="产品品牌">
                  <ProductBrand id="productRebateDetailList-productBrandSn" placeholder="请选择产品品牌" v-model="queryParam.productEntity.productBrandSn"></ProductBrand>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品分类">
                  <ProductType id="productRebateDetailList-productType" placeholder="请选择产品分类" @change="changeProductType" v-model="queryParam.productType"></ProductType>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品编码">
                  <a-input id="productRebateDetailList-code" v-model.trim="queryParam.productEntity.code" allowClear placeholder="请输入产品编码"/>
                </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="productRebateDetailList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="productRebateDetailList-reset">重置</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"
          :pageSize="30"
          :style="{ height: tableHeight+38+'px' }"
          :scroll="{ x: 2200,y: tableHeight-80 }"
          :defaultLoadData="false"
          bordered>
          <template slot="footer">
            <a-row type="flex" justify="end" :gutter="10">
              <a-col flex="10%" >总开单金额：{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? toThousands(totalData.totalAmount) : '--' }}</a-col>
              <a-col flex="10%" >总实售金额：{{ (totalData && (totalData.totalRealAmount || totalData.totalRealAmount==0)) ? toThousands(totalData.totalRealAmount) : '--' }}</a-col>
              <a-col flex="10%" >总差价金额：{{ (totalData && (totalData.rebateAmount || totalData.rebateAmount==0)) ? toThousands(totalData.rebateAmount) : '--' }}</a-col>
              <a-col flex="10%">原总开单金额：{{ (totalData && (totalData.totalAmountOrig || totalData.totalAmountOrig==0)) ? toThousands(totalData.totalAmountOrig) : '--' }}</a-col>
              <a-col flex="10%">原总实售金额：{{ (totalData && (totalData.totalRealAmountOrig || totalData.totalRealAmountOrig==0)) ? toThousands(totalData.totalRealAmountOrig) : '--' }}</a-col>
            </a-row>
          </template>
        </s-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import dealerSearchList from '@/views/common/dealerSearchList.vue'
// 组件
import { rebateDetailQueryList, rebateDetailQueryCount } from '@/api/reportData'
export default {
  components: { STable, VSelect, rangeDate, ProductType, ProductBrand, dealerSearchList },
  mixins: [commonMixin],
  name: 'ProductRebateDetailList',
  data () {
    return {
      spinning: false,
      labelCol: { span: 8 }, // 调整表单纵向布局
      wrapperCol: { span: 16 }, // 调整表单横向布局
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      //  查询条件
      queryParam: {
        time: [], // 日期
        beginDate: '', // 开始日期
        endDate: '', // 结束日期
        buyerSn: undefined, // 客户sn
        bizNo: '', // 订单号
        bizSubNo: '', // 备货单号
        bizType: undefined, // 单据类型
        parentDealerSn: undefined, // 差价归属方
        rebateParentType: undefined, // 差价归属类型
        productEntity: {
          productBrandSn: undefined, //  产品品牌
          productTypeSn1: '', //  产品一级分类
          productTypeSn2: '', //  产品二级分类
          productTypeSn3: '', //  产品三级分类
          code: '', //  产品编码
          name: '' //  产品名称
        }
      },
      totalData: null, //  合计
      rules: {
        'time': [{ required: true, message: '请选择日期', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        this.spinning = true
        delete params.time
        // 总计
        this.getCount(params)
        // 获取列表数据 有分页
        return rebateDetailQueryList(params).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
              data.list[i].inStockQty = data.list[i].qty
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '60px', align: 'center' },
        { title: '订单号', dataIndex: 'bizNo', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备货单号', dataIndex: 'bizSubNo', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据类型', dataIndex: 'bizTypeDictValue', width: '80px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户级别', dataIndex: 'buyerLevelDictValue', width: '90px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', width: '150px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '差价归属方', dataIndex: 'parentDealerName', width: '130px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '百分比', dataIndex: 'rebateRate', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text * 100 + '%' : '--') } },
        { title: '差价归属类型', dataIndex: 'rebateParentTypeDictValue', width: '120px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '价格级别', dataIndex: 'directLevelDictValue', width: '80px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'productEntity.productBrandName', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品分类', width: '160px', align: 'center', customRender: function (text, record) { return record.productEntity.productTypeName1 + (record.productEntity.productTypeName2 ? '>' : '') + (record.productEntity.productTypeName2 || '') } },
        { title: '产品编码', dataIndex: 'productEntity.code', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '150px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '数量', dataIndex: 'qty', width: '60px', align: 'center', customRender: function (text, record) { return ((text || text == 0) && _this.getNormalVal(record.rebateParentTypeDictValue) ? text : '--') } },
        { title: '省级价', dataIndex: 'provincePrice', width: '80px', align: 'right', customRender: function (text, record) { return ((text || text == 0) && _this.getNormalVal(record.rebateParentTypeDictValue) ? _this.toThousands(text) : '--') } },
        { title: '市级价', dataIndex: 'cityPrice', width: '80px', align: 'right', customRender: function (text, record) { return ((text || text == 0) && _this.getNormalVal(record.rebateParentTypeDictValue) ? _this.toThousands(text) : '--') } },
        { title: '特约价', dataIndex: 'specialPrice', width: '80px', align: 'right', customRender: function (text, record) { return ((text || text == 0) && _this.getNormalVal(record.rebateParentTypeDictValue) ? _this.toThousands(text) : '--') } },
        { title: '总开单金额', dataIndex: 'totalAmount', width: '80px', align: 'right', customRender: function (text, record) { return ((text || text == 0) && _this.getNormalVal(record.rebateParentTypeDictValue) ? _this.toThousands(text) : '--') } },
        { title: '总实售金额', dataIndex: 'totalRealAmount', width: '80px', align: 'right', customRender: function (text, record) { return ((text || text == 0) && _this.getNormalVal(record.rebateParentTypeDictValue) ? _this.toThousands(text) : '--') } },
        { title: '总差价金额', dataIndex: 'totalRebateAmount', width: '80px', align: 'right', customRender: function (text, record) { return ((text || text == 0) && _this.getNormalVal(record.rebateParentTypeDictValue) ? _this.toThousands(text) : '--') } },
        { title: '差价金额', dataIndex: 'rebateAmount', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '原总开单金额', dataIndex: 'totalAmountOrig', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '原总实售金额', dataIndex: 'totalRealAmountOrig', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } }
      ]
      if(_this.$hasPermissions('M_productRebateReportList_costPrice')){
        arr.push({ title: '实际总成本', dataIndex: 'totalCost', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  watch: {
    // 展开关闭 监听表格高度变化
    advanced (newValue, oldValue) {
      this.setTableH()
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    // 判断差价归属类型为-- 或者 直接上级时  数量/省级价/市级价/特约价/总开单金额/总实售金额/差价  正常显示
    getNormalVal (val) {
      return !val || val === '直接上级'
    },
    // 合计
    getCount (params) {
      rebateDetailQueryCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  日期  change
    dateChange (date) {
      this.queryParam.time = date
      this.queryParam.beginDate = date[0] || ''
      this.queryParam.endDate = date[1] || ''
    },
    //  查询
    handleSearch () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$refs.table.refresh(true)
        } else {
          this.$message.error('请选择日期')
          return false
        }
      })
    },
    // 客户名称
    dealerChange (val) {
      if (val.row) {
        this.queryParam.buyerSn = val.row.dealerSn
      } else {
        this.queryParam.buyerSn = undefined
      }
    },
    // 差价归属方
    parentDealerChange (val) {
      if (val.row) {
        this.queryParam.parentDealerSn = val.row.dealerSn
      } else {
        this.queryParam.parentDealerSn = undefined
      }
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.time = []
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.bizNo = ''
      this.queryParam.bizSubNo = ''
      this.queryParam.bizType = undefined
      this.queryParam.buyerSn = undefined
      this.queryParam.parentDealerSn = undefined
      this.queryParam.rebateParentType = undefined
      this.$refs.dealer.resetForm()
      this.$refs.parentDealer.resetForm()

      this.queryParam.productEntity.productBrandSn = undefined
      this.queryParam.productEntity.productTypeSn1 = ''
      this.queryParam.productEntity.productTypeSn2 = ''
      this.queryParam.productEntity.productTypeSn3 = ''
      this.queryParam.productEntity.code = ''
      this.queryParam.productEntity.name = ''
      this.queryParam.productType = []
      this.productType = []
      this.$refs.ruleForm.resetFields()
      this.totalData = null
      this.$refs.table.clearTable()
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productEntity.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productEntity.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productEntity.productTypeSn3 = val[2] ? val[2] : ''
    },
    // 初始化
    pageInit () {
      this.disabled = false
      this.spinning = false
      this.setTableH()
    },
    // 计算表格高度
    setTableH () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        const tableSearchH = this.$refs.tableSearch1.offsetHeight
        this.tableHeight = window.innerHeight - tableSearchH - 300
      })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
