<template>
  <a-card size="small" :bordered="false" class="salesReturnsReportList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper">
        <a-form-model
          id="salesReturnsReportList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="7" :sm="24">
              <a-form-model-item label="退货完成日期" prop="time">
                <rangeDate ref="rangeDate" :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="salesReturnsReportList-salesReturnBillNo" v-model.trim="queryParam.salesReturnBillNo" allowClear placeholder="请输入退货单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-model-item label="所在区域">
                <subarea id="salesReturnsReportList-subareaSn" v-model="queryParam.subareaSn"></subarea>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户名称">
                  <custList id="salesReturnsReportList-dealerName" ref="custList" :itemSn="queryParam.dealerSn" @change="custChange"></custList>
                </a-form-model-item>
              </a-col>
              <a-col :md="5" :sm="24">
                <a-form-model-item label="客户级别">
                  <v-select
                    v-model="queryParam.dealerLevel"
                    ref="dealerLevel"
                    id="salesReturnsReportList-dealerLevel"
                    code="DEALER_LEVEL"
                    placeholder="请选择客户级别"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="11" :sm="24">
                <a-row>
                  <a-form-model-item label="地区" style="margin-bottom: 0!important;">
                    <a-col span="7">
                      <a-form-model-item prop="dealerProvinceSn" style="margin: 0;">
                        <a-select v-model="queryParam.dealerProvinceSn" allowClear @change="getCityList" 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 span="7" offset="1">
                      <a-form-model-item prop="dealerCitySn" style="margin: 0;">
                        <a-select v-model="queryParam.dealerCitySn" allowClear @change="getAreaList" placeholder="请选择市">
                          <a-select-option v-for="item in addrCityList" :value="item.id" :key="item.id + 'b'">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                    <a-col span="7" offset="1">
                      <a-form-model-item prop="dealerCountySn" style="margin: 0;">
                        <a-select v-model="queryParam.dealerCountySn" allowClear placeholder="请选择区/县">
                          <a-select-option v-for="item in addrDistrictList" :value="item.id" :key="item.id + 'c'">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                  </a-form-model-item>
                </a-row>
              </a-col>
            </template>
            <a-col :md="8" :sm="24" style="margin-bottom: 10px;">
              <a-button
                type="primary"
                class="button-info"
                size="small"
                @click="handleStock"
                id="salesReturnsReportList-stockDate">盘点区间日期</a-button>
              <a-button style="margin-left: 5px" type="primary" @click="handleSearch" :disabled="disabled" id="salesReturnsReportList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="salesReturnsReportList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_salesReturns_report')"
                id="salesReturnsReportList-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>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1740 }"
        :defaultLoadData="false"
        bordered>
        <template slot="footer">
          <a-row :gutter="15">
            <a-col :md="4" :sm="24">总数量：{{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ? totalData.totalQty : '--' }}</a-col>
            <a-col :md="4" :sm="24" v-if="$hasPermissions('B_isShowPrice')">开单退货金额：{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? totalData.totalAmount : '--' }}</a-col>
            <a-col :md="4" :sm="24" v-if="$hasPermissions('B_isShowPrice')">实售退货金额：{{ (totalData && (totalData.totalRealAmount || totalData.totalRealAmount==0)) ? totalData.totalRealAmount : '--' }}</a-col>
            <a-col :md="4" :sm="24" v-if="$hasPermissions('B_isShowPrice')">经销商金额：{{ (totalData && (totalData.totalWholesalePrice2 || totalData.totalWholesalePrice2==0)) ? totalData.totalWholesalePrice2 : '--' }}</a-col>
            <a-col :md="4" :sm="24" v-if="$hasPermissions('B_isShowPrice')">服务中心金额：{{ (totalData && (totalData.totalWholesalePrice1 || totalData.totalWholesalePrice1==0)) ? totalData.totalWholesalePrice1 : '--' }}</a-col>
            <a-col :md="4" :sm="24" v-if="$hasPermissions('B_isShowPrice')">特约加盟店金额：{{ (totalData && (totalData.totalWholesalePrice3 || totalData.totalWholesalePrice3==0)) ? totalData.totalWholesalePrice3 : '--' }}</a-col>
          </a-row>
        </template>
      </s-table>
    </a-spin>
    <!-- 导出提示框 -->
    <reportModal :visible="showExport" @close="showExport=false"></reportModal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import subarea from '@/views/common/subarea.js'
