<template>
  <div class="supervisionDiskCheck-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" @back="handleBack" class="supervisionDiskCheck-cont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="supervisionDiskCheck-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="supervisionDiskCheck-print-btn"
            :disabled="list.length==0"
            :loading="spinningPrint"
            v-if="$hasPermissions('B_supervisionDiskPrint')"
            @click="handlePdPrint">监盘打印</a-button>
        </template></a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="supervisionDiskCheck-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="supervisionDiskCheck-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.checkSuperviseQty || productTotal.checkSuperviseQty==0) ? productTotal.checkSuperviseQty : '--' }}</strong>，
                监盘盈亏数量：<strong :style="{ color: productTotal && productTotal.profitLossQty>0?'red':productTotal && productTotal.profitLossQty<0?'green':'' }">{{ 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="supervisionDiskCheck-refresh">查询</a-button>
                      <a-button style="margin-left: 5px" @click="resetSearchForm" id="supervisionDiskCheck-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="checkSuperviseQty" slot-scope="text, record">
            <a-input-number
              size="small"
              id="supervisionDiskCheck-checkSuperviseQty"
              v-model="record.checkSuperviseQty"
              :precision="0"
              :min="0"
              :max="99999999"
              placeholder="请输入"
              v-if="record.type=='superior'"
              @blur="e => checkSuperviseQtyBlur(e.target.value, record)"
              class="input-number"
              style="width: 100%;text-align: center;" />
            <span v-else>{{ record.checkSuperviseQty }}</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="default"
        id="supervisionDiskCheck-check-btn"
        size="large"
        class="button-primary"
        :disabled="spinning"
        @click="handleCheck"
        style="padding: 0 50px;">重新盘点</a-button>
      <a-button
        type="primary"
        id="supervisionDiskCheck-submit-btn"
        size="large"
        class="button-primary"
        :disabled="spinning"
        @click="handleSubmit"
        style="padding: 0 60px;margin-left: 15px">提交监盘</a-button>
    </div>
    <!-- 盘点打印确认 -->
    <print-modal :openModal="visiblePrint" nowType="CHECK_WAREHOUSE_SUPERVISE" :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 '../makeInventory/printModal.vue'
import { printFun } from '@/libs/JGPrint.js'
import { checkWarehouseDetail, checkWarehouseDetailList, checkWarehouseDetailCount, checkWarehouseDetailPrint, checkWarehousePrintCheck, checkWarehouseDetailSave, checkWarehouseSupervise, checkWarehouseReCheck } from '@/api/checkWarehouse'
export default {
  name: 'SupervisionDiskCheck',
  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', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '监盘数量', dataIndex: 'checkSuperviseQty', width: '8%', scopedSlots: { customRender: 'checkSuperviseQty' }, 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/supervisionDisk/list', query: { closeLastOldTab: true, isRefresh: true } })
    },
    // 重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.getList(1)
    },
    // 盘点数量  blur
    checkSuperviseQtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.checkSuperviseQtyBackups) {
        this.handleEdit(record)
      }
    },
    //  编辑
    handleEdit (row) {
      const params = {
        checkWarehouseSn: this.$route.params.sn,
        productSn: row.productSn,
        reCheckSuperviseQty: row.checkSuperviseQty,
        stockQty: row.stockQty
      }
      // 清空数量时,值应保持未清空前的值，因数量不可为空
      if (!(row.checkSuperviseQty || row.checkSuperviseQty == 0)) {
        row.checkSuperviseQty = row.checkSuperviseQtyBackups
        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
          checkWarehouseSupervise({ 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
            }
          })
        }
      })
    },
    // 重新盘点
    handleCheck () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要重新盘点吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          checkWarehouseReCheck({ 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].checkSuperviseQtyBackups = data.list[i].checkSuperviseQty
            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_SUPERVISE' }).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: true, ...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">
  .supervisionDiskCheck-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .supervisionDiskCheck-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>
