<template>
  <a-card size="small" :bordered="false" class="priceDifferenceDetailList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form-model
          id="priceDifferenceDetailList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="4" :sm="24">
              <a-form-model-item label="月份" prop="month">
                <a-month-picker
                  placeholder="请选择月份"
                  locale="zh-cn"
                  v-model="queryParam.month"
                  @change="onChange"
                  :disabled-date="disabledDate"
                  style="width: 100%;"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="3" :sm="24">
              <a-form-model-item label="省份" prop="provinceSn">
                <a-select v-model="queryParam.provinceSn" allowClear placeholder="请选择省">
                  <a-select-option v-for="item in addrProvinceList" :value="item.id" :key="item.id + 'a'">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="记账门店">
                <custList id="priceDifferenceDetailList-rebateDealer" ref="rebateDealerList" @change="rebateDealerChange"></custList>
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="客户名称">
                <custList id="priceDifferenceDetailList-custList" ref="custList" :itemSn="queryParam.dealerSn" @change="custChange"></custList>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="priceDifferenceDetailList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="priceDifferenceDetailList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_priceDifferenceDetail_Export')"
                id="allocationDetailsList-export">导出</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :defaultLoadData="false"
        bordered>
        <template slot="footer">
          <table>
            <tr>
              <td width="51%" colspan="4"></td>
              <td width="8%">
                <div v-if="$hasPermissions('B_isShowPrice')">实售金额：{{ (totalData && (totalData.totalRealAmount || totalData.totalRealAmount==0)) ? toThousands(totalData.totalRealAmount) : '--' }}</div>
              </td>
              <td width="8%">
                <div v-if="$hasPermissions('B_isShowPrice')">开单金额：{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? toThousands(totalData.totalAmount) : '--' }}</div>
              </td>
              <td width="8%">
                <div v-if="$hasPermissions('B_isShowPrice')">差价金额：{{ (totalData && (totalData.rebateAmount || totalData.rebateAmount==0)) ? toThousands(totalData.rebateAmount) : '--' }}</div>
              </td>
              <td width="25%" colspan="2"></td>
            </tr>
          </table>
        </template>
      </s-table>
    </a-spin>
    <!-- 导出提示框 -->
    <reportModal :visible="showExport" @close="showExport=false"></reportModal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import { STable, VSelect } from '@/components'
import custList from '@/views/common/custList.vue'
import { getArea } from '@/api/data'
import subarea from '@/views/common/subarea.js'
import rangeDate from '@/views/common/rangeDate.vue'
import reportModal from '@/views/common/reportModal.vue'
import { hdExportExcel } from '@/libs/exportExcel'
import { reportRebateReportList, reportRebateCount, reportRebateExport } from '@/api/reportData'
export default {
  name: 'PriceDifferenceDetailReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, custList, subarea, rangeDate, reportModal },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      exportLoading: false,
      showExport: false,
      queryParam: { //  查询条件
        month: moment().format('YYYY-MM'),
        provinceSn: undefined,
        rebateDealerSn: undefined,
        dealerSn: undefined
      },
      rules: {
        'month': [{ required: true, message: '请选择月份', trigger: 'change' }],
        'provinceSn': [{ required: true, message: '请选择省份', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      addrProvinceList: [], //  省下拉
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        if (params.month) {
          params.month = params.month + '-01'
        }
        this.spinning = true
        return reportRebateReportList(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
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      totalData: null
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '月份', dataIndex: 'month', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '省份', dataIndex: 'provinceName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '记账门店', dataIndex: 'rebateDealerName', width: '15%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户名称', dataIndex: 'dealerName', width: '16%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品品牌+二级分类', dataIndex: 'productBrandAndType2', width: '15%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '类型', dataIndex: 'bizType', width: '10%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      if (this.$hasPermissions('B_isShowPrice')) { //  售价权限
        arr.splice(4, 0, { title: '实售金额', dataIndex: 'totalRealAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(5, 0, { title: '开单金额', dataIndex: 'totalAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(6, 0, { title: '差价金额', dataIndex: 'rebateAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    onChange (date, dateString) {
      this.queryParam.month = dateString
    },
    disabledDate (current) {
      return current && current > moment().endOf('day')
    },
    // 合计
    getCount (params) {
      reportRebateCount(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 {
          console.log('error submit!!')
          return false
        }
      })
    },
    rebateDealerChange (val) {
      this.queryParam.rebateDealerSn = val.key
    },
    custChange (val) {
      this.queryParam.dealerSn = val.key
    },
    //  省/市/区
    getArea (leve, sn) {
      let params
      if (leve == 'province') {
        params = { type: '2' }
      } else {
        params = { parentId: sn, type: leve == 'city' ? '3' : '4' }
      }
      getArea(params).then(res => {
        if (res.status == 200) {
          if (leve == 'province') {
            this.addrProvinceList = res.data || []
          } else if (leve == 'city') {
            this.addrCityList = res.data || []
          } else if (leve == 'district') {
            this.addrDistrictList = res.data || []
          }
        } else {
          if (leve == 'province') {
            this.addrProvinceList = []
          } else if (leve == 'city') {
            this.addrCityList = []
          } else if (leve == 'district') {
            this.addrDistrictList = []
          }
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.month = moment().format('YYYY-MM')
      this.queryParam.provinceSn = undefined
      this.queryParam.rebateDealerSn = undefined
      this.queryParam.dealerSn = undefined
      this.$refs.rebateDealerList.resetForm()
      this.totalData = null
      if (this.advanced) {
        this.$refs.custList.resetForm()
      }
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(reportRebateExport, params, '差价明细报表', function () {
            _this.exportLoading = false
            _this.spinning = false
          })
        } else {
          return false
        }
      })
    },
    pageInit () {
      this.getArea('province')
    }
  },
  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>
