<template>
  <a-card size="small" :bordered="false" class="bulkWarehousingOrderList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <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="产品编码">
                <a-input id="bulkWarehousingOrderList-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="关联单号">
                <a-input id="bulkWarehousingOrderList-relationNo" v-model.trim="queryParam.relationNo" allowClear placeholder="请输入关联单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="入库单号">
                <a-input id="bulkWarehousingOrderList-sparePartsNo" v-model.trim="queryParam.sparePartsNo" allowClear placeholder="请输入入库单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商户名称">
                <a-input id="bulkWarehousingOrderList-supplierName" v-model.trim="queryParam.supplierName" allowClear placeholder="请输入商户名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="金蝶单号">
                <a-input id="bulkWarehousingOrderList-kingdeeNo" v-model.trim="queryParam.kingdeeNo" allowClear placeholder="请输入金蝶单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="入库类型">
                <v-select
                  v-model="queryParam.sparePartsType"
                  ref="sparePartsType"
                  id="bulkWarehousingOrderList-sparePartsType"
                  code="SPARE_PARTS_TYPE"
                  placeholder="请选择入库类型"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="状态">
                <v-select
                  v-model="queryParam.state"
                  ref="state"
                  id="bulkWarehousingOrderList-state"
                  code="SPARE_PARTS_STATE"
                  placeholder="请选择状态"
                  allowClear
                ></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="bulkWarehousingOrderList-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm()" :disabled="disabled" id="bulkWarehousingOrderList-reset">重置</a-button>
                <a-button
                  style="margin-left: 10px"
                  v-if="$hasPermissions('B_sparePartsExport')"
                  type="primary"
                  class="button-warning"
                  @click="handleExport"
                  :disabled="disabled"
                  :loading="exportLoading"
                >导出明细</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button v-if="$hasPermissions('B_sparePartsNew')" id="bulkWarehousingOrderList-add" type="primary" class="button-error" @click="handleAdd">新增</a-button>
        <a-button
          v-if="$hasPermissions('B_sparePartsBatchAudit')"
          id="bulkWarehousingOrderList-batchAudit"
          type="primary"
          class="button-warning"
          :loading="loading"
          @click="handleBatchAudit"
          style="margin: 0 15px;">批量审核</a-button>
        <span style="margin-left: 8px">
          <template v-if="rowSelectionInfo && rowSelectionInfo.selectedRowKeys.length>0">{{ `已选 ${rowSelectionInfo.selectedRowKeys.length} 项` }}</template>
        </span>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.sparePartsSn"
        rowKeyName="sparePartsSn"
        :row-selection="$hasPermissions('B_sparePartsBatchAudit')?{ columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: record.state != 'WAIT_AUDIT' } }) }:null"
        @rowSelection="rowSelectionFun"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 入库单号 -->
        <template slot="sparePartsNo" slot-scope="text, record">
          <span v-if="$hasPermissions('B_sparePartsDetail')" class="link-bule" @click="handleDetail(record)">{{ record.sparePartsNo }}</span>
          <span v-else>{{ record.sparePartsNo }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_sparePartsAudit')"
            class="button-warning"
            @click="handleAudit(record)"
            id="allocateBillList-examine-btn">审核</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_sparePartsEdit')"
            @click="handleEdit(record)"
            class="button-info"
            id="bulkWarehousingOrderList-edit-btn">编辑</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_sparePartsDel')"
            @click="handleDel(record)"
            class="button-error"
            id="bulkWarehousingOrderList-del-btn">删除</a-button>
          <span v-if="!(record.state == 'WAIT_AUDIT'&&($hasPermissions('B_sparePartsEdit') || $hasPermissions('B_sparePartsDel') || $hasPermissions('B_sparePartsAudit')))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 选择基本信息弹框 -->
    <basic-info-modal v-drag :openModal="openModal" @ok="handleOk" @close="openModal=false" />
    <sparePartsDetailModal v-drag :openModal="openDetailModal" :itemSn="itemSn" @close="closeDetailModal" />
    <!-- 导出提示框 -->
    <reportModal :visible="showExport" @close="showExport=false"></reportModal>
    <!-- 审核不通过弹框 -->
    <auditNoPassModal v-drag ref="auditNoPassModal" :openModal="openAuditNoModal" @close="openAuditNoModal=false" />
    <batchAuditNoModal v-drag ref="batchAuditNoModal" :openModal="openBatchAuditNoModal" @close="openBatchAuditNoModal=false" @ok="hanldeAuditOk" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import basicInfoModal from './basicInfoModal.vue'
import sparePartsDetailModal from './detailModal.vue'
import reportModal from '@/views/common/reportModal.vue'
import auditNoPassModal from './auditNoPassModal.vue'
import batchAuditNoModal from './batchAuditNoModal.vue'
import { hdExportExcel } from '@/libs/exportExcel'
import { sparePartsList, sparePartsDelete, sparePartsAudit, sparePartsAuditVerify, sparePartsDetailExport } from '@/api/spareParts'
export default {
  name: 'BulkWarehousingOrderList',
  mixins: [commonMixin],
  components: { STable, VSelect, basicInfoModal, sparePartsDetailModal, reportModal, auditNoPassModal,batchAuditNoModal },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 基本信息弹框是否显示
      showExport: false,
      exportLoading: false,
      openAuditNoModal: false,
      openBatchAuditNoModal: false,
      tableHeight: 0,
      // 查询参数
      queryParam: {
        productCode: '',
        relationNo: '',
        state: undefined,
        sparePartsType: undefined,
        sparePartsNo: '',
        supplierName: '',
        kingdeeNo: ''
      },
      loading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return sparePartsList(Object.assign(parameter, this.queryParam)).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
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      openDetailModal: false,
      itemSn: null,
      rowSelectionInfo: null
    }
  },
  computed: {
	  columns () {
	    const arr = [
	      { title: '创建时间', dataIndex: 'createDate', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
	      { title: '入库单号', scopedSlots: { customRender: 'sparePartsNo' }, width: '15%', align: 'center' },
	      { title: '商户名称', dataIndex: 'supplierName', align: 'center', width: '15%', customRender: function (text) { return text || '--' }, ellipsis: true },
	      { title: '入库数量', dataIndex: 'productTotalQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
	      // { title: '入库成本', dataIndex: 'productTotalCost', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
	      { title: '入库类型', dataIndex: 'sparePartsTypeDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
	      { title: '关联单号', dataIndex: 'relationNo', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
	      { title: '金蝶单号', dataIndex: 'kingdeeNo', width: '12.5%', align: 'center', customRender: function (text) { return text || '--' } },
	      { title: '状态', dataIndex: 'stateDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
	      { title: '备注', dataIndex: 'remark', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
	      { title: '操作', scopedSlots: { customRender: 'action' }, width: '9%', align: 'center' }
	    ]
	    if (this.$hasPermissions('B_isShowCost')) { //  成本价权限
	      arr.splice(4, 0, { title: '入库成本', dataIndex: 'productTotalCost', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
	    }
	    return arr
	  }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    //  导出
    handleExport () {
      const _this = this
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(sparePartsDetailExport, _this.queryParam, '散件入库明细', function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.showExport = true
      })
    },
    //  新增
    handleAdd () {
      this.openModal = true
    },
    //  基本信息  保存
    handleOk (row) {
      this.$router.push({ path: `/purchasingManagement/bulkWarehousingOrder/add/${row.id}/${row.sparePartsSn}` })
    },
    //  编辑
    handleEdit (row) {
      this.$router.push({ path: `/purchasingManagement/bulkWarehousingOrder/edit/${row.id}/${row.sparePartsSn}` })
    },
    //  详情
    handleDetail (row) {
      if (!this.$hasPermissions('B_sparePartsDetail')) { return }
      this.itemSn = row.sparePartsSn
      this.openDetailModal = true
    },
    // 关闭弹框
    closeDetailModal () {
      this.itemSn = null
      this.openDetailModal = false
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          sparePartsDelete({ sn: row.sparePartsSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam = {
        productCode: '',
        relationNo: '',
        state: undefined,
        sparePartsType: undefined,
        sparePartsNo: '',
        supplierName: '',
        kingdeeNo: ''
      }
      this.$refs.table.refresh(true)
    },
    //  单条审核
    handleAudit (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要审核通过吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          sparePartsAudit({sn:row.sparePartsSn}).then(res => {
            if (res.status == 200) {
              if(res.data&&res.data.sparePartsDetailList){
                _this.$nextTick(()=>{
                  _this.openAuditNoModal = true
                  _this.$refs.auditNoPassModal.setData(res.data.sparePartsDetailList)
                })
              }else{
                _this.hanldeAuditOk(res.message)
              }
            }
            _this.spinning = false
          })
        }
      })
    },
    // 批量审核
    handleBatchAudit () {
      const _this = this
      if (!this.rowSelectionInfo || (this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      const snList = this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys || []
      _this.spinning = true
      sparePartsAuditVerify(snList).then(res => {
        if(res.status == 200&&res.data){
          _this.$nextTick(()=>{
            _this.openBatchAuditNoModal = true
            _this.$refs.batchAuditNoModal.getData(res.data)
          })
        }
        _this.spinning = false
      })
    },
    // 审核成功
    hanldeAuditOk(message){
      this.$refs.table.clearSelected() // 清空表格选中项
      this.$message.success(message)
      this.$refs.table.refresh()
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.openModal = false
      this.openDetailModal = false
      this.itemSn = null
      this.rowSelectionInfo = null
      this.$refs.table.clearTable()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 235
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less">
  .bulkWarehousingOrderList-wrap{
    .active{
      color: #ed1c24;
      cursor: pointer;
    }
    .common{
      color: rgba(0, 0, 0);
    }
  }
</style>
