<template>
  <div>
    <a-card size="small" :bordered="false" class="transferReturnDetailReport-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="transferReturnDetailReport-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="transferReturnDetailReport-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="transferReturnDetailReport-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="调拨退货单号">
                <a-input id="transferReturnDetailReport-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="transferReturnDetailReport-targetName" v-model.trim="queryParam.targetName" allowClear placeholder="请输入调拨退货对象名称"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="调拨退货类型">
                <AllocateType id="transferReturnDetailReport-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="transferReturnDetailReport-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="transferReturnDetailReport-subareaSn" ref="subarea" @change="subareaChange"></subarea>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="所在省份">
                <Area id="transferReturnDetailReport-provinceSn" defValKey="id" v-model="queryParam.provinceSn" placeholder="请选择省"></Area>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品名称">
                  <a-input id="transferReturnDetailReport-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="品牌分类">
                  <v-select code="BRAND_TYPE" id="transferReturnDetailReport-productBrandTypeSn" v-model="queryParam.productBrandTypeSn" allowClear placeholder="请选择品牌分类"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品品牌">
                  <ProductBrand id="transferReturnDetailReport-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品分类">
                  <ProductType id="transferReturnDetailReport-productType" placeholder="请选择产品分类" @change="changeProductType" v-model="productType"></ProductType>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="24" :sm="24" style="margin-bottom: 10px;text-align:center;">
              <a-button style="margin-left: 5px" type="primary" @click="handleSearch" :disabled="disabled" id="transferReturnDetailReport-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="transferReturnDetailReport-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('M_transferReturnDetailReportExport')"
                id="transferReturnDetailReport-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+70+'px' }"
          :scroll="{ x: 3050 ,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.returnQty || totalData.returnQty==0)) ? totalData.returnQty : '--' }}</a-col>
              <a-col :md="4" :sm="24">坏件总数量：{{ (totalData && (totalData.badQty || totalData.badQty==0)) ? totalData.badQty : '--' }}</a-col>
              <a-col :md="4" :sm="24">返库总数量：{{ (totalData && (totalData.backStockQty || totalData.backStockQty==0)) ? totalData.backStockQty : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_transferReturnDetailReportList_salesPrice')">退货总金额：{{ (totalData && (totalData.totalPrice || totalData.totalPrice==0)) ? toThousands(totalData.totalPrice) : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_transferReturnDetailReportList_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 Area from '@/views/common/area.js'
import ProductBrand from '@/views/common/productBrand.js'
import ProductType from '@/views/common/productType.js'
// 接口
import { allocateReturnReportDetailQueryPage, allocateReturnReportDetailQueryCount, allocateReturnReportDetailExport } from '@/api/reportData'
export default {
  name: 'TransferReturnDetailReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, subarea, Area, ProductBrand, ProductType, reportModal, AllocateType },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      showExport: false, // 导出弹窗
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      //  查询条件
      queryParam: {
        // 退货完成日期 默认日期
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime, // 开始日期
        endDate: getDate.getCurrMonthDays().endtime, // 结束日期
        allocateReturnNo: '', // 调拨退货单号
        productCode: '', // 产品编码
        productName: '', // 产品名称
        targetName: '', // 调拨退货对象名称
        costTypeSn: undefined, // 调拨退货  成本类型
        allocateSortSn: undefined, // 调拨退货类型
        allocateReturnTypeSn: undefined, // 调拨退货类型 sn
        targetType: undefined, // 调拨退货对象类型
        productBrandTypeSn: undefined, // 品牌分类
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined// 分区
        },
        provinceSn: undefined// 省份编码
      },
      rules: {
        'time': [{ required: true, message: '请选择退货完成日期', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam, {
          // 产品相关查询
          productEntity: {
            productBrandSn: this.queryParam.productBrandSn,
            code: this.queryParam.productCode,
            name: this.queryParam.productName,
            productTypeSn1: this.queryParam.productTypeSn1,
            productTypeSn2: this.queryParam.productTypeSn2,
            productTypeSn3: this.queryParam.productTypeSn3
          },
          // 品牌分类
          productBrandEntity: {
            brandType: this.queryParam.productBrandTypeSn
          }
        })
        delete params.time
        // 获取列表数据 有分页
        return allocateReturnReportDetailQueryPage(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, // 统计数据
      productType: [], // 产品分类
      allocateTypeVal: []// 调拨退货类型数据
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { 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: 'dealerEntity.provinceName', width: 90, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { 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: 'productEntity.productBrandName', width: 130, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '二级分类', dataIndex: 'productEntity.productTypeName2', width: 130, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: 250, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品编码', dataIndex: 'productEntity.code', width: 150, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: 50, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货数量', dataIndex: 'returnQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '坏件数量', dataIndex: 'badQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '返库数量', dataIndex: 'backStockQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      if (this.$hasPermissions('M_transferReturnDetailReportList_salesPrice')) { //  售价权限
        arr.push({ title: '退货单价', dataIndex: 'price', width: 80, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.push({ title: '退货金额', dataIndex: 'totalPrice', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_transferReturnDetailReportList_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: {
    // 调拨退货类型 change
    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] : ''
    },
    // 总计
    getCount (params) {
      allocateReturnReportDetailQueryCount(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.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.targetName = ''
      this.queryParam.costTypeSn = undefined
      this.queryParam.allocateSortSn = undefined
      this.queryParam.allocateReturnTypeSn = undefined
      this.allocateTypeVal = []
      this.queryParam.targetType = undefined
      this.queryParam.productBrandTypeSn = undefined
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.provinceSn = undefined
      this.productType = []
      this.$refs.subarea.clearData()
      this.totalData = null
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'M_transferReturnDetailReportExport'
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(allocateReturnReportDetailExport, params, '调拨退货明细报表', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => {
        _this.setTableH()
      })
      _this.resetSearchForm()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 200
    }
  },
  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>
