<template>
  <a-modal
    centered
    class="shelfSet-basicInfo-modal"
    :footer="null"
    :maskClosable="false"
    :title="'新增调回单——'+recallBillInfo.shelfName"
    v-model="isShow"
    @cancel="isShow = false"
    width="60%">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model id="shelfSet-basicInfo-form" ref="ruleForm" :model="queryParam" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-row :gutter="10">
          <a-col :md="8" :sm="24">
            <a-form-model-item label="产品编码"><a-input allowClear placeholder="请输入产品编码" v-model.tirm="queryParam.productCode" /></a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="产品名称"><a-input allowClear placeholder="请输入产品名称" v-model.tirm="queryParam.productName" /></a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="滞销天数">
              <a-input-group>
                <a-row>
                  <a-col :md="11" :sm="24">
                    <a-input-number
                      id="shelfMonitoringList-minUnsalableDays"
                      v-model="queryParam.unsalableDaysBegin"
                      :precision="0"
                      :min="0"
                      :max="999999"
                      placeholder="起始天数"
                      style="width: 100%;display: inline-block;"
                    />
                  </a-col>
                  <a-col :md="2" :sm="24"><span style="display: block;text-align: center;line-height: 32px;">至</span></a-col>
                  <a-col :md="11" :sm="24">
                    <a-input-number
                      id="shelfMonitoringList-maxUnsalableDays"
                      v-model="queryParam.unsalableDaysEnd"
                      :precision="0"
                      :min="0"
                      :max="999999"
                      placeholder="截止天数"
                      style="width: 100%;display: inline-block;"
                    />
                  </a-col>
                </a-row>
              </a-input-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" style="text-align: right;padding-right: 30px;">
            <a-button type="primary" @click="$refs.recallBillTable.refresh(true)" id="outboundOrderList-refresh">查询</a-button>
            <a-button style="margin-left: 8px" @click="resetSearchForm" id="outboundOrderList-reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form-model>
      <div class="tableCon">
        <div style="margin-bottom: 16px">
          <a-button type="primary" @click="handleSave">新增调回单</a-button>
          <span class="tableSpan" v-if="totalCategory ||totalNum">
            <template>
              已选
              <span>{{ totalCategory }}</span>
              款产品，共
              <span>{{ totalNum }}</span>
              件
            </template>
          </span>
          <span v-if="totalNum ||totalCategory"><a-checkbox @change="isShowChooseList" :checked="showChecked" size="small">仅显示已选产品</a-checkbox></span>
        </div>
        <s-table
          class="sTable"
          ref="recallBillTable"
          size="small"
          :rowKey="(record) => record.id"
          :row-selection="{columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: record.confirmQty <= 0 } })}"
          @rowSelection="onSelectChange"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: 450 }"
          :showPagination="false"
          bordered>
          <template slot="confirmQty" slot-scope="text, record">
            <div v-if="record.confirmQty === 0">--</div>
            <a-input-number
              v-else
              size="small"
              v-model="record.confirmQty"
              :readonly="hasChecked(record.id)"
              @change="changeNums(record)"
              :precision="0"
              :min="1"
              :max="record.recallBillQty?record.qty - record.recallBillQty :record.qty"
              placeholder="请输入"
              :style="{ width: '100%' }"
            ></a-input-number>
          </template>
        </s-table>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { STable } from '@/components'
