<template>
  <div class="key-dm-inbound-wrapper">
    <Tabs v-model="activeTab" @on-click="handleTabChange">
      <TabPane label="办公用品入库" name="inbound">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="8">
              <Input v-model="filters.inbound.inbound_no" placeholder="单号/批次号" style="width:60%" />
              <Button type="primary" class="mr10" @click="handleSearch('inbound')">搜索</Button>
              <Button @click="handleReset('inbound')">重置</Button>
            </Col>
            <Col span="16" class="text-right">
              <Button type="success" @click="openInboundModal">新增入库</Button>
            </Col>
          </Row>
        </div>
        <Table :data="tables.inbound" :loading="loading.inbound" border>
          <TableColumn type="index" title="序号" width="60" align="center" />
          <TableColumn prop="inbound_no" title="入库单号" align="center" />
          <TableColumn prop="batch_no" title="批次号" align="center" />
          <TableColumn prop="inbound_date" title="入库日期" align="center" />
          <TableColumn prop="inbound_type" title="类型" align="center" />
          <TableColumn prop="inbound_status" title="状态" align="center" />
          <TableColumn title="操作" width="360" align="center">
            <template slot-scope="{ row }">
              <Button size="small" @click="openDetail(row)">详细</Button>
              <Button size="small" type="primary" @click="openEdit(row)" v-if="canEdit(row)">修改</Button>
              <Poptip confirm title="确认删除？" transfer @on-ok="deleteInbound(row)">
                <Button size="small" type="error">删除</Button>
              </Poptip>
              <Poptip confirm title="确认执行入库？" transfer @on-ok="doInbound(row)" v-if="row.inbound_status===0">
                <Button size="small" type="success">入库</Button>
              </Poptip>
            </template>
          </TableColumn>
        </Table>
        <Page class="page_style" :total="pagers.inbound.totalRecord" :current="pagers.inbound.pageNo" :page-size="pagers.inbound.pageSize"
          show-total show-sizer @on-change="pageChange('inbound', $event)" @on-page-size-change="sizeChange('inbound', $event)" />
      </TabPane>

      <TabPane label="办公用品归还" name="return">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="10">
              <Input v-model="filters.return.key" placeholder="申请单号/申请人" style="width:60%" />
              <Button type="primary" class="mr10" @click="handleSearch('return')">搜索</Button>
              <Button @click="handleReset('return')">重置</Button>
            </Col>
          </Row>
        </div>
        <Table :data="tables.return" :loading="loading.return" border>
          <TableColumn type="index" title="序号" width="60" align="center" />
          <TableColumn prop="application_no" title="申请单号" align="center" />
          <TableColumn prop="applicant_name" title="申请人" align="center" />
          <TableColumn prop="department_name" title="部门" align="center" />
          <TableColumn prop="issue_status" title="发放状态" align="center" />
          <TableColumn title="操作" width="140" align="center">
            <template slot-scope="{ row }">
              <Button size="small" type="primary" @click="openReturnModal(row)">归还</Button>
            </template>
          </TableColumn>
        </Table>
        <Page class="page_style" :total="pagers.return.totalRecord" :current="pagers.return.pageNo" :page-size="pagers.return.pageSize"
          show-total show-sizer @on-change="pageChange('return', $event)" @on-page-size-change="sizeChange('return', $event)" />
      </TabPane>

      <TabPane label="库存查询" name="inventory">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="10">
              <Input v-model="filters.inventory.material_name" placeholder="物料名称/编码" style="width:60%" />
              <Button type="primary" class="mr10" @click="handleSearch('inventory')">搜索</Button>
              <Button @click="handleReset('inventory')">重置</Button>
            </Col>
          </Row>
        </div>
        <Table :data="tables.inventory" :loading="loading.inventory" border>
          <TableColumn type="index" title="序号" width="60" align="center" />
          <TableColumn prop="material_code" title="物料编码" align="center" />
          <TableColumn prop="material_name" title="物料名称" align="center" />
          <TableColumn prop="total_quantity" title="总量" align="center" />
          <TableColumn prop="available_quantity" title="可用" align="center" />
          <TableColumn prop="borrowed_quantity" title="借出" align="center" />
        </Table>
      </TabPane>
    </Tabs>

    <!-- 入库弹窗 -->
    <Modal v-model="inboundModal.visible" :title="inboundModal.isEdit ? '修改入库' : '新增入库'" width="800">
      <Form :model="inboundModal.form" :label-width="120" ref="inboundForm">
        <FormItem label="入库单号">
          <Input v-model="inboundModal.form.inbound_no" />
        </FormItem>
        <FormItem label="批次号">
          <Input v-model="inboundModal.form.batch_no" />
        </FormItem>
        <FormItem label="入库日期">
          <DatePicker v-model="inboundModal.form.inbound_date" type="date" />
        </FormItem>
        <FormItem label="存放位置">
          <Input v-model="inboundModal.form.storage_location" />
        </FormItem>
        <FormItem label="备注">
          <Input type="textarea" v-model="inboundModal.form.remark" :rows="2" />
        </FormItem>

        <h4>明细（从物料库选择）</h4>
        <Table :data="inboundModal.details" size="small" border>
          <TableColumn prop="material_code" title="物料编码" />
          <TableColumn prop="material_name" title="物料名称" />
          <TableColumn prop="inbound_quantity" title="入库数量" />
          <TableColumn prop="unit_price" title="单价" />
          <TableColumn prop="total_amount" title="总金额" />
        </Table>
      </Form>
      <div slot="footer">
        <Button @click="inboundModal.visible=false">取消</Button>
        <Button type="primary" :loading="inboundModal.saving" @click="saveInbound">保存</Button>
      </div>
    </Modal>

    <!-- 归还弹窗 -->
    <Modal v-model="returnModal.visible" title="归还物品" width="700">
      <Form :model="returnModal.record" :label-width="120">
        <FormItem label="申请单号"><span>{{ returnModal.record.application_no }}</span></FormItem>
        <FormItem label="申请人"><span>{{ returnModal.record.applicant_name }}</span></FormItem>
        <FormItem label="归还明细">
          <Table :data="returnModal.details" size="small" border>
            <TableColumn prop="material_name" title="物料名称" />
            <TableColumn prop="apply_quantity" title="申请数量" />
            <TableColumn prop="returned_quantity" title="归还数量" />
          </Table>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="returnModal.visible=false">取消</Button>
        <Button type="primary" :loading="returnModal.saving" @click="confirmReturn">归还</Button>
      </div>
    </Modal>

    <!-- 详情弹窗 -->
    <Modal v-model="detailModal.visible" title="入库/归还详情" width="720">
      <Spin fix v-if="detailModal.loading"></Spin>
      <div v-else>
        <Row :gutter="16"><Col span="12"><p><strong>单号：</strong>{{ detailModal.data.inbound_no || detailModal.data.application_no }}</p></Col></Row>
        <Row class="mt8"><Col span="24"><h4>明细</h4></Col></Row>
        <Table :data="detailModal.details" size="small" border>
          <TableColumn prop="material_code" title="物料编码" />
          <TableColumn prop="material_name" title="物料名称" />
          <TableColumn prop="inbound_quantity" title="数量" />
          <TableColumn prop="unit_price" title="单价" />
        </Table>
        <Row class="mt8"><Col span="24"><h4>操作日志</h4></Col></Row>
        <Table :data="detailModal.logs" size="small" border>
          <TableColumn prop="op_type" title="操作类型" />
          <TableColumn prop="quantity" title="数量" />
          <TableColumn prop="create_time" title="时间" />
        </Table>
      </div>
      <div slot="footer"><Button type="primary" @click="detailModal.visible=false">关闭</Button></div>
    </Modal>
  </div>
