<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" :columns="applyColumns" border>
          <template slot="action" 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>
        </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" :columns="pendingColumns" border>
          <template slot="action" slot-scope="{ row }">
            <Button size="small" type="primary" @click="openApproveModal(row)">处理</Button>
          </template>
        </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" :columns="historyColumns" border>
          <template slot="action" slot-scope="{ row }">
            <Button size="small" @click="openDetail(row)">详细</Button>
          </template>
        </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>
        <Row type="flex" justify="end" class="mb8">
          <Col>
            <Button size="small" class="mr5" type="primary" @click="showMaterialSelector = true">添加</Button>
            <Button size="small" type="error" @click="deleteSelectedDetails">删除</Button>
          </Col>
        </Row>
        <Table :data="applyModal.details" :columns="applyDetailColumns" size="small" border @on-selection-change="onApplyDetailSelectionChange" />
        <MaterialSelector v-model="showMaterialSelector" :selected="[]" @on-ok="handleMaterialSelectorOk" @cancel="showMaterialSelector = false" />
      </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" :columns="approveDetailColumns" size="small" border />
        </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" :columns="detailDetailColumns" size="small" border />
        <Row class="mt8"><Col span="24"><h4>审批记录</h4></Col></Row>
        <Table :data="detailModal.logs" :columns="detailLogsColumns" size="small" border />
      </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'
import MaterialSelector from '@/view/key-person/key_dm_conf/materialSelector.vue'

export default {
  name: 'key-dm-inventory-index',
  components: { MaterialSelector },
  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 },
      applyColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '申请单号', key: 'application_no', align: 'center' },
        { title: '申请人', key: 'applicant_name', align: 'center' },
        { title: '部门', key: 'department_name', align: 'center' },
        { title: '请假类型', key: 'borrow_purpose', align: 'center' },
        { title: '起止时间', key: 'start_time', align: 'center' },
        { title: '时长', key: 'duration', align: 'center' },
        { title: '状态', key: 'approval_status', align: 'center' },
        { title: '操作', slot: 'action', align: 'center', width: 320 }
      ],
      pendingColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '申请单号', key: 'application_no', align: 'center' },
        { title: '申请人', key: 'applicant_name', align: 'center' },
        { title: '部门', key: 'department_name', align: 'center' },
        { title: '提交时间', key: 'submit_time', align: 'center' },
        { title: '操作', slot: 'action', width: 120, align: 'center' }
      ],
      historyColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '申请单号', key: 'application_no', align: 'center' },
        { title: '申请人', key: 'applicant_name', align: 'center' },
        { title: '状态', key: 'approval_status', align: 'center' },
        { title: '审批完成时间', key: 'approval_complete_time', align: 'center' },
        { title: '操作', slot: 'action', width: 100, align: 'center' }
      ],
      // 模态窗口内表格列定义
      applyDetailColumns: [
        { type: 'selection', width: 60 },
        { title: '物料编码', key: 'material_code' },
        { title: '物料名称', key: 'material_name' },
        { title: '申请数量', key: 'apply_quantity' },
        { title: '单位', key: 'unit' },
        { title: '备注', key: 'issue_remark' }
      ],
      approveDetailColumns: [
        { title: '物料名称', key: 'material_name' },
        { title: '申请数量', key: 'apply_quantity' },
        { title: '单位', key: 'unit' },
        { title: '可用库存', key: 'available_quantity' }
      ],
      detailDetailColumns: [
        { title: '物料编码', key: 'material_code' },
        { title: '物料名称', key: 'material_name' },
        { title: '申请数量', key: 'apply_quantity' },
        { title: '单位', key: 'unit' },
        { title: '已归还', key: 'returned_quantity' }
      ],
      detailLogsColumns: [
        { title: '操作类型', key: 'op_type' },
        { title: '数量', key: 'quantity' },
        { title: '时间', key: 'create_time' },
        { title: '操作人', key: 'create_by' }
      ],
      // 选择器控制与已选明细
      showMaterialSelector: false,
      applySelectedDetails: [],
      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
    },
    onApplyDetailSelectionChange (list) {
      this.applySelectedDetails = list || []
    },
    handleMaterialSelectorOk (selectedRows) {
      if (!Array.isArray(selectedRows) || selectedRows.length === 0) {
        this.$Message.warning('未选择物料')
        return
      }
      selectedRows.forEach(sel => {
        const code = sel.material_code
        const exist = this.applyModal.details.find(d => d.material_code === code)
        if (exist) {
          exist.apply_quantity = Number(exist.apply_quantity || 0) + 1
        } else {
          this.applyModal.details.push({
            material_code: sel.material_code,
            material_name: sel.material_name,
            apply_quantity: 1,
            unit: sel.unit,
            issue_remark: '',
            available_quantity: sel.available_quantity || 0
          })
        }
      })
      this.showMaterialSelector = false
    },
    deleteSelectedDetails () {
      if (!this.applySelectedDetails || this.applySelectedDetails.length === 0) {
        this.$Message.warning('请先选择要删除的明细行')
        return
      }
      const toRemoveCodes = this.applySelectedDetails.map(r => r.material_code)
      this.applyModal.details = this.applyModal.details.filter(d => !toRemoveCodes.includes(d.material_code))
      this.applySelectedDetails = []
    },
    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>