import custList from '@/views/common/custList.vue'
import reportModal from '@/views/common/reportModal.vue'
import { getArea } from '@/api/data'
import { hdExportExcel } from '@/libs/exportExcel'
import { reportSalesReturnList, reportSalesReturnCount, salesReturnsExport } from '@/api/reportData'
export default {
  name: 'SalesReturnsReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, subarea, custList, reportModal },
  data () {
    return {
      spinning: false,
      exportLoading: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      showExport: false,
      queryParam: { //  查询条件
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        salesReturnBillNo: '',
        subareaSn: undefined,
        dealerSn: '',
        dealerLevel: undefined,
        dealerProvinceSn: undefined,
        dealerCitySn: undefined,
        dealerCountySn: undefined
      },
      rules: {
        'time': [{ required: true, message: '请选择退货完成日期', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        delete params.time
        return reportSalesReturnList(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,
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [] //  区下拉
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '退货单号', dataIndex: 'salesReturnBillNo', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货完成日期', dataIndex: 'salesReturnDate', width: 130, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerName',width: 120, align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户级别', dataIndex: 'dealerLevelDictValue', width: 120, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '直接绑定客户名称', dataIndex: 'directDealerName', width: 120, align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '间接绑定客户名称', dataIndex: 'indirectDealerName', width: 120, align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '退货数量', dataIndex: 'totalQty', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '开单退货金额', dataIndex: 'totalAmount', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '经销商价', dataIndex: 'totalWholesalePrice2', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '服务中心价', dataIndex: 'totalWholesalePrice1', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '特约加盟店价', dataIndex: 'totalWholesalePrice3', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '实售退货金额', dataIndex: 'totalRealAmount', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '直接差价', dataIndex: 'totalDirectRebate', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '间接差价', dataIndex: 'totalIndirectRebate', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '坏件数量', dataIndex: 'totalBadQty', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作员', dataIndex: 'operatorName', width: 130, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true }
      ]
      if (this.$hasPermissions('B_isShowPrice')) { //  售价权限
        arr.splice(7, 0, { title: '开单退货金额', dataIndex: 'totalAmount', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(8, 0, { title: '经销商价', dataIndex: 'totalWholesalePrice2', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(9, 0, { title: '服务中心价', dataIndex: 'totalWholesalePrice1', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(10, 0, { title: '特约加盟店价', dataIndex: 'totalWholesalePrice3', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(11, 0, { title: '实售退货金额', dataIndex: 'totalRealAmount', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(12, 0, { title: '直接差价', dataIndex: 'totalDirectRebate', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(13, 0, { title: '间接差价', dataIndex: 'totalIndirectRebate', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    }
  },
  methods: {
    //  导出
    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(salesReturnsExport, params, '销售退货单报表', function () {
            _this.exportLoading = false
            _this.spinning = false
          })
        } else {
          return false
        }
      })
    },
    // 盘点库存日期
    handleStock () {
      this.$message.info('无盘点区间的起始/终止时间，请自行选择日期区间查询！')
    },
    // 总计
    getCount (params) {
      reportSalesReturnCount(params).then(res => {
        if (res.status == 200 && res.data) {
          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 {
          return false
        }
      })
    },
    //  创建时间  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] || ''
    },
    custChange (val) {
      this.queryParam.dealerSn = val.key
    },
    //  重置
    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.salesReturnBillNo = ''
      this.queryParam.subareaSn = undefined
      this.queryParam.dealerSn = undefined
      this.queryParam.dealerLevel = undefined
      this.queryParam.dealerProvinceSn = undefined
      this.queryParam.dealerCitySn = undefined
      this.queryParam.dealerCountySn = undefined
      if (this.advanced) {
        this.$refs.custList.resetForm()
      }
      this.totalData = null
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    // 获取城市列表
    getCityList (val) {
      this.addrCityList = []
      this.addrDistrictList = []
      this.queryParam.dealerCitySn = undefined
      this.queryParam.dealerCountySn = undefined
      if (val) {
        this.getArea('city', val)
      }
    },
    // 获取区县列表
    getAreaList (val) {
      this.addrDistrictList = []
      this.queryParam.dealerCountySn = undefined
      if (val) {
        this.getArea('district', val)
      }
    },
    //  省/市/区
    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 = []
          }
        }
      })
    },
    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>
