<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch2">
        <a-form-model
          id="productRebateDealerList-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="productRebateDealerList-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="productRebateDealerList-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="客户名称">
                <dealerSearchList ref="dealer" id="productRebateDealerList-buyerName" @change="dealerChange" />
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户级别">
                  <v-select
                    v-model="queryParam.dealer.dealerLevel"
                    id="productRebateDealerList-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="所在区域">
                  <subarea id="productRebateDealerList-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="productRebateDealerList-bizUserSn" v-model="queryParam.subareaArea.bizUserSn"></BizUser>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="省份">
                  <Area id="productRebateDealerList-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="差价归属方">
                  <dealerSearchList ref="parentDealer" id="productRebateDealerList-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="productRebateDealerList-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="单据类型" prop="bizType">
                  <a-select id="productRebateDealerList-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="6" :sm="24">
                <a-form-model-item label="客服">
                  <customerService id="productRebateDealerList-customerName" ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </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="productRebateDealerList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="productRebateDealerList-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-5+'px' }"
          :scroll="{ x: 2200,y: tableHeight-120 }"
          :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.directRebateAmount || totalData.directRebateAmount==0)) ? toThousands(totalData.directRebateAmount) : '--' }}</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 dealerSearchList from '@/views/common/dealerSearchList.vue'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import BizUser from '@/views/common/bizUser.js'
import customerService from '@/views/common/customerService'
// 接口
import { productRebateParentList, productRebateParentCount } from '@/api/reportData'
export default {
  components: { STable, VSelect, rangeDate, dealerSearchList, subarea, Area, BizUser, customerService },
  mixins: [commonMixin],
  name: 'ProductRebateDealerList',
  data () {
    return {
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 }, // 调整表单
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      //  查询条件
      queryParam: {
        time: [], // 日期
        beginDate: '', // 开始日期
        endDate: '', // 结束日期
        bizNo: '', // 订单号
        buyerSn: undefined, // 客户sn
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined, // 分区
          bizUserSn: undefined // 区域负责人
        },
        dealer: {
          dealerSn: undefined, // 客户sn
          dealerLevel: undefined, // 客户名称
          provinceSn: undefined// 省份
        },
        parentDealerSn: undefined, // 差价归属方
        rebateParentType: undefined, // 差价归属类型
        bizType: undefined, // 类型
        bizUserSn: undefined // 客服类型
      },
      bizTypeList: [// 单据类型数据
        { value: 'SALES', name: '采购差价' },
        { value: 'SALES_RETURN', 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 productRebateParentList(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
              // 差价归属类型 不等于 直接上级时，统计值恢复undefined
              if (data.list[i].rebateParentTypeDictValue && data.list[i].rebateParentTypeDictValue != '直接上级') {
                data.list[i].totalAmount = undefined
                data.list[i].totalRealAmount = undefined
                data.list[i].directRebateAmount = undefined
              }
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: 60, align: 'center' },
        { 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: '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: 'parentDealerName', width: 120, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '百分比', dataIndex: 'rebateRate', width: 120, align: 'center', customRender: function (text) { return ((text || text == 0) ? text * 100 + '%' : '--') } },
        { title: '差价归属类型', dataIndex: 'rebateParentTypeDictValue', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '总开单金额', dataIndex: 'totalAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '总实售金额', dataIndex: 'totalRealAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '总差价金额', dataIndex: 'directRebateAmount', width: 100, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '差价金额', dataIndex: 'rebateAmount', width: 80, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '单据类型', dataIndex: 'bizTypeDictValue', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '原总开单金额', dataIndex: 'totalAmountOrig', width: 80, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '原总实售金额', dataIndex: 'totalRealAmountOrig', width: 80, 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: {
    // 合计
    getCount (params) {
      productRebateParentCount(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] || ''
    },
    // 客户名称 change
    dealerChange (val) {
      if (val.row) {
        this.queryParam.buyerSn = val.row.dealerSn
      } else {
        this.queryParam.buyerSn = undefined
      }
    },
    // 区域分区
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // 差价归属方
    parentDealerChange (val) {
      if (val.row) {
        this.queryParam.parentDealerSn = val.row.dealerSn
      } else {
        this.queryParam.parentDealerSn = undefined
      }
    },
    //  查询
    handleSearch () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$refs.table.refresh(true)
        } else {
          this.$message.error('请选择日期')
          return false
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.time = []
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.bizNo = ''
      this.queryParam.buyerSn = undefined// 客户sn
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.subareaArea.bizUserSn = undefined// 区域负责人
      this.queryParam.dealer.dealerSn = undefined// 客户名称
      this.queryParam.dealer.dealerLevel = undefined// 客户等级
      this.queryParam.dealer.provinceSn = undefined// 省区域
      this.queryParam.parentDealerSn = undefined// 差价归属方
      this.queryParam.rebateParentType = undefined// 差价归属类型
      this.queryParam.bizType = undefined// 类型
      this.queryParam.bizUserSn = undefined// 客服类型

      this.$refs.dealer.resetForm()
      this.$refs.subarea.clearData()
      this.$refs.parentDealer.resetForm()
      this.$refs.ruleForm.resetFields()
      this.totalData = null
      this.$refs.table.clearTable()
    },
    // 初始化
    pageInit () {
      this.disabled = false
      this.spinning = false
      this.setTableH()
    },
    // 计算表格高度
    setTableH () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        const tableSearchH = this.$refs.tableSearch2.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>
