<template>
  <div class="bulkWarehousingOrderEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 内容 -->
      <a-page-header :ghost="false" :backIcon="false" class="bulkWarehousingOrderEdit-cont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="bulkWarehousingOrderEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">单号：{{ basicInfoData&&basicInfoData.sparePartsNo }}</span>
          <span style="margin: 0 10px;color: #666;">供应商：{{ basicInfoData&&basicInfoData.supplierName }}</span>
          <a-button type="link" size="small" class="button-default" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="bulkWarehousingOrderEdit-cont" v-show="showDetail">
        <div v-if="basicInfoData" ref="detailBar">
          <a-descriptions :column="2">
            <a-descriptions-item label="入库单号">{{ (basicInfoData&&basicInfoData.sparePartsNo) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="供应商">{{ (basicInfoData&&basicInfoData.supplierName) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="入库类型">{{ (basicInfoData&&basicInfoData.sparePartsTypeDictValue) || '--' }}</a-descriptions-item>
            <a-descriptions-item label="入库仓库">{{ (basicInfoData&&basicInfoData.warehouseName) || '--' }}</a-descriptions-item>
          </a-descriptions>
        </div>
      </a-card>
      <a-card size="small" :bordered="false" class="bulkWarehousingOrderEdit-cont">
        <div ref="toolsBar">
          <!-- 筛选条件 -->
          <div 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="产品编码" prop="productCode">
                    <a-input id="allocateBillEdit-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="allocateBillEdit-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                  <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="bulkWarehousingOrderEdit-refresh">查询</a-button>
                  <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="bulkWarehousingOrderEdit-reset">重置</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- 操作按钮 -->
          <div class="table-operator" style="display: flex;align-items:center;">
            <div>
              <a-button id="bulkWarehousingOrderEdit-add" type="primary" class="button-primary" @click="handleEdit()">新增产品</a-button>
              <a-button id="bulkWarehousingOrderEdit-import" type="default" class="button-primary" @click="openGuideModal=true">导入产品</a-button>
            </div>
            <!-- 总计 -->
            <a-alert type="info" v-if="productTotal">
              <div slot="message">
                入库数量 <strong>{{ (productTotal&&(productTotal.productTotalQty || productTotal.productTotalQty==0)) ? productTotal.productTotalQty : '--' }}</strong> ，
                <span v-if="$hasPermissions('B_sparePartsEdit_costPrice')">
                  入库金额 <strong>{{ (productTotal&&(productTotal.productTotalCost || productTotal.productTotalCost==0)) ? toThousands(productTotal.productTotalCost) : '--' }}</strong>
                </span>
              </div>
            </a-alert>
          </div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          :style="{ height: tableHeight+70+'px' }"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              @click="handleEdit(record)"
              class="button-info"
              id="bulkWarehousingOrderList-edit-btn">编辑</a-button>
            <a-button
              size="small"
              type="link"
              @click="handleDel(record)"
              class="button-error"
              id="bulkWarehousingOrderList-del-btn">删除</a-button>
          </template>

          <template slot="productName" slot-scope="text, record">
            {{ record.productName }}
            <a-tag color="red" v-if="record.giftFlag==1">赠品</a-tag>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="bulkWarehousingOrderEdit-submit"
        :disabled="spinning"
        size="large"
        class="button-primary"
        @click="handleBack"
        style="padding: 0 60px;">保存</a-button>
    </div>
    <!-- 新增产品 -->
    <spare-parts-product-modal :openModal="openModal" :itemSn="itemSn" :nowData="basicInfoData" @ok="handleAddModal" @close="closeModal" />
    <!-- 导入产品 -->
    <importGuideModal :openModal="openGuideModal" :params="{sparePartsSn: $route.params.sn}" @close="openGuideModal=false" @ok="hanldeOk" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { getOperationalPrecision } from '@/libs/tools.js'
import sparePartsProductModal from './productModal.vue'
import ImportGuideModal from './importGuideModal.vue'
import { sparePartsDetailList, sparePartsPageCount, sparePartsDeleteDetail, sparePartsDetailBatchInsert, queryDetailCount } from '@/api/spareParts'
export default {
  name: 'BulkWarehousingOrderEdit',
  mixins: [commonMixin],
  components: { STable, VSelect, sparePartsProductModal, ImportGuideModal },
  data () {
    return {
      spinning: false,
      disabled: false,
      showDetail: false,
      queryParam: {
        productCode: '',
        productName: ''
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return sparePartsDetailList(Object.assign(parameter, this.queryParam, { sparePartsSn: 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
              // 小计  由于数据库内小数位数为4位，页面则需显示2位。因此会做小数运算精度处理
              data.list[i].subtotal = getOperationalPrecision(data.list[i].productCost || 0, data.list[i].productQty)
            }
            this.getBasicInfoData()
            this.getDetailCount(Object.assign(parameter, { sparePartsSn: this.$route.params.sn }))
          }
          return data
        })
      },
      openModal: false, // 选择基本信息弹框是否显示
      basicInfoData: null, //  基础信息
      productTotal: null, //  合计
      itemSn: '',
      openGuideModal: false, //  导入产品引导
      tableHeight: 0
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '20%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品名称', scopedSlots: { customRender: 'productName' }, width: '25%', align: 'left' },
        { title: '单位', dataIndex: 'unit', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '入库数量', dataIndex: 'productQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.$hasPermissions('B_sparePartsEdit_costPrice')) { //  成本价权限
        arr.splice(5, 0, { title: '入库单价', dataIndex: 'productCost', width: '10%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(6, 0, { title: '小计', dataIndex: 'subtotal', width: '10%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  watch: {
    showDetail (newValue, oldValue) {
      this.setTableH()
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    //  添加/编辑
    handleEdit (row) {
      this.itemSn = (row && row.sparePartsDetailSn) ? row.sparePartsDetailSn : null
      this.openModal = true
    },
    setTableH () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        const toolsBarH = this.$refs.toolsBar.offsetHeight
        this.tableHeight = window.innerHeight - toolsBarH - 282
        if (this.showDetail) {
          this.tableHeight = this.tableHeight - this.$refs.detailBar.offsetHeight - 30
        }
      })
    },
    // 关闭
    closeModal () {
      this.itemSn = ''
      this.openModal = false
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          sparePartsDeleteDetail({ sn: row.sparePartsDetailSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh(true)
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.$refs.table.refresh(true)
    },
    // 导入产品
    hanldeOk (obj) {
      this.spinning = true
      sparePartsDetailBatchInsert(obj).then(res => {
        if (res.status == 200) {
          this.$refs.table.refresh(true)
        }
        this.spinning = false
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/purchasingManagement/bulkWarehousingOrder/list', query: { closeLastOldTab: true } })
    },
    // 获取统计数据
    getDetailCount (params) {
      sparePartsPageCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    // 获取基础信息数据
    getBasicInfoData () {
      queryDetailCount({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data
        } else {
          this.basicInfoData = null
        }
      })
    },
    handleAddModal () {
      this.openModal = false
      this.$refs.table.refresh(true)
    },
    pageInit () {
      this.productTotal = null
      this.openModal = false
      this.$refs.table.refresh(true)
      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" scoped>
  .bulkWarehousingOrderEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    .bulkWarehousingOrderEdit-cont{
      margin-bottom: 6px;
      .table-operator{
        border: 0;
        padding-top: 0;
      }
    }
  }
</style>
