<template>
  <div>
    <!-- 搜索条件 -->
    <div class="table-page-search-wrapper">
      <a-form-model
        id="purchaseReturnOrderList-form"
        ref="ruleForm"
        class="form-model-con"
        layout="inline"
        :model="queryParam"
        :rules="rules"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        @keyup.enter.native="handleSearch" >
        <a-row :gutter="15">
          <a-col :md="6" :sm="24">
            <a-form-model-item label="出库时间" prop="time">
              <rangeDate ref="rangeDate" @change="dateChange" />
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-model-item label="采购退货单号" prop="purchaseReturnNo">
              <a-input v-model.trim="queryParam.purchaseReturnNo" allowClear placeholder="请输入采购退货单号"/>
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-model-item label="供应商" prop="returnTargetSn">
              <a-select
                id="purchaseReturnOrderList-returnTargetSn"
                placeholder="请选择供应商"
                allowClear
                v-model="queryParam.returnTargetSn"
                :showSearch="true"
                option-filter-prop="children"
                :filter-option="filterOption">
                <a-select-option v-for="item in supplierList" :pyCode="item.pyCode" :key="item.purchaseTargetSn" :value="item.purchaseTargetSn">{{ item.purchaseTargetName }}</a-select-option>
              </a-select>
            </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="purchaseReturnOrderList-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="purchaseReturnOrderList-reset">重置</a-button>
            <a-button
              style="margin-left: 5px"
              type="primary"
              class="button-warning"
              @click="handleExport"
              :disabled="disabled"
              :loading="exportLoading"
              v-if="$hasPermissions('B_purchaseReturnReportExport')"
              id="purchaseReturnOrderList-export">导出</a-button>
          </a-col>

        </a-row>
      </a-form-model>
    </div>
    <!-- 合计 -->
    <a-alert type="info" style="margin-bottom:10px">
      <div class="ftext" slot="message">
        总单数：<strong>{{ statisticsNum?statisticsNum :'--' }}</strong>；
        产品总数量：<strong>{{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ? totalData.totalQty : '--' }}</strong>；
        <div style="display: inline-block;" v-if="$hasPermissions('M_ShowAllCost')">
          退货总成本：<strong>{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? toThousands(totalData.totalAmount) : '--' }}</strong>；
        </div>
      </div>
    </a-alert>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      size="small"
      :rowKey="(record) => record.receivingBillSn"
      :columns="columns"
      :data="loadData"
      :defaultLoadData="false"
      bordered>
    </s-table>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { downloadExcel } from '@/libs/JGPrint.js'
import { purchaseReturnList, purchaseReturnQueryCount, purchaseReturnExport } from '@/api/reportData'
import { queryReturnSupplierList } from '@/api/purchaseReturn'
export default {
  components: { STable, VSelect, rangeDate },
  mixins: [commonMixin],
  data () {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      queryParam: { //  查询条件
        time: [],
        beginDate: '',
        endDate: '',
        purchaseReturnNo: undefined,
        returnTargetSn: undefined,
        showCost: undefined
      },
      dataList: null, // 总单数
      rules: {
        'time': [{ required: true, message: '请选择出库时间', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      statisticsNum: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        this.$emit('spinning', true)
        delete params.time
        if (params.beginDate) {
          return purchaseReturnList(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.$emit('spinning', false)
            this.statisticsNum = data.count
            return data
          })
        } else {
          const _this = this
          return new Promise(function (resolve, reject) {
            const data = {
              pageNo: 1,
              pageSize: 10,
              list: [],
              count: 0
            }
            _this.disabled = false
            _this.$emit('spinning', false)
            _this.$message.info('请选择出库时间')
            resolve(data)
          })
        }
      },
      totalData: null, //  合计
      supplierList: null
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '采购退货单号', dataIndex: 'purchaseReturnNo', width: '17%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '供应商', dataIndex: 'returnTargetName', width: '17%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '款数', dataIndex: 'totalCategory', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '数量', dataIndex: 'totalQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '成本', dataIndex: 'totalAmount', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '出库时间', dataIndex: 'outStockTime', width: '16%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      if (this.$hasPermissions('M_ShowAllCost')) { //  售价权限
        arr.splice(5, 0, { title: '成本', dataIndex: 'totalAmount', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取供应商数据
    getSupperList () {
      queryReturnSupplierList({}).then(res => {
        if (res.status == 200) {
          this.supplierList = res.data
        } else {
          this.supplierList = []
        }
      })
    },
    // 合计
    getCount (params) {
      purchaseReturnQueryCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  创建时间  change
    dateChange (date) {
      this.queryParam.time = date
      this.queryParam.beginDate = date[0] || ''
      this.queryParam.endDate = date[1] || ''
    },
    //  查询
    handleSearch () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.queryParam.showCost = this.$hasPermissions('M_ShowAllCost') ? 1 : 0
          this.$refs.table.refresh(true)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.time = []
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.purchaseReturnNo = undefined
      this.queryParam.returnTargetSn = undefined
      this.totalData = null
      this.statisticsNum = null
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.queryParam.showCost = this.$hasPermissions('M_ShowAllCost') ? 1 : 0
          const params = _this.queryParam
          _this.exportLoading = true
          _this.spinning = true
          purchaseReturnExport(params).then(res => {
            downloadExcel(res, '采购退货单报表')
            _this.exportLoading = false
            _this.spinning = false
          })
        } else {
          return false
        }
      })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.resetSearchForm()
      this.getSupperList()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.resetSearchForm()
      this.getSupperList()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style>
</style>
