<template>
  <div class="inventoryQueryWarehouseDetail-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="inventoryQueryWarehouseDetail-back">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="inventoryQueryWarehouseDetail-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="inventoryQueryWarehouseDetail-cont">
        <!-- 搜索条件 -->
        <div ref="tableSearch" class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
            <a-row :gutter="15">
              <a-col :md="6" :sm="24">
                <a-form-item label="变动类型">
                  <v-select
                    v-model="queryParam.flowType"
                    ref="flowType"
                    id="warehousingAuditList-flowType"
                    code="STOCK_FLOW_TYPE"
                    placeholder="请选择变动类型"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="单据类型">
                  <v-select
                    v-model="queryParam.bizType"
                    ref="bizType"
                    id="inventoryQueryWarehouseDetail-bizType"
                    code="STOCK_FLOW_BIZ_TYPE"
                    placeholder="请选择单据类型"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="仓库">
                  <a-select id="inventoryQueryWarehouseDetail-warehouseSn" placeholder="请选择仓库" allowClear v-model="queryParam.warehouseSn" >
                    <a-select-option v-for="item in warehouseList" :key="item.warehouseSn" :value="item.warehouseSn">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <template v-if="advanced">
                <a-col :md="6" :sm="24">
                  <a-form-item label="单据审核时间">
                    <rangeDate ref="rangeDate" @change="dateChange" />
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="单位名称">
                    <a-input id="inventoryQueryWarehouseDetail-unitName" v-model.trim="queryParam.unitName" allowClear placeholder="请输入单位名称"/>
                  </a-form-item>
                </a-col>
              </template>
              <a-col :md="6" :sm="24">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="inventoryQueryWarehouseDetail-refresh">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="inventoryQueryWarehouseDetail-reset">重置</a-button>
                <a @click="advanced=!advanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 合计 -->
        <a-alert type="info" style="margin-bottom:10px">
          <div class="ftext" slot="message">
            当前库存总数量（个）：<strong>{{ (productTotal&&(productTotal.currentStockQty || productTotal.currentStockQty==0)) ? productTotal.currentStockQty : '--' }}</strong>；
            当前库存总成本(￥)：<strong>{{ (productTotal&&(productTotal.currentStockCost || productTotal.currentStockCost==0)) ? productTotal.currentStockCost : '--' }}</strong>。
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 数量 -->
          <template slot="qty" slot-scope="text, record">
            <p :class="record.flowType=='PUT' ? 'green':'red'" style="margin: 0;">
              <span v-if="record.qty!=0">{{ record.flowType=='PUT' ? '+':'-' }}</span>
              {{ record.qty }}
            </p>
          </template>
        </s-table>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { stockFlowList } from '@/api/stockFlow'
import { stockByProductSn } from '@/api/stock'
import { warehouseAllList } from '@/api/warehouse'
export default {
  name: 'WarehouseDetail',
  components: { STable, VSelect, rangeDate },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: '',
        endDate: '',
        bizType: undefined,
        flowType: undefined,
        unitName: '',
        warehouseSn: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'product.code', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'product.name', width: '12%', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'product.origCode', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '批次号', dataIndex: 'stockBatchNo', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据类型', dataIndex: 'bizTypeDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据审核时间', dataIndex: 'auditTime', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位名称', dataIndex: 'unitName', width: '9%', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '仓库', dataIndex: 'warehouseName', width: '9%', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '9%', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '数量', scopedSlots: { customRender: 'qty' }, width: '5%', align: 'center' },
        { title: '总成本', dataIndex: 'totalCost', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总售价', dataIndex: 'totalPrice', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam, { productSn: this.$route.params.sn })
        return stockFlowList(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
              if (data.list[i].flowType == 'PUT') {
                data.list[i].qty = data.list[i].putQty
              } else if (data.list[i].flowType == 'OUT') {
                data.list[i].qty = data.list[i].outQty
              }
            }
            this.disabled = false
            this.getTotal(params)
          }
          this.spinning = false
          return data
        })
      },
      warehouseList: [], //  仓库  下拉数据
      productTotal: null //  合计
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 合计
    getTotal (param) {
      stockByProductSn({ productSn: this.$route.params.sn }).then(res => {
        if (res.status == 200 && res.data) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  重置
    resetSearchForm () {
      if (this.advanced) {
        this.$refs.rangeDate.resetDate()
      }
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.bizType = undefined
      this.queryParam.flowType = undefined
      this.queryParam.unitName = ''
      this.queryParam.warehouseSn = undefined
      this.$refs.table.refresh(true)
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/inventoryManagement/inventoryQuery/list' })
    },
    // 仓库下拉数据
    getWarehouseList (type) {
      warehouseAllList({}).then(res => {
        if (res.status == 200) {
          this.warehouseList = res.data
        } else {
          this.warehouseList = []
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.getWarehouseList()
      this.resetSearchForm()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 298
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .inventoryQueryWarehouseDetail-wrap{
    .inventoryQueryWarehouseDetail-back, .inventoryQueryWarehouseDetail-cont{
      margin-bottom: 10px;
    }
    .green{
      color: #19be6b;
    }
    .red{
      color: #ed1c24;
    }
  }
</style>
