<template>
  <div class="salesReturnReceive-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesReturnReceive-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="salesReturnReceive-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;">客户名称：{{ ordeDetail&&ordeDetail.buyerName || '--' }}</span>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesReturnReceive-cont">
        <a-form layout="inline" style="margin-bottom:10px;" @keyup.enter.native="$refs.table.refresh(true)">
          <a-form-item label="产品编码" prop="productCode">
            <a-input id="salesReturnReceive-productCode" v-model.trim="queryParam.productCode" placeholder="请输入产品编码" allowClear />
          </a-form-item>
          <a-form-item label="产品名称" prop="productName">
            <a-input id="salesReturnReceive-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" class="button-info" @click="$refs.table.refresh(true)" :disabled="disabled" id="salesReturnReceive-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="salesReturnReceive-reset">重置</a-button>
          </a-form-item>
        </a-form>
        <div style="border-top:1px solid #eee;padding-top:10px;">
          <a-button type="primary" :loading="loading" class="button-info" @click="openModal = true">新增产品</a-button>
          <a-button type="primary" :loading="loading" class="button-error" @click="handlePlss">批量实收</a-button>
          <div style="float:right;color:#999;margin-top:8px;">说明：红色行表示收货时新增的产品</div>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          :rowClassName="(record, index) => record.addFlag == '1' ? (record.addType == 'WAREHOUSE_RECEIVE'?'redBg-row':'orgBg-row'):''"
          size="small"
          :rowKey="(record) => record.id"
          :row-selection="{ columnWidth: 40, getCheckboxProps:record =>({props: { disabled: record.addFlag == '1' }}) }"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 仓库实收数量 -->
          <template slot="receiveQty" slot-scope="text, record">
            <a-input-number
              size="small"
              v-model="record.receiveQty"
              :precision="0"
              :min="0"
              :max="999999"
              @blur="e => onCellBlurReceiveQty(e.target.value, record)"
              placeholder="请输入"
              style="width: 100%;" />
          </template>
          <!-- 退货原因 -->
          <template slot="returnReason" slot-scope="text, record">
            <a-select
              style="width:100%;"
              v-model="record.returnReason"
              v-if="record.addFlag == '1'&&record.addType == 'WAREHOUSE_RECEIVE'"
              @change="e => onCellBlurReturnReason(e, record)"
              placeholder="请选择退货原因"
            >
              <a-select-option v-for="item in returnReasonList" :value="item.code">
                {{ item.dispName }}
              </a-select-option>
            </a-select>
            <span v-else>{{ record.returnReasonDictValue }}</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                v-if="record.addFlag == '1'&&record.addType == 'WAREHOUSE_RECEIVE'"
                size="small"
                type="link"
                class="button-warning"
                @click="handleDel(record)"
              >删除</a-button>
            </div>
          </template>
        </s-table>
        <div class="footer-btn">
          <a-button
            size="large"
            style="padding: 0 60px;"
            :disabled="spinning"
            type="primary"
            class="button-primary"
            @click="handleSubmit()"
            id="salesReturn-handleSubmit">提交</a-button>
        </div>
      </a-card>
    </a-spin>
    <!-- 添加产品 -->
    <chooseProductsModal ref="chooseProduct" :openModal="openModal" :buyerSn="$route.params.buyerSn" @close="openModal=false" @addProduct="addProduct"></chooseProductsModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import chooseProductsModal from './chooseProductsModal.vue'
