<template>
  <a-card size="small" :bordered="false" class="shelfMonitoringList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form-model
          id="shelfMonitoringList-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="shelfSn">
                <shelfSList ref="shelfList" @change="shelfChange" :itemSn="queryParam.shelfSn"></shelfSList>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="货位号">
                <a-input id="shelfMonitoringList-shelfPlaceCode" v-model.trim="queryParam.shelfPlaceCode" allowClear placeholder="请输入货位号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品编码">
                <a-input id="shelfMonitoringList-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品名称">
                  <a-input id="shelfMonitoringList-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="货位产品状态">
                  <v-select
                    v-model="queryParam.state"
                    ref="state"
                    id="shelfMonitoringList-state"
                    code="SHELF_PRODUCT_STATE"
                    placeholder="请选择货位产品状态"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="滞销天数">
                  <a-input-group>
                    <a-row>
                      <a-col :span="11">
                        <a-input-number
                          id="shelfMonitoringList-beginDate"
                          v-model="queryParam.beginDate"
                          :precision="0"
                          :min="0"
                          :max="999999"
                          placeholder="起始天数"
                          style="width: 100%;display: inline-block;" />
                      </a-col>
                      <a-col :span="2"><span style="display: block;text-align: center;line-height: 32px;">至</span></a-col>
                      <a-col :span="11">
                        <a-input-number
                          id="shelfMonitoringList-endDate"
                          v-model="queryParam.endDate"
                          :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>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="shelfMonitoringList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="shelfMonitoringList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <!-- 未选择合作商 -->
      <div class="unChoose" v-show="!isSearch">
        <a-icon type="exclamation-circle" theme="filled" :style="{ fontSize: '18px', color: '#ff9900', verticalAlign: 'sub', marginRight: '5px' }" />
        <span>请选择一个货架后点击查询按钮</span>
      </div>
      <div v-show="isSearch">
        <div style="margin-bottom: 10px">
          <div style="display: inline-block;margin-right: 15px;vertical-align: middle;font-weight: bold;font-size: 14px;">
            <a-divider type="vertical" style="background: #FF7D0C;width: 3px;height: 16px;" />
            <span>{{ shelfName || '--' }}</span>
          </div>
          <!-- <a-button type="primary" class="button-error" id="shelfMonitoringList-export" @click="handleAddBack">新增调回单</a-button> -->
          <span style="margin-left: 5px">
            <template v-if="rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length > 0">
              {{ `已选 ${rowSelectionInfo.selectedRowKeys.length} 项` }}
            </template>
          </span>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          size="small"
          :rowKey="(record) => record.shelfPlaceSn"
          :columns="columns"
          :data="loadData"
          rowKeyName="shelfPlaceSn"
          :row-selection="{ columnWidth: 40 }"
          @rowSelection="rowSelectionFun"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          :showPagination="false"
          bordered>
          <!-- 绑定产品状态 -->
          <template slot="state" slot-scope="text, record">
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{ record.productTypeName }}</span>
              </template>
              {{ record.stateDictValue }}
              <a-icon type="exclamation-circle" theme="filled" style="color: #39f;font-size: 16px;margin-left: 5px;vertical-align: middle;cursor: pointer;" />
            </a-tooltip>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              class="button-primary"
              @click="handleDetail(record)"
              id="shelfMonitoringList-warehousing-btn">出入库明细</a-button>
          </template>
        </s-table>
      </div>
    </a-spin>
    <!-- 新增调回单 -->
    <add-modal :openModal="openModal" :nowData="nowData" @ok="handleOk" @close="handleCancel" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import addModal from './addModal.vue'
