<template>
  <div class="key-dm-inventory-wrapper">
    <Tabs v-model="activeTab" @on-click="handleTabChange">
      <TabPane label="办公用品申领" name="apply">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="10">
              <Input v-model="filters.apply.applicant_name" placeholder="姓名/工号" style="width:60%" />
              <Button type="primary" class="mr10" @click="handleSearch('apply')">搜索</Button>
              <Button @click="handleReset('apply')">重置</Button>
            </Col>
            <Col span="14" class="text-right">
              <Button type="success" @click="openApplyModal">申请</Button>
            </Col>
          </Row>
        </div>

        <Table :data="tables.apply" :loading="loading.apply" 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="approval_status" title="状态" align="center" />
          <TableColumn prop="submit_time" title="提交时间" align="center" />
          <TableColumn title="操作" width="320" 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>
              <Button size="small" type="success" @click="submit(row)" v-if="canSubmit(row)">提交</Button>
              <Poptip confirm title="确认撤回？" transfer @on-ok="revoke(row)" v-if="canRevoke(row)">
                <Button size="small" type="warning">撤回</Button>
              </Poptip>
            </template>
          </TableColumn>
        </Table>
        <Page class="page_style" :total="pagers.apply.totalRecord" :current="pagers.apply.pageNo" :page-size="pagers.apply.pageSize"
          show-total show-sizer @on-change="pageChange('apply', $event)" @on-page-size-change="sizeChange('apply', $event)" />
      </TabPane>

      <TabPane label="办公用品待审核" name="pending">
        <Table :data="tables.pending" :loading="loading.pending" 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="submit_time" title="提交时间" align="center" />
          <TableColumn title="操作" width="140" align="center">
            <template slot-scope="{ row }">
              <Button size="small" type="primary" @click="openApproveModal(row)">处理</Button>
            </template>
          </TableColumn>
        </Table>
        <Page class="page_style" :total="pagers.pending.totalRecord" :current="pagers.pending.pageNo" :page-size="pagers.pending.pageSize"
          show-total show-sizer @on-change="pageChange('pending', $event)" @on-page-size-change="sizeChange('pending', $event)" />
      </TabPane>

      <TabPane label="办公用品审核历史查询" name="history">
        <Table :data="tables.history" :loading="loading.history" 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="approval_status" title="状态" align="center" />
          <TableColumn prop="approval_time" title="审批时间" align="center" />
          <TableColumn title="操作" width="100" align="center">
            <template slot-scope="{ row }">
              <Button size="small" @click="openDetail(row)">详细</Button>
            </template>
          </TableColumn>
        </Table>
        <Page class="page_style" :total="pagers.history.totalRecord" :current="pagers.history.pageNo" :page-size="pagers.history.pageSize"
          show-total show-sizer @on-change="pageChange('history', $event)" @on-page-size-change="sizeChange('history', $event)" />
      </TabPane>
    </Tabs>

    <!-- 申请弹窗 -->
    <Modal v-model="applyModal.visible" :title="applyModal.isEdit ? '修改领用申请' : '新增领用申请'" width="800">
      <Form :model="applyModal.form" :label-width="120" ref="applyForm">
        <FormItem label="申请人">
          <Input v-model="applyModal.form.applicant_name" disabled />
        </FormItem>
        <FormItem label="部门">
          <Input v-model="applyModal.form.department_name" disabled />
        </FormItem>
        <FormItem label="领用用途">
          <Input v-model="applyModal.form.borrow_purpose" />
        </FormItem>
        <FormItem label="预计归还日期">
          <DatePicker v-model="applyModal.form.expected_return_date" type="date" />
        </FormItem>

        <h4>申请明细</h4>
        <Table :data="applyModal.details" size="small" border>
          <TableColumn prop="material_code" title="物料编码" />
          <TableColumn prop="material_name" title="物料名称" />
          <TableColumn prop="apply_quantity" title="申请数量" />
          <TableColumn prop="unit" title="单位" />
          <TableColumn prop="issue_remark" title="备注" />
        </Table>
      </Form>
      <div slot="footer">
        <Button @click="applyModal.visible=false">取消</Button>
        <Button type="primary" :loading="applyModal.saving" @click="saveApplication">保存</Button>
      </div>
    </Modal>

    <!-- 审核弹窗 -->
    <Modal v-model="approveModal.visible" title="申请处理" width="700">
      <Form :model="approveModal.record" :label-width="120">
        <FormItem label="申请单号"><span>{{ approveModal.record.application_no }}</span></FormItem>
        <FormItem label="申请人"><span>{{ approveModal.record.applicant_name }}</span></FormItem>
        <FormItem label="申请明细">
          <Table :data="approveModal.details" size="small" border>
            <TableColumn prop="material_name" title="物料名称" />
            <TableColumn prop="apply_quantity" title="申请数量" />
            <TableColumn prop="unit" title="单位" />
            <TableColumn prop="available_quantity" title="可用库存" />
          </Table>
        </FormItem>
        <FormItem label="审批意见">
          <Input type="textarea" v-model="approveModal.opinion" placeholder="驳回时必填" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="approveModal.visible=false">取消</Button>
        <Button type="success" :loading="approveModal.submitting" @click="confirmApprove">通过</Button>
        <Button type="error" :loading="approveModal.submitting" @click="confirmReject">驳回</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.applicant_name }}</p></Col><Col span="12"><p><strong>部门：</strong>{{ detailModal.data.department_name }}</p></Col></Row>
        <Row class="mt8"><Col span="24"><p><strong>领用用途：</strong>{{ detailModal.data.borrow_purpose }}</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="apply_quantity" title="申请数量" />
          <TableColumn prop="unit" title="单位" />
          <TableColumn prop="returned_quantity" 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="时间" />
          <TableColumn prop="create_by" title="操作人" />
        </Table>
      </div>
      <div slot="footer"><Button type="primary" @click="detailModal.visible=false">关闭</Button></div>
    </Modal>
  </div>
