<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form-model
          id="productRebateReportList-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="5" :sm="24">
              <a-form-model-item label="日期" prop="time">
                <rangeDate id="productRebateReportList-time" ref="rangeDate" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="订单号">
                <a-input id="productRebateReportList-bizNo" v-model.trim="queryParam.bizNo" allowClear placeholder="请输入订单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="客户名称">
                <dealerSearchList ref="dealer" id="productRebateReportList-buyerName" @change="dealerChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="单据类型">
                <v-select
                  v-model="queryParam.bizType"
                  ref="bizType"
                  id="productRebateReportList-bizType"
                  code="REBATE_BILL_BIZ_TYPE"
                  placeholder="请选择单据类型"
                  allowClear></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="4" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="productRebateReportList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="productRebateReportList-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <div style="margin-bottom:12px;text-align: right;">
          <span>显示：</span>
          <a-tree-select
            size="small"
            v-model="showCols"
            style="min-width: 200px"
            dropdownMatchSelectWidth
            :maxTagCount="3"
            :tree-data="colsArr"
            id="productRebateReportList-isShowColumn"
            tree-checkable
            placeholder="请选择要显示的列（多选）"
          />
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :style="{ height: tableHeight+'px' }"
          :scroll="{ y: tableHeight-120 }"
          :rowKey="(record) => record.bizNo"
          rowKeyName="bizNo"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :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.directRebate || totalData.directRebate==0)) ? toThousands(totalData.directRebate) : '--' }}</a-col>
              <a-col flex="10%">间接差价金额：{{ (totalData && (totalData.indirectRebate || totalData.indirectRebate==0)) ? toThousands(totalData.indirectRebate) : '--' }}</a-col>
              <a-col flex="10%">总实售价金额：{{ (totalData && (totalData.totalRealAmount || totalData.totalRealAmount==0)) ? toThousands(totalData.totalRealAmount) : '--' }}</a-col>
              <a-col flex="10%">原总开单金额：{{ (totalData && (totalData.totalBillingAmount || totalData.totalBillingAmount==0)) ? toThousands(totalData.totalBillingAmount) : '--' }}</a-col>
              <a-col flex="10%">原总实售金额：{{ (totalData && (totalData.totalRealSaleAmount || totalData.totalRealSaleAmount==0)) ? toThousands(totalData.totalRealSaleAmount) : '--' }}</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 dealerSearchList from '@/views/common/dealerSearchList.vue'
// 接口
import { rebateQueryList, rebateQueryCount } from '@/api/reportData'
export default {
  components: { STable, VSelect, rangeDate, dealerSearchList },
  mixins: [commonMixin],
  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: '', // 订单号
        bizType: undefined// 单据类型
      },
      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 rebateQueryList(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
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      totalData: null, //  合计
      colsArr: [ // 显示列数据
        {
          title: '直接差价金额（明细）',
          value: 'directRebateAmountInfo',
          key: 'directRebateAmountInfo',
          disabled: !this.$hasPermissions('M_salesOrderTotalList_salesPrice')
        },
        {
          title: '间接差价金额（明细）',
          value: 'indirectRebateAmountInfo',
          key: 'indirectRebateAmountInfo',
          disabled: !this.$hasPermissions('M_salesOrderTotalList_salesPrice')
        }
      ],
      showCols: []// 已选显示列数据
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '订单号', dataIndex: 'bizNo', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据类型', dataIndex: 'bizTypeDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户级别', dataIndex: 'buyerLevelDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', width: '16%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '总开单金额', dataIndex: 'totalAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '直接差价金额', dataIndex: 'directRebate', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '间接差价金额', dataIndex: 'indirectRebate', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '总实售价金额', dataIndex: 'totalRealAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '原总开单金额', dataIndex: 'totalBillingAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '原总实售金额', dataIndex: 'totalRealSaleAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } }
      ]
      if (this.showCols.includes('directRebateAmountInfo')) {
        arr.splice(6, 0, { title: '直接上级差价', dataIndex: 'directSuperiorsAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(7, 0, { title: '直接指定差价', dataIndex: 'directAssignAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(8, 0, { title: '直接总部差价', dataIndex: 'directHeadAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.showCols.includes('indirectRebateAmountInfo')) {
        const pos = this.showCols.includes('directRebateAmountInfo') ? 10 : 7
        arr.splice(pos, 0, { title: '间接上级差价', dataIndex: 'indirectSuperiorsAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(pos + 1, 0, { title: '间接指定差价', dataIndex: 'indirectAssignAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(pos + 2, 0, { title: '间接总部差价', dataIndex: 'indirectHeadAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 合计
    getCount (params) {
      rebateQueryCount(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
        }
      })
    },
    // 客户名称 change
    dealerChange (val) {
      if (val.row) {
        this.queryParam.buyerSn = val.row.dealerSn
      } else {
        this.queryParam.buyerSn = undefined
      }
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.time = []
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.bizNo = ''
      this.queryParam.bizType = undefined
      this.queryParam.buyerSn = undefined
      this.$refs.dealer.resetForm()
      this.$refs.ruleForm.resetFields()
      this.totalData = null
      this.$refs.table.clearTable()
    },
    // 表格高度自适应
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 210
    }
  },
  watch: {
    //  展开关闭 监听列表高度变化
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.setTableH()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.setTableH()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