import { salesReturnDetail, salesReturnReceive } from '@/api/salesReturn'
import {
  salesReturnDetailList, salesReturnDetailReceiveBatch, salesReturnDetailUpdateReceiveQty, salesReturnDetailUpdateReason, insertByReceive, deleteByReceiver
} from '@/api/salesReturnDetail'
export default {
  name: 'Receiving',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    chooseProductsModal
  },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      orderSn: null,
      disabled: false,
      openModal: false, // 添加产品
      ordeDetail: null,
      loading: false,
      // 已选产品
      dataSource: [],
      productForm: {
        salesReturnBillSn: ''
      },
      chooseLoadData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 查询总计
        this.productForm.salesReturnBillSn = this.$route.params.sn
        return salesReturnDetailList(Object.assign(parameter, this.productForm, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              data.list[i].receiveQtyBackups = data.list[i].receiveQty
              data.list[i].returnReasonBackups = data.list[i].returnReason
            }
            this.disabled = false
            this.chooseLoadData = data.list
          }
          return data
        })
      },
      rowSelectionInfo: null,
      queryParam: {
        productCode: '',
        productName: ''
      },
      returnReasonList: [] // 申请退货列表
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', align: 'center', width: '10%', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '20%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '申请退货数量', dataIndex: 'qty', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库实收数量', dataIndex: 'receiveQty', align: 'center', width: '10%', scopedSlots: { customRender: 'receiveQty' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货单价', dataIndex: 'price', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货原因', dataIndex: 'returnReason', width: '20%', align: 'center', scopedSlots: { customRender: 'returnReason' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'receiveCheckList' })
    },
    // 添加产品
    addProduct (data) {
      const params = {
        'salesReturnBillSn': this.orderSn,
        'salesReturnBillNo': this.ordeDetail.salesReturnBillNo,
        ...data
      }
      insertByReceive(params).then(res => {
        if (res.status == 200) {
          this.resetSearchForm()
          this.$message.info(res.message)
        }
        this.$refs.chooseProduct.resetLoading()
      })
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.loading = true
          _this.spinning = true
          deleteByReceiver({ salesReturnDetailSn: row.salesReturnDetailSn }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm(false)
            }
            _this.$message.info(res.message)
            _this.loading = false
            _this.spinning = false
          })
        }
      })
    },
    // 批量实收
    handlePlss () {
      const _this = this
      const snList = []
      _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows.map(item => {
        snList.push(item.salesReturnDetailSn)
      })
      if (snList.length == 0) {
        _this.$message.warning('请先选择产品！')
        return
      }
      _this.$confirm({
        title: '提示',
        content: '确认要批量实收吗？',
        centered: true,
        onOk () {
          _this.loading = true
          _this.spinning = true
          salesReturnDetailReceiveBatch(snList).then(res => {
            if (res.status == 200) {
              _this.rowSelectionInfo = null
              _this.$refs.table.clearTable()
              _this.resetSearchForm()
              _this.$message.success(res.message)
            }
            _this.loading = false
            _this.spinning = false
          })
        }
      })
    },
    // 仓库实收数量修改
    onCellBlurReceiveQty (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.receiveQtyBackups) {
        this.loading = true
        this.spinning = true
        salesReturnDetailUpdateReceiveQty({
          salesReturnDetailSn: record.salesReturnDetailSn,
          receiveQty: val
        }).then(res => {
          if (res.status == 200) {
            this.$refs.table.refresh()
            this.$message.success(res.message)
          } else {
            record.receiveQty = record.receiveQtyBackups
          }
          this.loading = false
          this.spinning = false
        })
      } else {
        record.receiveQty = record.receiveQtyBackups
      }
    },
    // 修改退货原因
    onCellBlurReturnReason (e, record) {
      this.loading = true
      this.spinning = true
      salesReturnDetailUpdateReason({
        salesReturnDetailSn: record.salesReturnDetailSn,
        returnReason: record.returnReason
      }).then(res => {
        if (res.status == 200) {
          this.$refs.table.refresh()
          this.$message.success(res.message)
        } else {
          record.returnReason = record.returnReasonBackups
        }
        this.loading = false
        this.spinning = false
      })
    },
    // 获取单据详细
    getOrderDetail () {
      this.rowSelectionInfo = null
      salesReturnDetail({ sn: this.orderSn }).then(res => {
        this.ordeDetail = res.data || null
      })
    },
    // 审核销售单
    handleSubmit () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '提交后将进入品检环节，确认提交吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          salesReturnReceive({ salesReturnBillSn: _this.orderSn }).then(res => {
            if (res.status == 200) {
              _this.handleBack()
              _this.$message.success(res.message)
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  重置
    resetSearchForm (flag) {
      this.queryParam.productName = ''
      this.queryParam.productCode = ''
      this.$refs.table.refresh(!!flag)
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.orderSn = this.$route.params.sn
      this.returnReasonList = this.$store.state.app.returnReason
      this.getOrderDetail()
    },
    setTableH () {
      this.tableHeight = window.innerHeight - 390
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.$refs.table.refresh(true)
      this.pageInit()
    }
  },
  activated () {
    this.$refs.table.refresh()
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .salesReturnReceive-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      height: 100%;
    }
    .footer-btn{
      text-align: center;
    }
    .salesReturnReceive-cont{
      margin-top: 10px;
      .sTable{
        margin-top: 10px;
      }
      .total-bar{
        display: flex;
        align-items: center;
        justify-content: space-between;
        > div{
          &:last-child{
            display: flex;
            align-items: center;
            justify-content: space-between;
            > div{
              padding: 0 10px;
            }
          }
        }
      }
    }
    .redBg-row{
      background-color: #f5beb4;
    }
    .orgBg-row{
      background-color: #fffca2;
    }
  }
</style>
