<template>
  <div>
    <a-card size="small" :bordered="false" class="transferReturnReportList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="transferReturnReportList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          @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="transferReturnReportList-time" :value="queryParam.time" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="调拨退货单号">
                <a-input id="transferReturnReportList-allocateReturnNo" v-model.trim="queryParam.allocateReturnNo" allowClear placeholder="请输入调拨退货单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="调拨退货对象名称">
                <a-input id="transferReturnReportList-targetName" v-model.trim="queryParam.targetName" allowClear placeholder="请输入调拨退货对象名称"/>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="调拨退货类型">
                  <AllocateType id="transferReturnReportList-allocateReturnTypeSn" :changeOnSelect="true" v-model="allocateTypeVal" @change="changeAllocatype"></AllocateType>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="调拨退货对象类型">
                  <v-select
                    code="TARGET_TYPE"
                    id="transferReturnReportList-targetType"
                    v-model="queryParam.targetType"
                    allowClear
                    placeholder="请选择调拨退货对象类型"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所在区域">
                  <subarea id="transferReturnReportList-subareaSn" ref="subarea" @change="subareaChange"></subarea>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button style="margin-left: 5px" type="primary" @click="handleSearch" :disabled="disabled" id="transferReturnReportList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="transferReturnReportList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('M_transferReturnReportExport')"
                id="transferReturnReportList-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>
    </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.id"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ x: 1100 ,y: tableHeight-30 }"
          :defaultLoadData="false"
          bordered>
          <!-- 调拨类型 -->
          <template slot="allocateType" slot-scope="text, record">
            <div>
              <span v-if="record.allocateSortName">{{ record.allocateSortName }}</span>
              <span v-if="record.allocateSortName&&record.allocateReturnTypeName">/</span>
              <span v-if="record.allocateReturnTypeName">{{ record.allocateReturnTypeName }}</span>
            </div>
          </template>
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="4" :sm="24"></a-col>
              <a-col :md="4" :sm="24">退货总数量：{{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ? totalData.totalQty : '--' }}</a-col>
              <a-col :md="4" :sm="24">坏件总数量：{{ (totalData && (totalData.totalBadQty || totalData.totalBadQty==0)) ? totalData.totalBadQty : '--' }}</a-col>
              <a-col :md="4" :sm="24">返库总数量：{{ (totalData && (totalData.totalBackStockQty || totalData.totalBackStockQty==0)) ? totalData.totalBackStockQty : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_transferReturnReportList_salesPrice')">退货总金额：{{ (totalData && (totalData.totalPrice || totalData.totalPrice==0)) ? toThousands(totalData.totalPrice) : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_transferReturnReportList_costPrice')">退货总成本：{{ (totalData && (totalData.totalCost || totalData.totalCost==0)) ? toThousands(totalData.totalCost) : '--' }}</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 subarea from '@/views/common/subarea.js'
import reportModal from '@/views/common/reportModal.vue'
import AllocateType from '@/views/common/allocateType.js'
// 接口
import { allocateReturnReportQueryPage, allocateReturnReportQueryCount, allocateReturnReportExport } from '@/api/reportData'
export default {
  name: 'TransferReturnReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, subarea, reportModal, AllocateType },
  data () {
    return {
      spinning: false,
      exportLoading: false, // 导出按钮加载状态
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      showExport: false, // 导出弹窗
      disabled: false, //  查询、重置按钮是否可操作
      //  查询条件
      queryParam: {
        // 退货完成日期 默认值
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime, // 开始日期
        endDate: getDate.getCurrMonthDays().endtime, // 结束日期
        allocateReturnNo: '', // 退货单号
        targetName: '', // 调拨退货对象名称
        costTypeSn: undefined, // 调拨退货  成本类型
        allocateSortSn: undefined, // 调拨退货类型
        allocateReturnTypeSn: undefined, // 调拨退货类型 sn
        targetType: undefined, // 调拨退货对象类型
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined// 分区
        }
      },
      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 allocateReturnReportQueryPage(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, // 统计数据
      allocateTypeVal: []// 调拨退货类型数据
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '退货单号', dataIndex: 'allocateReturnNo', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货完成日期', dataIndex: 'financeAuditTime', width: 130, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨退货对象类型', dataIndex: 'targetTypeDictValue', width: 120, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '调拨退货对象名称', dataIndex: 'targetName', width: 120, align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '费用类型', dataIndex: 'costTypeName', width: 90, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨退货类型', scopedSlots: { customRender: 'allocateType' }, width: 120, align: 'center' },
        { title: '退货总数量', dataIndex: 'totalQty', 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: 'totalBackStockQty', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
        // { title: '退货总金额', dataIndex: 'totalPrice', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } }
        // { title: '退货总成本', dataIndex: 'totalCost', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      if (this.$hasPermissions('M_transferReturnReportList_salesPrice')) { //  金额权限
        arr.push({ title: '退货总金额', dataIndex: 'totalPrice', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_transferReturnReportList_costPrice')) { //  成本价权限
        arr.push({ title: '退货总成本', dataIndex: 'totalCost', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  watch: {
    // 展开关闭
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    // 调拨退货类型
    changeAllocatype (val, opts) {
      this.allocateTypeVal = val || []
      this.queryParam.costTypeSn = val && val[0] ? val[0] : ''
      this.queryParam.allocateSortSn = val && val[1] ? val[1] : ''
      this.queryParam.allocateReturnTypeSn = val && val[2] ? val[2] : ''
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'M_transferReturnReportExport'
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(allocateReturnReportExport, params, '调拨退货单报表', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    // 总计
    getCount (params) {
      allocateReturnReportQueryCount(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 {
          _this.$message.error('请选择退货完成日期')
          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] || ''
    },
    // 区域分区 change
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    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.allocateReturnNo = ''
      this.queryParam.targetName = ''
      this.queryParam.costTypeSn = undefined
      this.queryParam.allocateSortSn = undefined
      this.queryParam.allocateReturnTypeSn = undefined
      this.queryParam.targetType = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.totalData = null
      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.allocateTypeVal = []
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => {
        _this.setTableH()
      })
      _this.resetSearchForm()
    },
    // 计算表格高度
    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>
