<template>
  <a-modal
    centered
    class="creatReplenish-confirm-modal"
    :footer="null"
    :maskClosable="false"
    :title="modalTit"
    v-model="isShow"
    @cancel="isShow = false"
    width="80%">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper">
        <a-form-model
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          @keyup.enter.native="$refs.table.refresh(true)" >
          <a-row :gutter="5">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品编码">
                <a-input id="chooseShelf-code" ref="searchProductCode" 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="chooseShelf-name" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="10" :sm="24">
              <a-form-model-item label="库存情况">
                <a-checkbox-group :options="options" v-model="queryParam.stockStateList" @change="onStockChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="24" :sm="24" style="margin-bottom: 10px;text-align:right;">
              <a-button type="primary" @click="$refs.table.refresh(true)" id="chooseShelf-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" id="chooseShelf-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div>
        <div class="table-operator">
          <div>
            <a-button type="primary" @click="handleSave">创建补货单</a-button>
            <span style="margin-left:10px;" v-if="totalCategory||totalQty">
              已选 {{ totalCategory }} 款产品，共 {{ totalQty }} 件
            </span>
          </div>
          <div style="margin-left:20px;" v-if="totalCategory||totalQty">
            <a-checkbox @change="changeShowChecked">
              仅显示已选产品
            </a-checkbox>
          </div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :row-selection="{columnWidth: 40}"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :data="loadData"
          :style="{ height: '480px' }"
          :scroll="{ y: 450 }"
          :showPagination="false"
          bordered>
          <template slot="action" slot-scope="text, record">
            <a-input-number
              size="small"
              :readonly="hasChecked(record.id)"
              v-model="record.replenishQty"
              @change="changeNums(record)"
              :precision="0"
              :min="1"
              placeholder="请输入"
              style="width: 100%" />
          </template>
        </s-table>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { queryProductListForReplenish } from '@/api/shelf'
import { saveMainAndDetail } from '@/api/shelfReplenish'
export default {
  name: 'CreatReplenishmentOrder',
  components: { STable, VSelect },
  mixins: [commonMixin],
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    nowData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    modalTit () {
      const hjName = this.nowData ? this.nowData.shelfName : ''
      return '待补货产品 —— ' + hjName
    },
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '货位号', dataIndex: 'shelfPlaceCode', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'productCode', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '18%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '最大库容', dataIndex: 'maxQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '货架库存', dataIndex: 'qty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '补货在途', dataIndex: 'replenishBillQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '调回在途', dataIndex: 'recallBillQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '待补货数量', dataIndex: 'replenishBillWaitQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '门店库存数量', dataIndex: 'qplsStockQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'productUnit', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '本次补货数量', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      return arr
    },
    totalCategory () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRows.length
    },
    totalQty () {
      let ret = 0
      this.rowSelectionInfo && this.rowSelectionInfo.selectedRows.map(item => {
        ret = ret + item.replenishQty
      })
      return ret
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      options: [
        { label: '库存充足', value: 'stockEnough' },
        { label: '部分缺货', value: 'portionStockout' },
        { label: '全部缺货', value: 'allStockout' }
      ],
      queryParam: {
        productCode: '', //  产品编码
        productName: '', //  产品名称
        stockStateList: []
      },
      allData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        this.disabled = true
        this.queryParam.shelfSn = this.nowData.shelfSn
        return queryProductListForReplenish(this.queryParam).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            if (this.showChecked) {
              data = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
            }
            for (var i = 0; i < data.length; i++) {
              data[i].no = i + 1
              const row = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
              const cur = row.find(item => item.id == data[i].id)
              data[i].replenishQty = cur ? cur.replenishQty : (data[i].replenishBillWaitQty || 1)
              data[i].checked = !cur
            }
            this.disabled = false
          }
          this.spinning = false
          this.allData = data
          return data
        })
      },
      rowSelectionInfo: null,
      showChecked: false
    }
  },
  methods: {
    onStockChange (val) {
      this.queryParam.stockStateList = val
    },
    // 显示已选产品
    changeShowChecked (e) {
      this.showChecked = e.target.checked
      this.$refs.table.refresh(true)
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    hasChecked: function (value) {
      const row = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
      const cur = row.find(item => item.id == value)
      return !cur
    },
    changeNums (data) {
      const row = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
      const cur = row.find(item => item.id == data.id)
      if (cur) {
        cur.replenishQty = data.replenishQty
      }
      row.splice()
    },
    // 重置
    resetSearchForm () {
      this.queryParam = {
        productCode: '', //  产品编码
        productName: '', //  产品名称
        stockStateList: []
      }
      this.$refs.table.refresh(true)
    },
    //  确认补货
    handleSave () {
      if (this.totalCategory) {
        const data = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
        const dataList = []
        data.map(item => {
          dataList.push({
            shelfPlaceSn: item.shelfPlaceSn,
            shelfPlaceCode: item.shelfPlaceCode,
            productSn: item.productSn,
            productCode: item.productCode,
            qty: item.replenishQty
          })
        })
        // 开始提交
        this.spinning = true
        saveMainAndDetail({
          shelfSn: this.nowData.shelfSn,
          dealerSn: this.nowData.dealerSn,
          detailList: dataList
        }).then(res => {
          if (res.status == 200) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.$emit('close')
          }
          this.spinning = false
        })
      } else {
        this.$message.info('请选择产品')
      }
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
      } else {
        this.$nextTick(() => {
          this.resetSearchForm()
          this.$refs.table.clearSelected()
          this.showChecked = false
        })
      }
    }
  }
}
</script>

<style lang="less">
.creatReplenish-confirm-modal {
	.table-operator {
		padding:0 10px 10px 0;
		display:flex;
		align-items: center;
	}
}
</style>