import shelfSList from '@/views/common/shelfList.vue'
import { shelfControlList } from '@/api/shelf'
export default {
  components: { STable, VSelect, addModal, shelfSList },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      tableHeight: 0,
      queryParam: { //  查询条件
        shelfSn: undefined,
        shelfPlaceCode: '',
        productCode: '',
        productName: '',
        state: undefined,
        beginDate: undefined,
        endDate: undefined
      },
      rules: {
        'shelfSn': [{ required: true, message: '请选择货架', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '货位号', dataIndex: 'shelfPlaceCode', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '绑定产品编码', dataIndex: 'productCode', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '绑定产品名称', dataIndex: 'productName', width: '23%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '货位产品状态', scopedSlots: { customRender: 'state' }, width: '15%', align: 'center' },
        { title: '当前库存', dataIndex: 'qty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '最大库容', dataIndex: 'maxQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '滞销天数', dataIndex: 'unsalableDays', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'left' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // 校验滞销天数数值范围
        if (this.checkValueRange()) {
          this.disabled = true
          this.spinning = true
          return shelfControlList(this.queryParam).then(res => {
            let data
            if (res.status == 200) {
              data = res.data
              for (var i = 0; i < data.length; i++) {
                data[i].no = i + 1
              }
              this.disabled = false
            }
            this.spinning = false
            return data
          })
        } else {
          const _this = this
          this.disabled = true
          this.spinning = true
          return new Promise(function (resolve, reject) {
            const data = []
            _this.disabled = false
            _this.spinning = false
            resolve(data)
          })
        }
      },
      rowSelectionInfo: null,
      isSearch: false,
      openModal: false, //  新增编辑  弹框
      shelfName: '', // 货架名称
      nowData: {
        list: [],
        shelfInfo: {}
      }
    }
  },
  methods: {
    // 校验滞销天数数值范围
    checkValueRange () {
      const isONull = this.queryParam.beginDate === null || this.queryParam.beginDate === undefined
      const isOEmpty = this.queryParam.beginDate === ''
      const isOZero = this.queryParam.beginDate === 0
      const isTNull = this.queryParam.endDate === null || this.queryParam.endDate === undefined
      const isTEmpty = this.queryParam.endDate === ''
      const isTZero = this.queryParam.endDate === 0
      //  第一个为空（可为null可为空字符）第二个不为空
      //  第一个不为空第二个为空（可为null可为空字符）
      //  第一个大于第二个
      if ((isONull || isOEmpty) && (this.queryParam.endDate || isTZero)) {
        this.$message.info('请输入正确的滞销天数查询范围！')
        return false
      }
      if ((this.queryParam.beginDate || isOZero) && (isTNull || isTEmpty)) {
        this.$message.info('请输入正确的滞销天数查询范围！')
        return false
      }
      if (this.queryParam.beginDate > this.queryParam.endDate) {
        this.$message.info('请输入正确的滞销天数查询范围！')
        return false
      }
      this.queryParam.beginDate = this.queryParam.beginDate > 999999999 ? 999999999 : this.queryParam.beginDate
      this.queryParam.endDate = this.queryParam.endDate > 999999999 ? 999999999 : this.queryParam.endDate
      return true
    },
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 货架  change
    shelfChange (obj) {
      this.queryParam.shelfSn = obj.key || undefined
      this.shelfName = obj && obj.row && obj.row.shelfName || ''
    },
    //  查询
    handleSearch () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$refs.table.refresh(true)
          this.isSearch = true
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.isSearch = false
      this.queryParam.shelfSn = undefined
      this.$refs.shelfList.resetForm()
      this.queryParam.shelfPlaceCode = ''
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.state = undefined
      this.queryParam.beginDate = undefined
      this.queryParam.endDate = undefined
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    // 新增调回单
    handleAddBack () {
      if (!this.rowSelectionInfo || (this.rowSelectionInfo && this.rowSelectionInfo.selectedRows.length < 1)) {
        this.$message.warning('请至少选择一个产品')
      } else {
        this.nowData.list = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
        this.nowData.shelfInfo = {
          shelfName: this.shelfName,
          shelfSn: this.queryParam.shelfSn
        }
        this.openModal = true
      }
    },
    //  详情
    handleDetail (row) {
      this.$router.push({ path: `/numsGoodsShelves/shelfMonitoring/warehouseDetail/${row.shelfPlaceSn}/${row.productSn}` })
    },
    handleOk () {
      this.$refs.table.refresh()
      this.$refs.table.clearSelected() // 清空表格选中项
      this.isSearch = true
    },
    handleCancel () {
      this.openModal = false
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 245
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      setTimeout(() => {
        _this.setTableH()
      }, 400)
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .shelfMonitoringList-wrap{
    .unChoose {
      text-align: center;
      margin: 280px 0 340px;
      font-size: 16px;
    }
  }
</style>
