<template>
  <div class="makeInventoryCheck-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" @back="handleBack" class="makeInventoryCheck-cont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="makeInventoryCheck-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span class="billno">单号：{{ detail&&detail.checkWarehouseNo }}</span>
          <a-button size="small" type="link" class="button-default" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra">
          <a-button
            key="1"
            type="primary"
            class="button-info"
            id="makeInventoryCheck-print-btn"
            :disabled="list.length==0"
            :loading="spinningPrint"
            v-if="$hasPermissions('B_inventoryMakeInventoryPrint')"
            @click="handlePdPrint">盘点打印</a-button>
        </template></a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="makeInventoryCheck-cont" v-show="showDetail">
         <a-descriptions :column="3">
           <a-descriptions-item label="创建人">{{ (detail&&detail.creatorName) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="创建时间">{{ (detail&&detail.createDate) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="盘点类型">{{ (detail&&detail.checkTypeDictValue) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="盘点状态">{{ (detail&&detail.checkStateDictValue) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="仓库">{{ (detail&&detail.warehouseName) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="盘点人">{{ (detail&&detail.checkPersonName) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="盘点时间">{{ (detail&&detail.checkTime) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="监盘状态">{{ (detail&&detail.checkSuperviseStateDictValue) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="监盘人">{{ (detail&&detail.checkSupervisePersonName) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="监盘时间">{{ (detail&&detail.checkSuperviseTime) || '--' }}</a-descriptions-item>
           <a-descriptions-item label="财务确认时间">{{ (detail&&detail.financeAuditTime) || '--' }}</a-descriptions-item>
         </a-descriptions>
      </a-card>
      <!-- 产品详情 -->
      <a-card size="small" :bordered="false" class="makeInventoryCheck-cont">
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom:10px">
          <div slot="message">
            <div style="display: flex;justify-content: space-between;align-items: center;">
              <div>
                库存数量：<strong>{{ productTotal && (productTotal.stockQty || productTotal.stockQty==0) ? productTotal.stockQty : '--' }}</strong>，
                盘点数量：<strong>{{ productTotal && (productTotal.checkQty || productTotal.checkQty==0) ? productTotal.checkQty : '--' }}</strong>，
                盘点盈亏数量：<strong>{{ productTotal && (productTotal.profitLossQty || productTotal.profitLossQty==0) ? productTotal.profitLossQty : '--' }}</strong>
              </div>
              <div>
                <span style="color: red;display: inline-block;margin-right: 8px;">红色代表盘盈</span>
                <span style="color: green;">绿色代表盘亏</span>
              </div>
            </div>
          </div></a-alert>
        <!-- 搜索条件 -->
        <div class="table-page-search-wrapper">
          <a-row :gutter="15">
            <a-col :span="18">
              <a-form-model :model="queryParam" layout="inline" @keyup.enter.native="getList(1)" >
                <a-row :gutter="15">
                  <a-col :md="8" :sm="24">
                    <a-form-model-item label="产品编码">
                      <a-input v-model.trim="queryParam.productCode" allowClear placeholder="输入产品编码" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-button type="primary" @click="getList(1)" :disabled="disabled" id="makeInventoryCheck-refresh">查询</a-button>
                      <a-button style="margin-left: 5px" @click="resetSearchForm" id="makeInventoryCheck-reset">重置</a-button>
                  </a-col>
                </a-row>
              </a-form-model>
            </a-col>
            <a-col :span="6">
              <div style="float:right;overflow: hidden;margin-top:6px;">
                <a-checkbox v-model="foldState" @change="foldStateChange"><span style="display: inline-block;margin-top: 1px;">折叠列表</span></a-checkbox>
              </div>
            </a-col>
          </a-row>
        </div>
        <!-- 列表 -->
        <a-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id + record.type"
          :columns="columns"
          :pagination="false"
          :data-source="list"
          :loading="loading"
          @expand="handleExpand"
          :expandedRowKeys="expandedRowKeys"
          bordered>
          <!-- 数量 -->
          <template slot="checkQty" slot-scope="text, record">
            <a-input-number
              size="small"
              id="makeInventoryCheck-checkQty"
              v-model="record.checkQty"
              :precision="0"
              :min="0"
              :max="99999999"
              placeholder="请输入"
              v-if="record.type=='superior'"
              @blur="e => checkQtyBlur(e.target.value, record)"
              class="input-number"
              style="width: 100%;text-align: center;" />
            <span v-else>{{ record.checkQty }}</span>
          </template>
          <!-- 盈亏数量 -->
          <template slot="profitLossQty" slot-scope="text, record">
            <span v-if="record.type=='superior'" :style="{ color: record.profitLossQty>0?'red':record.profitLossQty<0?'green':'', fontWeight: record.profitLossQty!=0?'bold':'' }">
              {{ record.profitLossQty>0?'盘盈':record.profitLossQty<0?'盘亏':'' }}
              {{ (record.profitLossQty || record.profitLossQty==0) ? Math.abs(record.profitLossQty) : '--' }}
            </span>
            <span v-else></span>
          </template>
        </a-table>
        <!-- 分页 -->
        <tablePagination
          ref="tablePagination"
          :total="paginationProps.total"
          :current="paginationProps.current"
          :pageSize="paginationProps.pageSize"
          @changePageSize="changePageSize"
          @changePage="changePage" />
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="makeInventoryCheck-submit-btn"
        size="large"
        class="button-primary"
        :disabled="spinning"
        @click="handleSubmit"
        style="padding: 0 60px;">提交盘点</a-button>
    </div>
    <!-- 盘点打印确认 -->
    <print-modal :openModal="visiblePrint" nowType="CHECK_WAREHOUSE" :itemData="detail" @ok="handlePrint" @close="visiblePrint=false" />
    <div id="print"></div>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import tablePagination from '@/views/common/tablePagination.vue'
import printModal from './printModal.vue'
import { printFun } from '@/libs/JGPrint.js'
import { checkWarehouseDetail, checkWarehouseDetailList, checkWarehouseDetailCount, checkWarehouseDetailPrint, checkWarehousePrintCheck, checkWarehouseDetailSave, checkWarehouseCheck } from '@/api/checkWarehouse'
export default {
  name: 'MakeInventoryCheck',
  mixins: [commonMixin],
  components: { STable, VSelect, tablePagination, printModal },
  data () {
    return {
      spinning: false,
      disabled: false,
      loading: false,
      showDetail: false,
      queryParam: {
        productCode: ''
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '6%', align: 'center' },
        { title: '产品名称', dataIndex: 'productName', width: '16%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'productUnit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '仓库', dataIndex: 'warehouseName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '11%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '入库时间', dataIndex: 'lastStockTime', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '批次', dataIndex: 'stockBatchNo', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'productCode', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '库存数量', dataIndex: 'stockQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '盘点数量', dataIndex: 'checkQty', scopedSlots: { customRender: 'checkQty' }, width: '6%', align: 'center' },
        { title: '盈亏数量', dataIndex: 'profitLossQty', scopedSlots: { customRender: 'profitLossQty' }, width: '6%', align: 'center' }
      ],
      list: [],
      paginationProps: {
        total: 0, //  分页总条数
        current: 1,
        pageSize: 20
      },
      expandedRowKeys: [],
      detail: null, //  详情数据
      foldState: false, //  是否折叠列表
      productTotal: null, //  合计
      spinningPrint: false,
      visiblePrint: false
    }
  },
  methods: {
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/inventoryManagement/makeInventory/list', query: { closeLastOldTab: true, isRefresh: true } })
    },
    // 重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.getList(1)
    },
    // 盘点数量  blur
    checkQtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.checkQtyBackups) {
        this.handleEdit(record)
      }
    },
    //  编辑
    handleEdit (row) {
      const params = {
        checkWarehouseSn: this.$route.params.sn,
        productSn: row.productSn,
        reCheckQty: row.checkQty,
        stockQty: row.stockQty
      }
      // 清空数量时,值应保持未清空前的值，因数量不可为空
      if (!(row.checkQty || row.checkQty == 0)) {
        row.checkQty = row.checkQtyBackups
        return
      }
      this.spinning = true
      checkWarehouseDetailSave(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.getList()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 提交盘点
    handleSubmit () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认提交盘点吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          checkWarehouseCheck({ checkWarehouseSn: _this.$route.params.sn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.handleBack()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 获取列表数据
    getList (pageNo) {
      this.disabled = true
      this.paginationProps.current = pageNo || this.paginationProps.current
      const params = {
        pageNo: this.paginationProps.current,
        pageSize: this.paginationProps.pageSize,
        checkWarehouseSn: this.$route.params.sn,
        productCode: this.queryParam.productCode
      }
      this.loading = true
      checkWarehouseDetailList(params).then(res => {
        this.loading = false
        if (res.status == 200) {
          this.getCount(params)
          const data = res.data
          this.paginationProps.total = Number(res.data.count) || 0
          this.paginationProps.current = data.pageNo
          const no = (data.pageNo - 1) * data.pageSize
          this.expandedRowKeys = []
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
            data.list[i].checkQtyBackups = data.list[i].checkQty
            if (!this.foldState) {
              this.expandedRowKeys.push(data.list[i].id + data.list[i].type)
            }
          }
          this.list = data.list
          this.disabled = false
        } else {
          this.paginationProps.total = 0
          this.paginationProps.current = 1
          this.paginationProps.pageSize = 20
          this.list = []
        }
      })
    },
    getCount (params) {
      checkWarehouseDetailCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  分页  一页多少条change
    changePageSize (current, pageSize) {
      this.paginationProps.current = current
      this.paginationProps.pageSize = pageSize
      this.getList()
    },
    //  分页 页码change
    changePage (current) {
      this.paginationProps.current = current
      this.getList()
    },
    //  详情
    getDetail () {
      checkWarehouseDetail({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detail = res.data
        } else {
          this.detail = null
        }
      })
    },
    // 展开收起
    handleExpand (expanded, record) {
      if (record.type == 'superior') { // 只处理父级
        if (expanded) {
          this.expandedRowKeys.push(record.id + record.type)
        } else {
          if (this.expandedRowKeys.length > 0) {
            const expandedRowKeys = this.expandedRowKeys.filter(RowKey => RowKey !== (record.id + record.type))
            this.expandedRowKeys = expandedRowKeys
          }
        }
      }
    },
    // 折叠列表
    foldStateChange (e) {
      if (e.target.checked) {
        this.expandedRowKeys = []
      } else {
        this.expandedRowKeys = []
        this.list.map(item => {
          this.expandedRowKeys.push(item.id + item.type)
        })
      }
    },
    // 盘点打印
    handlePdPrint () {
      this.spinning = true
      checkWarehousePrintCheck({ checkWarehouseSn: this.$route.params.sn, type: 'CHECK_WAREHOUSE' }).then(res => {
        this.spinning = false
        if (res.status == 200) {
          if (res.data && res.data == 0) { // 无产品
            this.$info({
              title: '提示',
              content: '此盘点单没有产品，无法打印',
              centered: true
            })
          } else { // 有产品
            this.detail.printContent = '打印范围 —— 所有盘点产品（批次合并）'
            this.visiblePrint = true
          }
        }
      })
    },
    // 打印预览/快捷打印
    handlePrint (objs, type) {
      const _this = this
      _this.spinningPrint = true
      const params = { checkWarehouseSn: this.$route.params.sn, superviseFlag: false, ...objs }
      printFun(checkWarehouseDetailPrint, params, type, '盘点单', () => { _this.spinningPrint = false })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.resetSearchForm()
      this.getDetail()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.resetSearchForm()
      this.getDetail()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .makeInventoryCheck-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .makeInventoryCheck-cont{
      margin-bottom: 6px;
      .billno{
        font-size: 16px;
        font-weight: bold;
        margin: 0 15px;
      }
      .state-c{
        color: #ed1c24;
        font-size: 13px;
        font-weight: bold;
      }
    }
    .input-number{
      .ant-input-number-input{
        text-align: center;
      }
    }
  }
</style>
