<template>
  <div class="bulkReturnGoodsEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="bulkReturnGoodsEdit-cont">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="bulkReturnGoodsEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_sparePartsRetPrint')">
          <Print :disabled="localDataSource.length==0" @handlePrint="handlePrint"></Print>
        </template>
      </a-page-header>
      <!-- 选择产品 -->
      <a-card size="small" :bordered="false" class="bulkReturnGoodsEdit-cont">
        <!-- 搜索条件 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
            <a-row :gutter="15">
              <a-col :md="6" :sm="24">
                <a-form-item label="散件入库单号" prop="sparePartsPurchaseNo">
                  <a-input id="bulkReturnGoodsEdit-sparePartsPurchaseNo" v-model.trim="queryParam.sparePartsPurchaseNo" placeholder="请输入散件入库单号" allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品编码" prop="productCode">
                  <a-input id="bulkReturnGoodsEdit-productCode" v-model.trim="queryParam.productCode" placeholder="请输入产品编码" allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品名称" prop="productName">
                  <a-input id="bulkReturnGoodsEdit-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="bulkReturnGoodsEdit-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="bulkReturnGoodsEdit-reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :customRow="handleClickRow"
          :defaultLoadData="false"
          :data="loadData"
          :scroll="{ y:150 }"
          bordered>
          <!-- 退货单价 -->
          <template slot="purchaseCost" slot-scope="text, record">
            <a-input-number
              size="small"
              id="bulkReturnGoodsEdit-purchaseCost"
              v-model="record.purchaseCost"
              :precision="2"
              :min="0"
              :max="999999"
              placeholder="请输入"
              style="width: 100%;" />
          </template>
          <!-- 退货数量 -->
          <template slot="purchaseQty" slot-scope="text, record">
            <a-input-number
              size="small"
              id="bulkReturnGoodsEdit-purchaseQty"
              v-model="record.purchaseQty"
              :precision="0"
              :min="1"
              :max="record.currentStockQty"
              placeholder="请输入"
              style="width: 100%;" />
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button size="small" type="link" class="button-primary" @click="handleAdd(record)" id="bulkReturnGoodsEdit-add-btn">添加</a-button>
          </template>
        </s-table>
      </a-card>
      <!-- 已选产品 -->
      <a-card size="small" :bordered="false" class="bulkReturnGoodsEdit-cont">
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom:10px">
          <div slot="message">
            总款数<strong>{{ (productTotal&&(productTotal.purchaseSize || productTotal.purchaseSize==0)) ? productTotal.purchaseSize : '--' }}</strong> ，
            总数量<strong>{{ (productTotal&&(productTotal.purchaseQty || productTotal.purchaseQty==0)) ? productTotal.purchaseQty : '--' }}</strong> ，
            总金额<strong>{{ (productTotal&&(productTotal.purchaseCost || productTotal.purchaseCost==0)) ? '￥'+productTotal.purchaseCost : '--' }}</strong>
          </div>
        </a-alert>
        <!-- 筛选条件 -->
        <a-row :gutter="15" justify="space-between">
          <a-col :span="17">
            <div class="table-page-search-wrapper">
              <a-form layout="inline" @keyup.enter.native="$refs.chooseTable.refresh(true)">
                <a-row :gutter="15">
                  <a-col :md="9" :sm="24">
                    <a-form-item label="产品编码" prop="productCode">
                      <a-input id="bulkReturnGoodsEdit-productCode" v-model.trim="chooseQueryParam.productCode" placeholder="请输入产品编码" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="9" :sm="24">
                    <a-form-item label="产品名称" prop="productName">
                      <a-input id="bulkReturnGoodsEdit-productName" v-model.trim="chooseQueryParam.productName" placeholder="请输入产品名称" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                    <a-button type="primary" @click="$refs.chooseTable.refresh(true)" :disabled="chooseDisabled" id="bulkReturnGoodsEdit-refresh">查询</a-button>
                    <a-button style="margin-left: 8px" @click="chooseResetSearchForm" :disabled="chooseDisabled" id="bulkReturnGoodsEdit-reset">重置</a-button>
                  </a-col>
                </a-row>
              </a-form>
            </div>
          </a-col>
          <a-col :span="7" style="text-align: right;"></a-col>
        </a-row>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="chooseTable"
          size="small"
          :rowKey="(record) => record.id"
          :columns="chooseColumns"
          :data="chooseLoadData"
          :defaultLoadData="false"
          :scroll="{ y:200 }"
          bordered>
          <!-- 退货单价 -->
          <template slot="purchaseCost" slot-scope="text, record">
            <a-input-number
              size="small"
              id="bulkReturnGoodsEdit-purchaseCost"
              v-model="record.purchaseCost"
              :precision="2"
              :min="0"
              :max="999999"
              placeholder="请输入"
              @blur="e => purchaseCostBlur(e.target.value, record)"
              style="width: 100%;" />
          </template>
          <!-- 退货数量 -->
          <template slot="purchaseQty" slot-scope="text, record">
            <a-input-number
              size="small"
              id="bulkReturnGoodsEdit-purchaseQty"
              v-model="record.purchaseQty"
              :precision="0"
              :min="1"
              :max="999999"
              placeholder="请输入"
              @blur="e => purchaseQtyBlur(e.target.value, record)"
              style="width: 100%;" />
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button size="small" type="link" class="button-error" @click="handleDel(record)" id="bulkReturnGoodsEdit-del-btn">删除</a-button>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="bulkReturnGoodsEdit-submit-btn"
        size="large"
        :disabled="spinning"
        class="button-primary"
        @click="handleSubmit"
        style="padding: 0 60px;">提交</a-button>
    </div>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