import { commonMixin } from '@/utils/mixin'
import { shelfControlList } from '@/api/shelf'
import { shelfRecallSave } from '@/api/shelfRecall'
export default {
  name: 'AddRecallBillModal',
  mixins: [commonMixin],
  components: { STable },
  props: {
    openModal: {
      //  弹框显示状态
      type: Boolean,
      default: false
    },
    recallBillInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 17 }
      },
      queryParam: {
        //  查询条件
        shelfSn: '',
        productCode: undefined,
        productName: undefined,
        unsalableDaysBegin: undefined,
        unsalableDaysEnd: undefined
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '10%', align: 'center' },
        { title: '货位号', dataIndex: 'shelfPlaceCode', width: '15%', align: 'center' },
        {
          title: '产品编码',
          dataIndex: 'productCode',
          width: '20%',
          align: 'center',
          customRender: function (text) {
            return text || '--'
          }
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          width: '30%',
          align: 'center',
          customRender: function (text) {
            return text || '--'
          },
          ellipsis: true
        },
        {
          title: '最大库容',
          dataIndex: 'maxQty',
          width: '15%',
          align: 'center',
          customRender: function (text) {
            return text || text == 0 ? text : '--'
          }
        },
        {
          title: '补货在途',
          dataIndex: 'replenishBillQty',
          width: '15%',
          align: 'center',
          customRender: function (text) {
            return text || text == 0 ? text : '--'
          }
        },
        {
          title: '调回在途',
          dataIndex: 'recallBillQty',
          width: '15%',
          align: 'center',
          customRender: function (text) {
            return text || text == 0 ? text : '--'
          }
        },
        {
          title: '货架库存',
          dataIndex: 'qty',
          width: '15%',
          align: 'center',
          customRender: function (text) {
            return text || text == 0 ? text : '--'
          }
        },
        {
          title: '单位',
          dataIndex: 'productUnit',
          width: '15%',
          align: 'center',
          customRender: function (text) {
            return text || '--'
          }
        },
        {
          title: '滞销天数',
          dataIndex: 'unsalableDays',
          width: '15%',
          align: 'center',
          customRender: function (text) {
            return text || text == 0 ? text : '--'
          }
        },
        { title: '调回数量', width: '20%', align: 'center', scopedSlots: { customRender: 'confirmQty' } }
      ],
      showChecked: false,
      rowSelectionInfo: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // 获取列表
        this.spinning = true
        if (!this.checkValueRange()) {
          this.spinning = false
          return
        }
        this.queryParam.shelfSn = this.recallBillInfo.shelfSn
        return shelfControlList(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].confirmQty = cur ? cur.confirmQty : (data[i].confirmQty || data[i].recallBillQty ? data[i].qty - data[i].recallBillQty : data[i].qty)
              data[i].checked = !cur
            }
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    onSelectChange (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.confirmQty = data.confirmQty
      }
      row.splice()
    },
    //  确定新增回调单
    handleSave () {
      const _this = this
      if (this.rowSelectionInfo.selectedRows && this.rowSelectionInfo.selectedRows.length == 0) {
        this.$message.warning('请先选择产品')
        return
      }
      const flag = this.rowSelectionInfo.selectedRows.some(con => !con.confirmQty && con.confirmQty != 0)
      if (flag) {
        this.$message.warning('调回数量不能为空！')
        return
      }
      const arr = []
      this.rowSelectionInfo.selectedRows.forEach((item, index) => {
        arr.push({
          shelfSn: item.shelfSn,
          shelfPlaceSn: item.shelfPlaceSn,
          shelfPlaceCode: item.shelfPlaceCode,
          productSn: item.productSn,
          productCode: item.productCode,
          productName: item.productName,
          qty: item.confirmQty
        })
      })
      _this.spinning = true
      const params = {
        shelfSn: this.recallBillInfo.shelfSn,
        detailList: arr
      }
      shelfRecallSave(params).then(res => {
        _this.spinning = false
        if (res.status == 200) {
          _this.$emit('ok')
          _this.isShow = false
          this.$refs.recallBillTable.clearSelected()
          _this.$message.success('保存并确认成功')
        }
      })
    },
    isShowChooseList (e) {
      this.showChecked = e.target.checked
      this.$refs.recallBillTable.refresh(true)
    },
    // 重置
    resetSearchForm () {
      const obj = {
        //  查询条件
        shelfSn: this.recallBillInfo.shelfSn,
        productCode: undefined,
        productName: undefined,
        unsalableDaysBegin: undefined,
        unsalableDaysEnd: undefined
      }
      this.queryParam = obj
      this.$refs.recallBillTable.refresh(true)
    },
    // 校验滞销天数数值范围
    checkValueRange () {
      const isONull = this.queryParam.unsalableDaysBegin === null || this.queryParam.unsalableDaysBegin === undefined
      const isOEmpty = this.queryParam.unsalableDaysBegin === ''
      const isOZero = this.queryParam.unsalableDaysBegin === 0
      const isTNull = this.queryParam.unsalableDaysEnd === null || this.queryParam.unsalableDaysEnd === undefined
      const isTEmpty = this.queryParam.unsalableDaysEnd === ''
      const isTZero = this.queryParam.unsalableDaysEnd === 0
      //  第一个为空（可为null可为空字符）第二个不为空
      //  第一个不为空第二个为空（可为null可为空字符）
      //  第一个大于第二个
      if ((isONull || isOEmpty) && (this.queryParam.unsalableDaysEnd || isTZero)) {
        this.$message.info('请输入正确的滞销天数查询范围！')
        return false
      }
      if ((this.queryParam.unsalableDaysBegin || isOZero) && (isTNull || isTEmpty)) {
        this.$message.info('请输入正确的滞销天数查询范围！')
        return false
      }
      if (this.queryParam.unsalableDaysBegin > this.queryParam.unsalableDaysEnd) {
        this.$message.info('请输入正确的滞销天数查询范围！')
        return false
      }
      this.queryParam.unsalableDaysBegin = this.queryParam.unsalableDaysBegin > 999999999 ? 999999999 : this.queryParam.unsalableDaysBegin
      this.queryParam.unsalableDaysEnd = this.queryParam.unsalableDaysEnd > 999999999 ? 999999999 : this.queryParam.unsalableDaysEnd
      return true
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.$refs.ruleForm.resetFields()
      } else {
        this.$nextTick(() => {
          this.$refs.recallBillTable.clearSelected()
          this.showChecked = false
          this.resetSearchForm()
        })
      }
    }
  },
  computed: {
    totalNum () {
      let ret = 0
      this.rowSelectionInfo && this.rowSelectionInfo.selectedRows.map(item => {
        ret = ret + item.confirmQty
      })
      return ret
    },
    totalCategory () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRows.length
    }
  }
}
</script>

<style lang="less">
.shelfSet-basicInfo-modal {
  .ant-modal-body {
    padding: 40px 40px 24px;
  }
  .ant-form-item {
    margin-bottom: 15px;
  }
  .btn-cont {
    text-align: center;
    margin: 35px 0 10px;
  }
  .tableSpan {
    margin: 0 16px;
    span {
      margin: 0 10px;
      color: red;
      font-weight: bold;
    }
  }
}
</style>