</template>

<script>
import {
  getInboundList,
  saveInbound,
  deleteInbound,
  doInbound,
  getPendingReturnList,
  processReturn,
  getInventoryList,
  getInboundById
} from '@/api/key-dm-inbound'

export default {
  name: 'key-dm-inbound-index',
  data () {
    return {
      activeTab: 'inbound',
      filters: { inbound: { inbound_no: '' }, return: { key: '' }, inventory: { material_name: '' } },
      tables: { inbound: [], return: [], inventory: [] },
      pagers: { inbound: { pageNo:1,pageSize:10,totalRecord:0 }, return: { pageNo:1,pageSize:10,totalRecord:0 }, inventory: { pageNo:1,pageSize:10,totalRecord:0 } },
      loading: { inbound:false, return:false, inventory:false },
      inboundModal: { visible:false,isEdit:false,saving:false,form:{},details:[] },
      returnModal: { visible:false,record:{},details:[],saving:false },
      detailModal: { visible:false,loading:false,data:{},details:[],logs:[] }
    }
  },
  created () { this.fetchList('inbound') },
  methods: {
    handleTabChange (name) {
      this.activeTab = name
      if (name === 'return') this.fetchList('return')
      if (name === 'inventory') this.fetchList('inventory')
    },
    fetchList (tab) {
      const apiMap = { inbound: getInboundList, return: getPendingReturnList, inventory: getInventoryList }
      const api = apiMap[tab]; if (!api) return
      this.loading[tab] = true
      const payload = Object.assign({}, this.pagers[tab] || {}, { params: this.filters[tab] || {} })
      api(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          const data = ret.data.data || {}
          this.tables[tab] = data.results || []
          if (data.totalRecord !== undefined) (this.pagers[tab]||{}).totalRecord = data.totalRecord
        } else this.$Notice.error({ title:'查询失败', desc: ret.data && ret.data.errmsg })
      }).finally(()=>{ this.loading[tab]=false })
    },
    handleSearch (tab) { (this.pagers[tab]||{}).pageNo=1; this.fetchList(tab) },
    handleReset (tab) { this.filters[tab] = {}; (this.pagers[tab]||{}).pageNo=1; this.fetchList(tab) },
    pageChange (tab,pageNo) { (this.pagers[tab]||{}).pageNo=pageNo; this.fetchList(tab) },
    sizeChange (tab,size) { (this.pagers[tab]||{}).pageSize=size; (this.pagers[tab]||{}).pageNo=1; this.fetchList(tab) },

    openInboundModal () {
      this.inboundModal.isEdit = false
      this.inboundModal.form = { inbound_no:'', batch_no:'', inbound_date:'', inbound_type:1, storage_location:'', remark:'' }
      this.inboundModal.details = []
      this.inboundModal.visible = true
    },
    openEdit (row) {
      this.inboundModal.isEdit = true
      getInboundById({ id: row.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.inboundModal.form = ret.data.data || {}
          this.inboundModal.details = ret.data.data.details || []
        }
      })
      this.inboundModal.visible = true
    },
    saveInbound () {
      this.inboundModal.saving = true
      saveInbound(Object.assign({}, this.inboundModal.form, { details: this.inboundModal.details })).then(ret => {
        if (ret.data && ret.data.errcode === 0) { this.$Message.success('保存成功'); this.inboundModal.visible=false; this.fetchList('inbound') } else this.$Notice.error({ title:'保存失败', desc: ret.data && ret.data.errmsg })
      }).finally(()=>{ this.inboundModal.saving=false })
    },
    canEdit (row) { return row.inbound_status === 0 },
    deleteInbound (row) { deleteInbound({ id: row.id }).then(ret => { if (ret.data && ret.data.errcode === 0) { this.$Message.success('删除成功'); this.fetchList('inbound') } else this.$Notice.error({ title:'删除失败', desc: ret.data && ret.data.errmsg }) }) },
    doInbound (row) { doInbound({ id: row.id }).then(ret=>{ if (ret.data && ret.data.errcode === 0) { this.$Message.success('入库成功'); this.fetchList('inbound'); this.fetchList('inventory') } else this.$Notice.error({ title:'入库失败', desc: ret.data && ret.data.errmsg }) }) },

    openReturnModal (row) {
      this.returnModal.record = Object.assign({}, row)
      this.returnModal.details = []
      getInboundById({ id: row.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) this.returnModal.details = ret.data.data.details || []
      })
      this.returnModal.visible = true
    },
    confirmReturn () {
      this.returnModal.saving = true
      processReturn({ id: this.returnModal.record.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) { this.$Message.success('归还已入库并更新库存'); this.returnModal.visible=false; this.fetchList('return'); this.fetchList('inventory') } else this.$Notice.error({ title:'归还失败', desc: ret.data && ret.data.errmsg })
      }).finally(()=>{ this.returnModal.saving=false })
    },

    openDetail (row) {
      this.detailModal.visible = true
      this.detailModal.loading = true
      getInboundById({ id: row.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.detailModal.data = ret.data.data || {}
          this.detailModal.details = ret.data.data.details || []
          this.detailModal.logs = ret.data.data.logs || []
        } else this.$Notice.error({ title:'查询失败', desc: ret.data && ret.data.errmsg })
      }).finally(()=>{ this.detailModal.loading=false })
    }
  }
}
</script>

<style scoped>
.key-dm-inbound-wrapper { padding: 10px; }
.search-div { border: 1px solid #dce1e7; padding: 12px; margin-bottom: 12px; background-color: #f8fbff; }
.mr10 { margin-right: 10px; }
.text-right { text-align: right; }
.page_style { margin-top: 12px; text-align: right; }
.mt8 { margin-top: 8px; }
</style>


