<template>
  <a-card size="small" :bordered="false" class="accountManagementList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="36">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="调回单号">
                <a-input allowClear placeholder="请输入调回单号" v-model.tirm="queryParam.recallBillNo"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="货架名称">
                <shelfList @change="shelfChange"></shelfList>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="产品编码">
                  <a-input allowClear placeholder="请输入产品编码" v-model.tirm="queryParam.code"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品名称">
                  <a-input allowClear placeholder="请输入产品名称" v-model.tirm="queryParam.name"/>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="outboundOrderList-refresh" >查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="outboundOrderList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px" v-if="activeKey==0">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-tabs type="card" v-model="queryParam.billState" @change="tabChange" class="replenishmentManagementList-tabs ">
        <a-tab-pane v-for="item in tabsList" :key="item.code">
          <p slot="tab">{{ item.name }}<span v-if="item.countNum&&item.code=='WAIT_CONFIRM'" style="color:red">({{ item.countNum }})</span></p>
        </a-tab-pane>
      </a-tabs>
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+77+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y:tableHeight }"
        @expand="expand"
        :defaultLoadData="true"
        :expandRowByClick="true"
        :defaultExpandAllRows="true"
        bordered>
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-primary"
            @click.stop="handleRecall(record)"
            id="shelfMonitoringList-warehousing-btn">退库</a-button>
          <a-button
            size="small"
            type="link"
            class="button-primary"
            @click.stop="handleCancel(record)"
            id="shelfMonitoringList-warehousing-btn">取消调回单</a-button>
        </template>
        <a-table
          v-if="innerData&&innerData[index]"
          size="small"
          class="inner-table"
          slot-scope="record,index"
          slot="expandedRowRender"
          :rowKey="(rec) => rec.id"
          :columns="innerColumns"
          :data-source="innerData[index].innerData"
          :pagination="false"
        >
        </a-table>
      </s-table>
    </a-spin>
    <!-- 退库 -->
    <recallModal :isOpenModal="showModal" :currentData="currentData" @close="showModal=false" @refresh="$refs.table.refresh(true)"></recallModal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import rangeDate from '@/views/common/rangeDate.vue'
import { STable } from '@/components'
import recallModal from './recallModal.vue'
import getDate from '@/libs/getDate.js'
import shelfList from '@/views/common/shelfList.vue'
import { shelfRecallList, shelfRecallDetailList, shelfRecallCancel, shelfRecallStateCount } from '@/api/shelfRecall.js'
export default {
  components: { STable, recallModal, rangeDate, shelfList },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      disabled: false,
      tableHeight: 0,
      showModal: false,
      advanced: false,
      currentData: null,
      activeKey: 0, // 默认的tab
      tabsList: [],
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      queryParam: {
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        recallBillNo: '',
        shelfSn: '', // 数字货架sn
        billState: 'ALL'
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调回单号', dataIndex: 'recallBillNo', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '货架名称', dataIndex: 'shelfInfo.shelfName', width: '25%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '状态', dataIndex: 'state', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调回总量', dataIndex: 'totalQty', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '实退总量', dataIndex: 'totalConfirmQty', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', width: '10%', align: 'left', scopedSlots: { customRender: 'action' } }
      ],
      innerColumns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '产品编码', dataIndex: 'product.code', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'product.name', width: '30%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '调回数量', dataIndex: 'qty', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '实退数量', dataIndex: 'confirmQty', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'product.unit', width: '15%', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      innerData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = this.queryParam
        if (params.billState == 'ALL') {
          params.billState = ''
        }
        return shelfRecallList(Object.assign(parameter, params)).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].innerData = []
            }
            this.innerData = data.list || []
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    // 选择货架
    shelfChange (obj) {
      this.queryParam.shelfSn = obj.key || undefined
    },
    // 时间改变
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 禁止选择今天之后的日期
    disabledDate (current) {
      return current && current > moment().endOf('day')
    },
    // 切换tab
    tabChange (key) {
      console.log(key)
      this.activeKey = key
      this.queryParam.billState = key
      this.$refs.table.refresh(true)
    },
    // 获取各类型下的数量
    getSumByType () {
      shelfRecallStateCount({}).then(res => {
        if (res.status == 200) {
          this.tabsList = [
            { code: 'ALL', name: '全部', countNum: 0 }, { code: 'WAIT_CONFIRM', name: '待退库', countNum: 0 }, { code: 'FINISH', name: '已完成', countNum: 0 }, { code: 'CANCEL', name: '已取消', countNum: 0 }
          ]
          this.queryParam.billState = 'ALL'
          this.tabsList[1].countNum = res.data.WAIT_CONFIRM || 0
          this.tabsList[2].countNum = res.data.FINISH || 0
          this.tabsList[3].countNum = res.data.CANCEL || 0
          this.$refs.table.refresh()
        }
      })
    },
    // 点击行或图标触发接口
    expand (expanded, record) {
      if (expanded) {
        this.getinnerData(record) // 获取表格内部数据
      }
    },
    // 获取子表格数据
    getinnerData (record) {
      this.spinning = true
      shelfRecallDetailList({ recallBillSn: record.recallBillSn }).then(res => {
        const ind = this.innerData.findIndex(item => item.id == record.id)
        if (ind >= 0) {
          if (res.status == 200 && res.data && res.data.length) {
            res.data.map((item, index) => {
              item.no = index + 1
            })
            this.innerData[ind].innerData = res.data
          } else {
            this.innerData[ind].innerData = []
          }
        }
        this.spinning = false
      })
    },
    // 重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam = {
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        recallBillNo: '', // 调回单号
        shelfSn: '', // 数字货架sn
        billState: 'ALL'
      }
      this.$refs.table.refresh(true)
    },
    // 退库
    handleRecall (row) {
      this.showModal = true
      this.currentData = row
    },
    // 取消掉回单
    handleCancel (row) {
      const _this = this
      _this.spinning = true
      this.$confirm({
        title: '提示',
        content: '确定取消调回单吗？',
        centered: true,
        onOk: () => {
          shelfRecallCancel({}).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.spinning = false
              _this.$refs.table.refresh()
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 265
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.getSumByType()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      setTimeout(() => {
        _this.setTableH()
      }, 400)
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .accountManagementList-wrap{
    .inner-table{
      background-color: #fff;
      border-bottom: 1px solid #eee;
      .ant-table{
         margin: 10px 100px;
         border-bottom: 1px solid #eee;
      }
    }
  }
</style>
