<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <div class="table-page-search-wrapper newTableSearchName" ref="tableSearch">
        <a-form-model
          id="billingOrderReport-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :rules="rules"
          :model="queryParam"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="退货完成时间" prop="time">
                <rangeDate ref="rangeDate" id="billingOrderReport-time" :value="queryParam.time" @change="dateChange"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="供应商名称">
                <supplier id="billingOrderReport-supplierName" v-model="queryParam.supplier.supplierSn" @change="getSupplierName" placeholder="请输入供应商名称"></supplier>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="采购退货单号" >
                <a-input id="billingOrderReport-sparePartsReturnNo" v-model.trim="queryParam.sparePartsReturnNo" allowClear placeholder="请输入采购退货单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="地区">
                <AreaList id="billingOrderReport-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
              </a-form-model-item>
            </a-col>
            <a-col :md="24" :sm="24" style="margin-bottom: 10px;text-align:center;">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="billingOrderReport-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="billingOrderReport-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_regionTypeSalesReportExport')"
                id="billingOrderReport-export">导出</a-button>
            </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"
          :defaultLoadData="false"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ x: 1550 ,y: tableHeight-136 }"
          bordered>
          <template slot="footer" v-if="countLabel.length||countBrandLabel.length">
            <a-row>
              <a-col span="2">合计：</a-col>
              <a-col span="22">
                <a-row>
                  <a-col span="4" v-for="item in countLabel" :key="item.key">
                    {{ item.title }}：{{ totalData?(totalData[item.dataIndex]||totalData[item.dataIndex]==0)?toThousands(totalData[item.dataIndex]):'--':'--' }}
                  </a-col>
                </a-row>
                <a-row>
                  <a-col span="24" style="padding:8px;"></a-col>
                </a-row>
                <a-row>
                  <a-col span="4" v-for="item in countBrandLabel" :key="item.key">
                    {{ item.title }}：{{ totalData?(totalData[item.dataIndex] ||totalData[item.dataIndex]==0)?toThousands(totalData[item.dataIndex]):'--':'--' }}
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
          </template>
        </s-table>
      </a-spin>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import AreaList from '@/views/common/areaList.js'
import reportModal from '@/views/common/reportModal.vue'
import supplier from '@/views/common/supplier.js'
// 接口
import { queryBillNoPage, queryBillNoCount, queryBillNoTitle, billNoExport } from '@/api/reportData.js'
export default {
  name: 'BillingOrderReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, reportModal, AreaList, supplier },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      showExport: false, // 导出弹窗
      tableHeight: 0, // 表格高度
      queryParam: {
        // 退货完成时间 默认值
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        sparePartsReturnNo: undefined, // 采购退货单号
        supplier: {
          supplierSn: undefined, // 供应商 sn
          supplierName: undefined, // 供应商名称
          provinceSn: undefined, // 省
          citySn: undefined, // 市
          districtSn: undefined// 区
        }
      },
      countLabel: [], // 统计分类数据
      countBrandLabel: [], // 统计品牌数据
      columns: [], // 表头数据
      totalData: null, // 统计
      rules: {
        'time': [{ required: true, message: '请选择退货完成时间', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        delete params.time
        // 获取列表数据 有分页
        return queryBillNoPage(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
        })
      }
    }
  },
  methods: {
    // 选择供应商
    getSupplierName (val, item) {
      this.queryParam.supplier.supplierName = item ? item.supplierName : undefined
      this.queryParam.supplier.supplierSn = val
    },
    // 总计
    getCount (params) {
      queryBillNoCount(params).then(res => {
        if (res.status == 200 && res.data) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  退货完成时间  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] || ''
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择退货完成时间')
          return false
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.$refs.ruleForm.resetFields()
      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.supplier.provinceSn = undefined
      this.queryParam.supplier.citySn = undefined
      this.queryParam.supplier.districtSn = undefined
      this.queryParam.sparePartsReturnNo = undefined
      this.queryParam.supplier.supplierName = undefined
      this.queryParam.supplier.supplierSn = undefined
      this.$refs.areaList.clearData()
      this.$refs.table.clearTable()
    },
    // 地区
    areaChange (val) {
      this.queryParam.supplier.provinceSn = val[0] ? val[0] : ''
      this.queryParam.supplier.citySn = val[1] ? val[1] : ''
      this.queryParam.supplier.districtSn = val[2] ? val[2] : ''
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'B_billingReturn_Report'
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(billNoExport, params, '开单采退单', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          _this.$message.error('请选择退货完成时间')
          return false
        }
      })
    },
    // 获取表头
    async getTableTitle () {
      const _this = this
      const tableTitle = await queryBillNoTitle().then(res => res.data)
      this.columns = tableTitle.list
      this.countLabel = tableTitle.count.filter(item => item.title.indexOf('品牌') < 0)
      this.countBrandLabel = tableTitle.count.filter(item => item.title.indexOf('品牌') >= 0)
      this.columns.map(item => {
        let mw = 20
        if (item.customRender == 'amount') {
          mw = 15
          item.customRender = function (text) { return (text || text == 0) ? _this.toThousands(text) : '--' }
        } else {
          item.customRender = function (text) { return text || '--' }
        }
        const w = item.title.length * mw
        const tw = w <= 80 ? mw * 5 : w
        item.width = tw + 'px'
        this.tableWidth = this.tableWidth + tw
      })
      this.resetSearchForm()
    },
    // 初始化
    pageInit () {
      this.getTableTitle()
      this.setTableH()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 215
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
