<template>
  <div class="inventoryCheckMakeInventoryList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="inventoryCheckMakeInventoryList-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="inventoryCheckMakeInventoryList-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span class="billno">单号：{{ basicInfoData&&basicInfoData.checkWarehouseNo }}</span>
          <a-tag color="blue">{{ basicInfoData&&basicInfoData.stateDictValue }}</a-tag>
        </template>
        <template slot="extra" v-if="$hasPermissions('B_inventoryCheckingPrint')">
          <a-radio-group v-model="printerType">
            <a-radio value="NEEDLE">针式</a-radio>
            <a-radio value="INK">喷墨</a-radio>
          </a-radio-group>
          <a-button
            type="primary"
            class="button-error"
            id="inventoryCheckingDetail-pd-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('pddy')">盘点打印</a-button>
          <a-button
            type="primary"
            class="button-info"
            id="inventoryCheckingDetail-sh-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('shdy')">审核打印</a-button>
          <a-button
            type="primary"
            class="button-warning"
            id="inventoryCheckingDetail-export-btn"
            :disabled="localDataSource.length==0"
            @click="handleExport('export')">导出Excel</a-button>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="inventoryCheckMakeInventoryList-cont">
        <a-collapse defaultActiveKey="1">
          <a-collapse-panel key="1" header="基础信息">
            <a-descriptions :column="3">
              <a-descriptions-item label="盘点类型">{{ (basicInfoData&&basicInfoData.checkTypeDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="是否区分仓库" v-if="basicInfoData&&basicInfoData.checkType=='SELECT'">{{ (basicInfoData&&basicInfoData.warehouseFlagDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="盘点仓库" v-if="basicInfoData&&basicInfoData.warehouseFlag=='1'">{{ (basicInfoData&&basicInfoData.warehouseNameList) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="创建人">{{ (basicInfoData&&basicInfoData.creatorName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="创建时间">{{ (basicInfoData&&basicInfoData.createDate) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="审核时间">{{ (basicInfoData&&basicInfoData.checkSuperviseTime) || '--' }}</a-descriptions-item>
            </a-descriptions>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-card size="small" :bordered="false" class="inventoryCheckMakeInventoryList-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.totalCategory || productTotal.totalCategory==0) ? productTotal.totalCategory : '--' }}</strong> ，
                总数量： <strong>{{ productTotal&&(productTotal.stockQty || productTotal.stockQty==0) ? productTotal.stockQty : '--' }}</strong> ，
                总成本： <strong>{{ productTotal&&(productTotal.checkCost || productTotal.checkCost==0) ? '￥'+productTotal.checkCost : '--' }}</strong> ，
                盘盈数量： <strong>{{ productTotal&&(productTotal.checkProfitQty || productTotal.checkProfitQty==0) ? productTotal.checkProfitQty : '--' }}</strong> ，
                盘亏数量： <strong>{{ productTotal&&(productTotal.checkLossQty || productTotal.checkLossQty==0) ? productTotal.checkLossQty : '--' }}</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="19">
              <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="产品编码" prop="productCode">
                      <a-input id="inventoryCheckMakeInventoryList-productCode" v-model.trim="queryParam.productCode" placeholder="请输入" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-form-item label="产品名称" prop="productName">
                      <a-input id="inventoryCheckMakeInventoryList-productName" v-model.trim="queryParam.productName" placeholder="请输入" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-form-item label="产品分类">
                      <ProductType id="inventoryCheckMakeInventoryList-productType" @change="changeProductType" v-model="productType"></ProductType>
                    </a-form-item>
                  </a-col>
                  <template v-if="advanced && (basicInfoData&&basicInfoData.warehouseFlag=='1')">
                    <a-col :md="6" :sm="24" v-if="basicInfoData&&basicInfoData.warehouseFlag=='1'">
                      <a-form-item label="仓库">
                        <a-select id="inventoryCheckMakeInventoryList-warehouseSn" allowClear placeholder="请选择仓库" 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>
                  <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                    <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="inventoryCheckMakeInventoryList-refresh">查询</a-button>
                    <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="inventoryCheckMakeInventoryList-reset">重置</a-button>
                    <a @click="advanced=!advanced" style="margin-left: 5px" v-if="basicInfoData&&basicInfoData.warehouseFlag=='1'">
                      {{ advanced ? '收起' : '展开' }}
                      <a-icon :type="advanced ? 'up' : 'down'"/>
                    </a>
                  </a-col>
                </a-row>
              </a-form>
            </a-col>
            <a-col :span="5">
              <div style="float:right;overflow: hidden;">
                <a-button size="small" type="primary" class="button-info" id="inventoryCheckMakeInventoryList-checkZero-btn" @click="handleCheckZero">整单盘零</a-button>
              </div>
            </a-col>
          </a-row>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          bordered>
          <!-- 产品分类 -->
          <template slot="productType" slot-scope="text, record">
            <span v-if="record.productTypeName2 || record.productTypeName3">{{ record.productTypeName2 }} {{ record.productTypeName3 ? '>' : '' }} {{ record.productTypeName3 }}</span>
            <span v-else>--</span>
          </template>
          <!-- 数量 -->
          <template slot="checkQty" slot-scope="text, record">
            <a-input-number
              size="small"
              id="inventoryCheckMakeInventoryList-choose-checkQty"
              v-model="record.checkQty"
              :precision="0"
              :min="0"
              :max="999999"
              placeholder="请输入"
              @blur="e => checkQtyBlur(e.target.value, record)"
              style="width: 100%;" />
          </template>
          <!-- 盈亏数量 -->
          <template slot="checkProfitLossQty" slot-scope="text, record">
            <span :style="{ color: record.checkProfitLossQty>0?'red':record.checkProfitLossQty<0?'green':'', fontWeight: record.checkProfitLossQty!=0?'bold':'' }">{{ (record.checkProfitLossQty || record.checkProfitLossQty==0) ? Math.abs(record.checkProfitLossQty) : '--' }}</span>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="inventoryCheckMakeInventoryList-submit"
        size="large"
        :disabled="spinning"
        class="button-primary"
        @click="handleSubmit"
        style="padding: 0 60px;">盘点完成</a-button>
    </div>
    <!-- 打印导出 -->
    <print-modal :openModal="openPrintModal" :itemData="basicInfoData" :nowType="nowType" @ok="handleOk" @close="openPrintModal=false" />
    <!-- 打印 -->
    <div id="print"></div>
    <!-- 导出选择弹框 -->
    <a-modal
      v-model="exportShow"
      :footer="null"
      :maskClosable="false"
      centered
      title="导出excel"
      @cancle="exportShow=false"
    >
      <div style="line-height: 48px;padding: 0 30px;">
        <div>盘点单号：{{ basicInfoData&&basicInfoData.checkWarehouseNo }}</div>
        <div>盘点类型：{{ (basicInfoData&&basicInfoData.checkTypeDictValue) || '--' }}
          <span v-if="basicInfoData&&basicInfoData.checkType=='SELECT'">({{ (basicInfoData&&basicInfoData.warehouseFlagDictValue) || '--' }})</span>
        </div>
        <div>产品范围：
          <a-radio-group v-model="productScopeFlag">
            <a-radio :value="true">
              所有盘点产品
            </a-radio>
            <a-radio :value="false">
              有盈亏的产品
            </a-radio>
          </a-radio-group>
        </div>
        <div class="btn-cont" style="text-align: center;padding-top: 40px;">
          <a-button id="inventoryChecking-export-save" @click="exportShow=false">取消</a-button>
          <a-button type="primary" id="inventoryChecking-export-back" @click="handlePrint('export')" style="margin-left: 15px;">确定导出</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import ProductType from '@/views/common/productType.js'
import printModal from './printModal.vue'
import { downloadExcel } from '@/libs/JGPrint.js'
import { checkWarehouseDetailList, checkWarehouseDetailCount, checkWarehouseInventory, checkWarehouseDetail, checkWarehouseDetailSave, checkWarehouseCheckZero, checkWarehouseWarehouse, checkWarehouseDetailExport, checkWarehouseDetailPrint } from '@/api/checkWarehouse'
export default {
  name: 'MakeInventory',
  components: { STable, VSelect, ProductType, printModal },
  mixins: [commonMixin],
  props: {},
  data () {
    return {
      spinning: false,
      disabled: false,
      advanced: false,
      exportShow: false,
      queryParam: {
        productName: '',
        productCode: '',
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined,
        warehouseSn: undefined
      },
      basicInfoData: null, // 基础信息
      productTotal: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return checkWarehouseDetailList(Object.assign(parameter, this.queryParam, { checkWarehouseSn: this.$route.params.sn })).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].checkQtyBackups = data.list[i].checkQty
            }
            this.localDataSource = data.list || []
            this.getProduceTotal()
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      productType: [],
      warehouseList: [], //  仓库  下拉数据
      localDataSource: [],
      openPrintModal: false,
      nowType: null,
      printerType: 'NEEDLE', //  打印机类型
      productScopeFlag: true
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '21%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '21%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, width: '14%' },
        { title: '单位', dataIndex: 'productUnit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '库存数量', dataIndex: 'stockQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '盘点数量', scopedSlots: { customRender: 'checkQty' }, width: '8%', align: 'center' },
        { title: '盈亏数量', scopedSlots: { customRender: 'checkProfitLossQty' }, width: '8%', align: 'center' }
      ]
      if (this.basicInfoData && this.basicInfoData.warehouseFlag == '1') {
        arr.splice(4, 0, { title: '仓库', dataIndex: 'warehouseName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      return arr
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.productScopeFlag = true
      this.queryParam.productName = ''
      this.queryParam.productCode = ''
      this.queryParam.warehouseSn = undefined
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productTypeSn2 = undefined
      this.queryParam.productTypeSn3 = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    //  盘点完成
    handleSubmit () {
      const _this = this
      _this.spinning = true
      checkWarehouseInventory({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          setTimeout(() => {
            _this.handleBack()
            _this.spinning = false
          }, 1000)
        } else {
          _this.spinning = false
        }
      })
    },
    // 数量  blur
    checkQtyBlur (val, record) {
      if ((val != record.checkQtyBackups) || (!val && record.checkQtyBackups == 0)) {
        this.handleAdd(record, 'edit')
      }
    },
    //  添加/编辑
    handleAdd (row, isEdit) {
      if (!isEdit && !row.checkQty) {
        this.$message.warning('请输入盘点数量！')
        return
      }
      const params = {
        checkWarehouseSn: this.$route.params.sn,
        id: row.id,
        checkCost: row.checkCost,
        checkQty: row.checkQty,
        productSn: row.productSn,
        productCode: row.productCode,
        productOrigCode: row.productOrigCode || undefined,
        productTypeSn1: row.productTypeSn1,
        productTypeSn2: row.productTypeSn2,
        productTypeSn3: row.productTypeSn3,
        brandSn: row.brandSn,
        stockQty: row.stockQty,
        lastStockTime: row.lastStockTime,
        checkProfitLossCost: row.checkProfitLossCost,
        stockBatchNo: row.stockBatchNo || undefined,
        productProduceDate: row.productProduceDate || undefined,
        productExpiryDate: row.productExpiryDate || undefined,
        warehouseSn: row.warehouseSn || undefined,
        warehouseLocationSn: row.warehouseLocationSn || undefined
      }
      if (isEdit) { // 编辑
        // 清空数量时,值应保持未清空前的值，因数量都不可为空
        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.$refs.table.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 整单盘零
    handleCheckZero () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定要进行 整单盘零 操作吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          checkWarehouseCheckZero({ checkWarehouseSn: _this.$route.params.sn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh(true)
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/inventoryManagement/inventoryChecking/list' })
    },
    // 查询基础信息
    getDetail () {
      checkWarehouseDetail({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200 && res.data) {
          this.basicInfoData = res.data
          this.warehouseList = res.data.warehouseList || []
        } else {
          this.basicInfoData = null
          this.warehouseList = []
        }
      })
    },
    // 已选产品总计查询
    getProduceTotal () {
      checkWarehouseDetailCount(Object.assign(this.queryParam, { checkWarehouseSn: this.$route.params.sn })).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    handleExport () {
      this.exportShow = true
    },
    // 打印导出
    handlePrint (type) {
      if (type == 'export') {
        this.exportShow = false
        this.nowType = type
        this.handleOk()
      } else {
        this.nowType = type
        this.openPrintModal = true
      }
    },
    handleOk (objs) {
      const _this = this
      let params
      let url = checkWarehouseDetailPrint //  打印
      if (this.nowType == 'export') { //  导出
        url = checkWarehouseDetailExport
        params = { checkWarehouseSn: this.$route.params.sn, productScopeFlag: this.productScopeFlag }
      } else { //  打印
        params = JSON.parse(JSON.stringify(objs))
        params.printType = this.printerType
        delete params.type
      }
      _this.spinning = true
      url(params).then(res => {
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          if (this.nowType == 'export' || this.nowType == 'typeExport') {
            downloadExcel(res, '库存盘点')
          } else {
            this.print(res, objs.type)
          }
        }
      })
    },
    print (data, type) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data], { type: 'application/pdf' }))
      document.getElementById('print').innerHTML = '<iframe id="printficm" name="printficm" src="' + url + '" hidden></iframe>'
      if (type == 'preview') { //  预览
        window.open(url)
      } else if (type == 'print') { //  打印
        window.frames['printficm'].focus()
        window.frames['printficm'].print()
      }
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.getDetail()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.getDetail()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .inventoryCheckMakeInventoryList-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    .inventoryCheckMakeInventoryList-cont, .inventoryCheckMakeInventoryList-back{
      margin-bottom: 10px;
    }
    .billno{
      font-size: 16px;
      font-weight: bold;
      margin: 0 15px;
    }
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
  }
</style>
