<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="单据审核时间">
                  <rangeDate ref="rangeDate" @change="dateChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="关联单号">
                  <a-input id="inventoryQueryWarehouseDetail-bizNo" v-model.trim="queryParam.bizNo" allowClear placeholder="请输入关联单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="下推单号">
                  <a-input id="inventoryQueryWarehouseDetail-bizSubNo" v-model.trim="queryParam.bizSubNo" allowClear placeholder="请输入下推单号"/>
                </a-form-item>
              </a-col>
              <template v-if="advanced">
                <a-col :md="6" :sm="24">
                  <a-form-item label="变动类型">
                    <v-select
                      v-model="queryParam.flowType"
                      ref="flowType"
                      id="inventoryQueryWarehouseDetail-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-input id="inventoryQueryWarehouseDetail-unitName" v-model.trim="queryParam.unitName" allowClear placeholder="请输入单位名称"/>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="出入库状态">
                    <v-select
                      v-model="queryParam.state"
                      ref="state"
                      id="inventoryQueryWarehouseDetail-state"
                      code="STOCK_FLOW_STATE"
                      placeholder="请选择出入库状态"
                      allowClear></v-select>
                  </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: 5px" @click="resetSearchForm" :disabled="disabled" id="inventoryQueryWarehouseDetail-reset">重置</a-button>
                <a-button
                  type="primary"
                  style="margin-left: 5px"
                  class="button-warning"
                  v-if="$hasPermissions('B_inventoryQuery_rkDetail_export')"
                  @click="handleExcel"
                  :disabled="disabled"
                  :loading="exportLoading"
                  id="inventoryQueryList-export">导出</a-button>
                <a @click="advanced=!advanced" style="margin-left: 5px" id="inventoryQueryList-advanced">
                  {{ 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.totalQty || productTotal.totalQty==0)) ? productTotal.totalQty : '--' }}个</strong>；
            入库总数量：<strong>{{ (productTotal&&(productTotal.totalPutQty || productTotal.totalPutQty==0)) ? productTotal.totalPutQty : '--' }}个</strong>；
            出库总数量：<strong>{{ (productTotal&&(productTotal.totalOutQty || productTotal.totalOutQty==0)) ? productTotal.totalOutQty : '--' }}个</strong>；
            <span v-if="$hasPermissions('B_inventoryQuery_rkDetail_costPrice')">当前库存总成本：<strong>{{ (productTotal&&(productTotal.totalCost || productTotal.totalCost==0)) ? toThousands(productTotal.totalCost) : '--' }}</strong>。</span>
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'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>
          <!-- 总售价 -->
          <template slot="totalAmount" slot-scope="text, record">
            <span v-if="record.bizType!='SPARE_PARTS_RETURN'"> {{ toThousands(record.totalPrice) }}</span>
            <span v-else>--</span>
          </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 { hdExportExcel } from '@/libs/exportExcel'
import { stockFlowCount, stockFlowList, stockFlowExport } from '@/api/stock'
export default {
  name: 'InventoryQueryWarehouseDetail',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: '', // 开始时间
        endDate: '', // 结束时间
        bizType: undefined, // 单据类型
        flowType: undefined, // 变动类型
        unitName: '', // 单位
        bizNo: '', // 关联单号
        bizSubNo: '', // 下推单号
        warehouseSn: undefined, // 仓库sn
        state: undefined // 单据状态
      },
      disabled: false, //  查询、重置按钮是否可操作
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam, { productSn: this.$route.params.sn, warehouseSn: this.$route.params.warehouseSn })
        return stockFlowList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            this.getTotal(params)
            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.spinning = false
          return data
        })
      },
      exportLoading: false, // 导出按钮loading
      productTotal: null //  合计
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '6%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '10%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '6%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '批次号', dataIndex: 'stockBatchNo', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据类型', dataIndex: 'bizTypeDictValue', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '关联单号', dataIndex: 'bizNo', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '下推单号', dataIndex: 'bizSubNo', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据审核时间', dataIndex: 'auditTime', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位名称', dataIndex: 'unitName', width: '10%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓库', dataIndex: 'warehouseName', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '数量', scopedSlots: { customRender: 'qty' }, width: '5%', align: 'center' },
        // { title: '总成本', dataIndex: 'totalCost', width: '4%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '总售价', dataIndex: 'totalPrice', width: '4%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '出入库状态', dataIndex: 'stateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      if (this.$hasPermissions('B_inventoryQuery_rkDetail_costPrice')) { // 成本价权限
        arr.splice(13, 0, { title: '总成本', dataIndex: 'totalCost', width: '5%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('B_inventoryQuery_rkDetail_salesPrice')) { // 售价权限
        arr.splice(14, 0, { title: '总售价', width: '5%', align: 'right', scopedSlots: { customRender: 'totalAmount' } })
      }
      return arr
    }
  },
  methods: {
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 合计
    getTotal (param) {
      stockFlowCount(param).then(res => {
        if (res.status == 200 && res.data) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.bizType = undefined
      this.queryParam.flowType = undefined
      this.queryParam.unitName = ''
      this.queryParam.bizSubNo = ''
      this.queryParam.bizNo = ''
      this.queryParam.warehouseSn = undefined
      this.queryParam.state = undefined
      this.$refs.table.refresh(true)
    },
    // 导出
    handleExcel () {
      const _this = this
      this.$store.state.app.curActionPermission = 'B_inventoryQuery_rkDetail_export'
      const params = Object.assign(this.queryParam, { productSn: this.$route.params.sn, warehouseSn: this.$route.params.warehouseSn })
      this.exportLoading = true
      this.spinning = true
      hdExportExcel(stockFlowExport, params, '出入库明细', function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.$store.state.app.curActionPermission = ''
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ name: 'inventoryQueryList', query: { closeLastOldTab: true } })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 268
    }
  },
  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.resetSearchForm()
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.resetSearchForm()
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

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