import { warehouseAllList } from '@/api/warehouse'
import { sparePartsPurDetailFinishList } from '@/api/sparePartsPur'
import {
  sparePartsRetDetailList,
  sparePartsRetDetailSave,
  sparePartsRetDetailCount,
  sparePartsRetDetailDel,
  sparePartsRetSubmit,
  sparePartsRetDetailPrint,
  sparePartsRetDetailExport } from '@/api/sparePartsRet'
export default {
  name: 'BulkReturnGoodsgrabEdit',
  components: { STable, VSelect, Print },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      queryParam: {
        productCode: '',
        productName: '',
        sparePartsPurchaseNo: ''
      },
      disabled: false, //  查询、重置按钮是否可操作
      dataSource: [],
      // 表头
      columns: [
        { title: '散件入库单号', dataIndex: 'sparePartsPurchaseNo', width: '16%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'productCode', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '16%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '入库价格', dataIndex: 'putCost', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '入库数量', dataIndex: 'putQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '已退数量', dataIndex: 'returnQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '可退数量', dataIndex: 'refundableQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '库存数量', dataIndex: 'currentStockQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'productUnit', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货单价', scopedSlots: { customRender: 'purchaseCost' }, width: '7%', align: 'center' },
        { title: '退货数量', scopedSlots: { customRender: 'purchaseQty' }, width: '7%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return sparePartsPurDetailFinishList(Object.assign(parameter, this.queryParam, { state: 'FINISH', supplierSn: this.$route.params.supplierSn })).then(res => {
          const 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
          }
          this.dataSource = data.list
          this.disabled = false
          return data
        })
      },
      chooseDisabled: false,
      chooseQueryParam: {
        productCode: '',
        productName: ''
      },
      // 表头
      chooseColumns: [
        { title: '散件入库单号', dataIndex: 'sparePartsPurchaseNo', width: '18%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'productCode', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '20%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productUnit', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货单价', scopedSlots: { customRender: 'purchaseCost' }, width: '8%', align: 'center' },
        { title: '退货数量', scopedSlots: { customRender: 'purchaseQty' }, width: '8%', align: 'center' },
        { title: '退货金额', dataIndex: 'purchaseAmount', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        this.chooseDisabled = true
        return sparePartsRetDetailList(Object.assign(parameter, this.chooseQueryParam, { sparePartsReturnSn: this.$route.params.sn })).then(res => {
          const 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].purchaseCostBackups = data.list[i].purchaseCost
            data.list[i].purchaseQtyBackups = data.list[i].purchaseQty
          }
          this.localDataSource = data.list || []
          this.chooseDisabled = false
          this.getDetailCount()
          return data
        })
      },
      localDataSource: [],
      productTotal: null, //  合计
      warehouseList: [] // 仓库列表
    }
  },
  methods: {
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      let url = sparePartsRetDetailPrint
      const params = { sn: this.$route.params.sn }
      if (type == 'export') { //  导出
        url = sparePartsRetDetailExport
      }
      // 打印或导出
      hdPrint(printerType, type, url, params, '散件退货单(抓单)', function () {
        _this.spinning = false
      })
    },
    // 合计
    getDetailCount () {
      sparePartsRetDetailCount(Object.assign(this.chooseQueryParam, { sparePartsReturnSn: this.$route.params.sn })).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.sparePartsPurchaseNo = ''
      this.$refs.table.refresh(true)
    },
    // 已选产品  重置
    chooseResetSearchForm () {
      this.chooseQueryParam.productCode = ''
      this.chooseQueryParam.productName = ''
      this.$refs.chooseTable.refresh(true)
    },
    //  添加/编辑
    handleAdd (row, isEdit) {
      if (!isEdit && !row.purchaseCost && row.purchaseCost != 0) {
        this.$message.warning('请输入退货单价后再添加！')
        return
      }
      if (!isEdit && !row.purchaseQty) {
        this.$message.warning('请输入退货数量后再添加！')
        return
      }
      const params = {
        id: isEdit ? row.id : undefined,
        sparePartsDetailSn: isEdit ? row.sparePartsDetailSn : row.id,
        sparePartsReturnSn: this.$route.params.sn,
        purchaseCost: row.purchaseCost,
        purchaseQty: row.purchaseQty,
        productSn: row.productSn,
        productCode: row.productCode,
        productOrigCode: row.productOrigCode,
        productTypeSn1: row.productTypeSn1,
        productTypeSn2: row.productTypeSn2,
        productTypeSn3: row.productTypeSn3,
        brandSn: row.brandSn,
        warehouseLocationSn: row.warehouseLocationSn,
        warehouseSn: row.warehouseSn,
        productExpiryDate: row.productExpiryDate
      }
      if (isEdit) { // 编辑
        // 清空成本价或数量时,值应保持未清空前的值，因成本价和数量都不可为空
        if (!row.purchaseCost) {
          row.purchaseCost = row.purchaseCostBackups
          return
        }
        if (!row.purchaseQty) {
          row.purchaseQty = row.purchaseQtyBackups
          return
        }
      }
      this.spinning = true
      sparePartsRetDetailSave(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.$refs.chooseTable.refresh()
          this.spinning = false
        } else {
          this.spinning = false
          this.$refs.chooseTable.refresh()
        }
      })
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          sparePartsRetDetailDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.$refs.chooseTable.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  提交
    handleSubmit () {
      const _this = this
      if (this.localDataSource.length < 1) {
        this.$message.info('退货单中不存在任何产品，无法提交')
        return
      }
      _this.spinning = true
      sparePartsRetSubmit({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          setTimeout(() => {
            _this.handleBack()
            _this.spinning = false
          }, 1000)
        } else {
          _this.spinning = false
        }
      })
    },
    // 已选产品 单价  blur
    purchaseCostBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.purchaseCostBackups) {
        this.handleAdd(record, 'edit')
      }
    },
    // 已选产品 数量  blur
    purchaseQtyBlur (val, record) {
      if (val != record.purchaseQtyBackups) {
        this.handleAdd(record, 'edit')
      }
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/bulkManagement/bulkReturnGoods/list' })
    },
    //  导入明细
    handleImport () {
      console.log(333)
    },
    // 双击快速添加
    handleClickRow (record) {
      return {
        on: {
          dblclick: (event) => {
            this.handleAdd(record)
          }
        }
      }
    },
    // 仓库
    getWarehouse () {
      warehouseAllList({}).then(res => {
        if (res.status == 200) {
          this.warehouseList = res.data
        } else {
          this.warehouseList = []
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    initPage () {
      this.getWarehouse()
      this.resetSearchForm()
      this.chooseResetSearchForm()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.initPage()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.initPage()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .bulkReturnGoodsEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .bulkReturnGoodsEdit-cont{
      margin-bottom: 10px;
    }
  }
</style>