</template>

<script>
import {
  getBorrowList,
  saveBorrowApplication,
  submitBorrow,
  revokeBorrow,
  getPendingBorrowList,
  approveBorrow,
  rejectBorrow,
  getBorrowById
} from '@/api/key-dm-inventory'

export default {
  name: 'key-dm-inventory-index',
  data () {
    return {
      activeTab: 'apply',
      filters: { apply: { applicant_name: '' } },
      tables: { apply: [], pending: [], history: [] },
      pagers: { apply: { pageNo: 1, pageSize: 10, totalRecord: 0 }, pending: { pageNo: 1, pageSize: 10, totalRecord: 0 }, history: { pageNo: 1, pageSize: 10, totalRecord: 0 } },
      loading: { apply: false, pending: false, history: false },
      applyModal: { visible: false, isEdit: false, saving: false, form: {}, details: [] },
      approveModal: { visible: false, record: {}, details: [], opinion: '', submitting: false },
      detailModal: { visible: false, loading: false, data: {}, details: [], logs: [] }
    }
  },
  created () { this.fetchList('apply') },
  methods: {
    handleTabChange (name) {
      this.activeTab = name
      if (name === 'pending') this.fetchList('pending')
      if (name === 'history') this.fetchList('history')
    },
    fetchList (tab) {
      const apiMap = { apply: getBorrowList, pending: getPendingBorrowList, history: getBorrowList }
      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) },

    openApplyModal () {
      this.applyModal.isEdit = false
      this.applyModal.form = { applicant_id: '', applicant_name: '', department_id: '', department_name: '', borrow_purpose: '', expected_return_date: '', approval_status: 0 }
      this.applyModal.details = []
      this.applyModal.visible = true
    },
    openEdit (row) {
      this.applyModal.isEdit = true
      this.applyModal.form = Object.assign({}, row)
      // load details from backend when open (simplified)
      getBorrowById({ id: row.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.applyModal.details = ret.data.data.details || []
        }
      })
      this.applyModal.visible = true
    },
    saveApplication () {
      this.applyModal.saving = true
      const payload = Object.assign({}, this.applyModal.form, { details: this.applyModal.details })
      saveBorrowApplication(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) { this.$Message.success('保存成功'); this.applyModal.visible = false; this.fetchList('apply') } else this.$Notice.error({ title: '保存失败', desc: ret.data && ret.data.errmsg })
      }).finally(() => { this.applyModal.saving = false })
    },
    canEdit (row) { return row.approval_status === 0 || row.approval_status === -1 },
    canSubmit (row) { return row.approval_status === 0 || row.approval_status === -1 },
    canRevoke (row) { return row.approval_status === 1 },
    submit (row) {
      this.$Modal.confirm({ title: '确认提交',
        content: '提交后进入审批流程，是否继续？',
        onOk: () => {
          submitBorrow({ id: row.id }).then(ret => { if (ret.data && ret.data.errcode === 0) { this.$Message.success('提交成功'); this.fetchList('apply') } else this.$Notice.error({ title: '提交失败', desc: ret.data && ret.data.errmsg }) })
        } })
    },
    revoke (row) { revokeBorrow({ id: row.id }).then(ret => { if (ret.data && ret.data.errcode === 0) { this.$Message.success('撤回成功'); this.fetchList('apply') } else this.$Notice.error({ title: '撤回失败', desc: ret.data && ret.data.errmsg }) }) },

    openApproveModal (row) {
      this.approveModal.record = Object.assign({}, row)
      this.approveModal.opinion = ''
      // load details and current inventory for display
      getBorrowById({ id: row.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.approveModal.details = ret.data.data.details || []
        }
      })
      this.approveModal.visible = true
    },
    confirmApprove () {
      this.approveModal.submitting = true
      approveBorrow({ id: this.approveModal.record.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) { this.$Message.success('已通过，已生成出库并更新库存'); this.approveModal.visible = false; this.fetchList('pending'); this.fetchList('apply') } else this.$Notice.error({ title: '操作失败', desc: ret.data && ret.data.errmsg })
      }).finally(() => { this.approveModal.submitting = false })
    },
    confirmReject () {
      if (!this.approveModal.opinion || !this.approveModal.opinion.trim()) { this.$Message.warning('请输入驳回原因'); return }
      this.approveModal.submitting = true
      rejectBorrow({ id: this.approveModal.record.id, comment: this.approveModal.opinion }).then(ret => {
        if (ret.data && ret.data.errcode === 0) { this.$Message.success('已驳回'); this.approveModal.visible = false; this.fetchList('pending') } else this.$Notice.error({ title: '驳回失败', desc: ret.data && ret.data.errmsg })
      }).finally(() => { this.approveModal.submitting = false })
    },

    openDetail (row) {
      this.detailModal.visible = true
      this.detailModal.loading = true
      getBorrowById({ 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-inventory-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>
