<template>
  <a-card size="small" :bordered="false" class="accountManagementList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" style="width:100%;overflow: hidden;" class="table-page-search-wrapper">
        <a-tabs type="card" v-model="queryParam.bizType" @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>
        <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 v-model="queryParam.shelfSn"></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.productCode"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品名称">
                  <a-input allowClear placeholder="请输入产品名称" v-model.tirm="queryParam.productName"/>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="getSumByType" :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>
      <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 }"
        :expandedRowKeys="expandedRowKeys"
        @expand="expandFun"
        :expandRowByClick="true"
        :defaultLoadData="false"
        bordered>
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="record.billState=='WAIT_CONFIRM'"
            class="button-primary"
            @click.stop="handleRecall(record)"
          >退库</a-button>
          <a-button
            size="small"
            v-if="record.billState=='WAIT_CONFIRM'"
            type="link"
            class="button-primary"
            @click.stop="handleCancel(record)"
          >取消调回单</a-button>
          <a-button
            size="small"
            v-if="record.billState=='CANCEL'"
            type="link"
            class="button-primary"
            @click.stop="handleDelete(record)"
          >删除</a-button>
          <span v-if="record.billState=='FINISH'">--</span>
        </template>
        <a-table
          v-if="innerData&&innerData[index]"
          size="small"
          class="inner-table"
          slot-scope="record,index"
          slot="expandedRowRender"
          :rowKey="(record) => record.id"
          :columns="innerColumns"
          :data-source="innerData[index].innerData"
          :pagination="false"
        >
        </a-table>
      </s-table>
      <!-- 退库 -->
      <recallModal :isOpenModal="showModal" :currentData="currentData" @close="showModal=false" @refresh="$refs.table.refresh(true)"></recallModal>
    </a-spin>
  </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 { toThousands } from '@/libs/tools.js'
import shelfList from '@/views/common/shelfList'
import { shelfRecallList, shelfRecallDetailList, shelfRecallCancel, shelfRecallStateCount, shelfRecallDelete } 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: [],
      expandedRowKeys: [],
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      queryParam: {
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        recallBillNo: '',
        shelfSn: undefined, // 数字货架sn
        bizType: '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 || '--' }, ellipsis: true },
        { title: '状态', dataIndex: 'billStateDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调回总量', dataIndex: 'totalQty', width: '9%', align: 'center', customRender: function (text) { return (text || text == 0) ? toThousands(text) : '--' } },
        { title: '实退总量', dataIndex: 'totalConfirmQty', width: '9%', align: 'center', customRender: function (text) { return (text || text == 0) ? toThousands(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 || '--' }, ellipsis: true },
        { title: '调回数量', dataIndex: 'qty', width: '15%', align: 'center', customRender: function (text) { return (text || text == 0) ? toThousands(text) : '--' } },
        { title: '实退数量', dataIndex: 'confirmQty', width: '15%', align: 'center', customRender: function (text) { return (text || text == 0) ? toThousands(text) : '--' } },
        { title: '单位', dataIndex: 'product.unit', width: '15%', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      innerData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        this.expandedRowKeys = []
        parameter.billState = this.queryParam.bizType == 'ALL' ? '' : this.queryParam.bizType
        const params = Object.assign(parameter, this.queryParam)
        delete params.index
        delete params.tableId
        delete params.bizType
        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: {
    // 时间改变
    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.expandedRowKeys = []
      setTimeout(() => {
        this.queryParam.bizType = key
        this.$refs.table.refresh(true)
      }, 100)
    },
    // 获取各类型下的数量
    getSumByType () {
      const params = JSON.parse(JSON.stringify(this.queryParam))
      params.billState = ''
      delete params.bizType
      shelfRecallStateCount(params).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.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(true)
        }
      })
    },
    // 点击行或图标触发接口
    expandFun (expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        this.getinnerData(record) // 获取表格内部数据
      } else {
        const i = this.expandedRowKeys.findIndex(item => item == record.id)
        this.expandedRowKeys.splice(i, 1)
      }
    },
    // 获取子表格数据
    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.resetData()
      this.getSumByType()
    },
    resetData () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam = {
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        recallBillNo: '', // 调回单号
        shelfSn: undefined, // 数字货架sn
        bizType: 'ALL'
      }
    },
    // 退库
    handleRecall (row) {
      this.showModal = true
      this.currentData = row
    },
    // 取消掉回单
    handleCancel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定取消调回单吗？',
        centered: true,
        onOk: () => {
          _this.spinning = true
          shelfRecallCancel({ recallBillSn: row.recallBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.spinning = false
              _this.$refs.table.refresh()
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 删除
    handleDelete (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认删除调回单吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          shelfRecallDelete({ recallBillSn: row.recallBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 250
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.getSumByType()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetData()
    }
  },
  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.resetData()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .accountManagementList-wrap{
    width:100%;
    .inner-table{
      background-color: #fff;
      border-bottom: 1px solid #eee;
      .ant-table{
         margin: 10px 100px;
         border-bottom: 1px solid #eee;
      }
    }
    .replenishmentManagementList-tabs.ant-tabs.ant-tabs-card .ant-tabs-bar{
      margin: 0 0 10px 0!important;
    }
    .replenishmentManagementList-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-nav-container{
      height: 30px!important;
    }
    .replenishmentManagementList-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active{
      height: 30px!important;
    }
    .replenishmentManagementList-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab{
      line-height: 26px!important;
      height: 30px!important;
    }
  }
</style>
