<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="18">
              <span>部门：</span>
              <Input
                v-model="filters.apply.department_name"
                placeholder="请输入部门"
                class="mr10"
                style="width: 200px"
              />
              <span>申请人：</span>
              <Input
                v-model="filters.apply.applicant_name"
                placeholder="请输入申请人"
                class="mr10"
                style="width: 200px"
              />
              <span>开始时间：</span>
              <DatePicker
                v-model="filters.apply.startDate"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始时间"
                class="mr10"
                style="width: 200px"
              />
              <span>结束时间：</span>
              <DatePicker
                v-model="filters.apply.endDate"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择结束时间"
                class="mr10"
                style="width: 200px"
              />
              <br>
              <div class="mt8">
              <span>审批状态：</span>
              <Select
                v-model="filters.apply.approval_status"
                placeholder="请选择审批状态"
                class="mr10"
                style="width: 200px"
              >
                <Option :value='0'>待提交</Option>
                <Option :value='1'>审核中</Option>
                <Option :value='9'>审核通过</Option>
                <Option :value='-1'>驳回</Option>
              </Select>
              </div>
            </Col>
            <!-- 右侧操作按钮区：固定居右 -->
            <Col span="6" class="action-col">
              <Button type="primary" class="mr10" @click="handleSearch('apply')">搜索</Button>
              <Button type="primary" class="mr10" @click="handleReset('apply')">重置</Button>
              <Button type="primary" class="mr10" @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)" class="mr5" >详细</Button>
            <Button size="small" type="primary"  class="mr5" @click="openEdit(row)" v-if="canEdit(row)">修改</Button>
            <Poptip confirm title="提交后将进入审批流程" transfer @on-ok="submit(row)" v-if="canSubmit(row)" class="mr5">
              <Button size="small" type="success">提交</Button>
            </Poptip>
            <Poptip confirm title="确认撤回？" transfer @on-ok="revoke(row)" v-if="canRevoke(row)" class="mr5">
              <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">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="18">
              <span>部门：</span>
              <Input
                v-model="filters.history.department_name"
                placeholder="请输入部门"
                class="mr10"
                style="width: 200px"
              />
              <span>申请人：</span>
              <Input
                v-model="filters.history.applicant_name"
                placeholder="请输入申请人"
                class="mr10"
                style="width: 200px"
               />
              <span>提交开始时间：</span>
              <DatePicker
                v-model="filters.history.startDate"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始时间"
                class="mr10"
                style="width: 200px"
              />
              <span>提交结束时间：</span>
              <DatePicker
                v-model="filters.history.endDate"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择结束时间"
                class="mr10"
                style="width: 200px"
              />
              <br>
              <span>审批状态：</span>
              <Select
                v-model="filters.history.approval_status"
                placeholder="请选择审批状态"
                class="mr10"
                style="width: 200px"
              >
                <Option :value= "0">待提交</Option>
                <Option :value= "1">审核中</Option>
                <Option :value= "9">审核通过</Option>
                <Option :value= "-1">驳回</Option>
              </Select>
            </Col>
            <Col span="6" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('history')">搜索</Button>
              <Button type="primary" class="mr10" @click="handleReset('history')">重置</Button>
            </Col>
          </Row>
        </div>

        <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" :rules="applyRules" :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="领用用途" prop="borrow_purpose">
          <Input v-model="applyModal.form.borrow_purpose" />
        </FormItem>
        <FormItem label="审批人:" prop="approver_id">
          <Select
            v-model="applyModal.form.approver_id"
            placeholder="请选择审批人"
            class="form-input"
            filterable
          >
            <Option
              v-for="item in approverModal.approverList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }} {{ item.leader === 1 ? '-leader' : '' }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="预计归还日期">
          <DatePicker
            v-model="applyModal.form.expected_return_date"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="请选择预计归还日期"
          />
        </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"><p><strong>预计归还日期：</strong>{{ formatDate(detailModal.data.expected_return_date) }}</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>
    <!-- <Modal v-model="approverModal.visible" title="选择审批人" width="500">
      <Form :model="approverModal.form" :label-width="80">
        <FormItem label="审批人：" required>
          <Select
            v-model="approverModal.form.approver_id"
            placeholder="请选择审批人"
            class="form-input"
            filterable
          >
            <Option
              v-for="item in approverModal.approverList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }} {{ item.leader === 1 ? '-leader' : '' }}
            </Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="approverModal.visible=false">取消</Button>
        <Button
          type="primary"
          :loading="approverModal.submitting"
          @click="confirmSubmitWithApprover"
          :disabled="!approverModal.form.approver_id"
        >
          确认提交
        </Button>
      </div>
    </Modal> -->
  </div>
</template>

<script>
import {
  getBorrowList,
  saveBorrowApplication,
  submitBorrow,
  revokeBorrow,
  getPendingBorrowList,
  getHistoryBorrowList,
  approveBorrow,
  rejectBorrow,
  getBorrowById,
  getSupplyApproval
} from '@/api/key-dm'
import MaterialSelector from '@/view/key-person/key_dm_conf/materialSelector.vue'
import { normalizeVisitTimeValue } from '@/view/key-person/key_dm_conf/dates.js'

export default {
  name: 'key-dm-inventory-index',
  components: { MaterialSelector },
  data () {
    return {
      // 表单验证规则
      applyRules: {
        borrow_purpose: [
          { required: true, message: '请填写申领用途', trigger: 'blur' }
        ],
        approver_id: [
          { required: true, message: '请选择审批人', trigger: 'change' }
        ]
      },
      approverModal: {
        visible: false,
        submitting: false,
        form: { approver_id: '' }, // 选中的审批人ID
        approverList: [], // 审批人列表
        currentBorrowId: '' // 暂存当前提交的申请ID
      },
      // 申请弹窗中的可编辑行状态
      editingRowIndex: -1,
      editingCellField: '',
      // 审批状态映射字典
      approvalStatusMap: { '0': '待提交', '1': '审核中', '9': '审核通过', '-1': '驳回' },
      opTypeMap: { '1': '入库', '2': '出库' },
      activeTab: 'apply',
      filters: {
        apply: { application_no: '', applicant_name: '', approval_status: null, startDate: null, endDate: null },
        history: { application_no: '', applicant_name: '', approval_status: null, startDate: null, endDate: null }
      },
      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: 'department_name', align: 'center' },
        { title: '申请人', key: 'applicant_name', align: 'center' },
        { title: '申领用途', key: 'borrow_purpose', align: 'center' },
        {
          title: '提交申请时间',
          key: 'submit_time',
          align: 'center',
          width: '300px',
          render: (h, { row }) => {
            return h('span', this.formatDateTime(row.submit_time) || '-')
          }
        },
        // {
        //   title: '起止时间',
        //   key: 'start_time',
        //   align: 'center',
        //   width: '300px',
        //   render: (h, { row }) => {
        //     return h('span', (this.formatDateTime(row.create_time) || row.create_time || '-') + '--' + (this.formatDateTime(row.approval_time) || row.approval_time || '-'))
        //   }
        // },
        // {
        //   title: '时长',
        //   key: 'duration',
        //   align: 'center',
        //   render: (h, { row }) => {
        //     const createTime = Number(row.create_time) || 0
        //     const approvalTime = Number(row.approval_time) || 0
        //     let duration = null
        //     if (createTime !== 0 && approvalTime !== 0) {
        //       const diffMs = Math.abs(approvalTime - createTime)
        //       duration = this.formatDuration(diffMs)
        //     } else {
        //       duration = this.formatDuration('')
        //     }
        //     return h('span', duration)
        //   }
        // },
        {
          title: '状态',
          key: 'approval_status',
          align: 'center',
          render: (h, { row }) => {
            return h('span', this.approvalStatusMap[row.approval_status + ''] || row.approval_status || '-')
          }
        },
        { title: '操作', slot: 'action', align: 'center', width: 260 }
      ],
      pendingColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        // { title: '申请单号', key: 'application_no', align: 'center' },
        { title: '部门', key: 'department_name', align: 'center' },
        { title: '申请人', key: 'applicant_name', align: 'center' },
        { title: '申请用途', key: 'borrow_purpose', align: 'center' },
        {
          title: '提交申请时间',
          key: 'submit_time',
          align: 'center',
          render: (h, { row }) => {
            return h('span', this.formatDate(row.submit_time) || row.submit_time || '-')
          }
        },
        { title: '操作', slot: 'action', width: 120, align: 'center' }
      ],
      historyColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '部门', key: 'department_name', align: 'center' },
        // { title: '申请单号', key: 'application_no', align: 'center' },
        { title: '申请人', key: 'applicant_name', align: 'center' },
        { title: '申请用途', key: 'borrow_purpose', align: 'center' },
        {
          title: '状态',
          key: 'approval_status',
          align: 'center',
          render: (h, { row }) => {
            return h('span', this.approvalStatusMap[row.approval_status + ''] || row.approval_status || '-')
          }
        },
        {
          title: '提交审批时间',
          key: 'submit_time',
          align: 'center',
          render: (h, { row }) => {
            return h('span', this.formatDateTime(row.submit_time) || '-')
          }
        },
        {
          title: '审批完成时间',
          key: 'approval_time',
          align: 'center',
          render: (h, { row }) => {
            return h('span', this.formatDateTime(row.approval_time) || row.approval_time || '-')
          }
        },
        { title: '操作', slot: 'action', width: 100, align: 'center' }
      ],
      // 模态窗口内表格列定义
      applyDetailColumns: [
        { type: 'selection', width: 60 },
        { title: '物料编码', key: 'material_code' },
        { title: '物料名称', key: 'material_name' },
        {
          title: '申请数量',
          key: 'apply_quantity',
          render: (h, { row, column, index }) => {
            // 如果当前行是编辑状态，显示输入框
            if (this.editingRowIndex === index && this.editingCellField === 'apply_quantity') {
              return h('InputNumber', {
                props: {
                  value: row.apply_quantity,
                  min: 1,
                  max: row.available_quantity || 9999,
                  precision: 0
                },
                style: { width: '100%' },
                on: {
                  input: (value) => {
                    // 更新数据
                    this.applyModal.details[index].apply_quantity = value
                  },
                  'on-blur': () => {
                    // 失去焦点时退出编辑模式
                    this.editingRowIndex = -1
                    this.editingCellField = ''
                  },
                  'on-keyup': (event) => {
                    // 按回车键保存并退出编辑
                    if (event.keyCode === 13) {
                      this.editingRowIndex = -1
                      this.editingCellField = ''
                    }
                  }
                }
              })
            } else {
              // 非编辑状态，显示文本和编辑图标
              return h('div', {
                style: {
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  cursor: 'pointer',
                  padding: '0 8px'
                },
                on: {
                  click: () => {
                    // 点击进入编辑模式
                    this.editingRowIndex = index
                    this.editingCellField = 'apply_quantity'
                    // 下一个tick聚焦到输入框
                    this.$nextTick(() => {
                      const input = document.querySelector(`.ivu-table-cell-with-input input`)
                      if (input) input.focus()
                    })
                  }
                }
              }, [
                h('span', row.apply_quantity || 0),
                h('Icon', {
                  props: {
                    type: 'md-create',
                    size: 14
                  },
                  style: {
                    color: '#2d8cf0',
                    marginLeft: '8px'
                  }
                })
              ])
            }
          }
        },
        { title: '单位', key: 'unit' }
      ],
      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: 'material_name' },
        {
          title: '操作类型',
          key: 'op_type',
          render: (h, { row }) => {
            return h('span', this.opTypeMap[row.op_type] || row.op_type || '-')
          }
        },
        { title: '数量', key: 'quantity' },
        {
          title: '时间',
          key: 'create_time',
          width: '150px',
          render: (h, { row }) => {
            return h('span', this.formatDateTime(row.create_time) || row.create_time || '-')
          }
        },
        { title: '操作人', key: 'name' }
      ],
      // 选择器控制与已选明细
      showMaterialSelector: false,
      applySelectedDetails: [],
      applyModal: { visible: false, isEdit: false, saving: false, form: {}, details: [], isEditing: false },
      approveModal: { visible: false, record: {}, details: [], opinion: '', submitting: false },
      detailModal: { visible: false, loading: false, data: {}, details: [], logs: [] }
    }
  },
  created () {
    this.fetchList('apply')
    this.fetchApproverList()
  },
  methods: {
    // 新增：获取审批人列表
    async fetchApproverList () {
      await getSupplyApproval().then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.approverModal.approverList = ret.data.data || []
          const leaderItem = this.approverModal.approverList.find(
            (item) => item.leader === 1
          )
          if (leaderItem) {
            this.approverModal.form.approver_id = leaderItem.id
          } else {
            this.approverModal.form.approver_id = this.approverModal.approverList[0].id
          }
        } else {
          this.$Notice.error({ title: '获取审批人失败', desc: ret.data && ret.data.errmsg })
        }
      })
    },
    // 获取当天日期，格式为 yyyy-MM-dd
    getTodayDate () {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 格式化毫秒差值为易读的时长
    formatDuration (diffMs) {
      // 无有效差值时返回兜底值
      if (diffMs <= 0) return '--'
      // 时间单位换算（毫秒）
      const oneSecond = 1000
      const oneMinute = oneSecond * 60
      const oneHour = oneMinute * 60
      const oneDay = oneHour * 24
      // 计算各单位的数值
      const days = Math.floor(diffMs / oneDay)
      const hours = Math.floor((diffMs % oneDay) / oneHour)
      const minutes = Math.floor((diffMs % oneHour) / oneMinute)
      const seconds = Math.floor((diffMs % oneMinute) / oneSecond)
      // 拼接时长字符串（按需显示非零单位，避免冗余）
      let duration = ''
      if (days > 0) duration += `${days}天`
      if (hours > 0 || duration) duration += `${hours}时`
      if (minutes > 0 || duration) duration += `${minutes}分`
      duration += `${seconds}秒`
      return duration
    },
    // 处理单元格点击编辑
    handleCellEdit (row, column, index, field) {
      if (field === 'apply_quantity') {
        this.editingRowIndex = index
        this.editingCellField = field
        // 下一个tick聚焦到输入框
        this.$nextTick(() => {
          const input = document.querySelector(`.ivu-table-cell-with-input input`)
          if (input) input.focus()
        })
      }
    },
    // 添加方法：退出编辑模式
    exitEditMode () {
      this.editingRowIndex = -1
      this.editingCellField = ''
    },
    // 转换时间戳为yyyy-MM-dd
    formatDate (timestamp) {
      if (!timestamp || isNaN(Number(timestamp))) return ''
      const d = new Date(Number(timestamp))
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    },
    // 转换时间戳为yyyy-MM-dd hh-mm-ss
    formatDateTime (timestamp) {
      // 空值/非数字处理：返回空字符串
      if (!timestamp || isNaN(Number(timestamp))) return ''
      const d = new Date(Number(timestamp))
      // 年
      const year = d.getFullYear()
      // 月（补0）
      const month = String(d.getMonth() + 1).padStart(2, '0')
      // 日（补0）
      const day = String(d.getDate()).padStart(2, '0')
      // 时（24小时制，补0）
      const hour = String(d.getHours()).padStart(2, '0')
      // 分（补0）
      const minute = String(d.getMinutes()).padStart(2, '0')
      // 秒（补0）
      const second = String(d.getSeconds()).padStart(2, '0')
      // 拼接为 yyyy-MM-dd HH:mm:ss
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    },
    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: getHistoryBorrowList }
      const api = apiMap[tab]; if (!api) return
      this.loading[tab] = true
      // 清理空值，防止参数传递问题
      const cleanParams = (obj) => {
        obj.startDate = normalizeVisitTimeValue(obj.startDate)
        obj.endDate = normalizeVisitTimeValue(obj.endDate)
        const cleaned = {}
        for (let key in obj) {
          const value = obj[key]
          if (value !== null && value !== undefined && value !== '') {
            cleaned[key] = value
          }
        }
        return cleaned
      }
      const payload = Object.assign({}, this.pagers[tab] || {}, { params: cleanParams(this.filters[tab] || {}) })
      console.log(payload)
      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,
        approver_id: '' // 确保包含审批人字段
      }
      // 如果有默认审批人，可以设置
      if (this.approverModal.approverList.length > 0) {
        const leaderItem = this.approverModal.approverList.find(item => item.leader === 1)
        this.applyModal.form.approver_id = leaderItem ? leaderItem.id : this.approverModal.approverList[0].id
      }
      this.applyModal.details = []
      this.applyModal.visible = true
      this.exitEditMode()
      // 重置验证状态（如果有的话）
      if (this.$refs.applyForm) {
        this.$refs.applyForm.resetFields()
      }
    },
    openEdit (row) {
      console.log(row)
      this.applyModal.isEdit = true
      this.applyModal.form = Object.assign({}, row)
      // 关键：时间戳转 yyyy-MM-dd 字符串
      if (this.applyModal.form.expected_return_date) {
        this.applyModal.form.expected_return_date = this.formatDate(this.applyModal.form.expected_return_date)
      } else {
        this.applyModal.form.expected_return_date = this.getTodayDate()
      }
      // 如果表单中没有 approver_id，设置默认值
      if (!this.applyModal.form.approver_id && this.approverModal.approverList.length > 0) {
        const leaderItem = this.approverModal.approverList.find(item => item.leader === 1)
        this.applyModal.form.approver_id = leaderItem ? leaderItem.id : this.approverModal.approverList[0].id
      }
      // 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
      this.exitEditMode()
    },
    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_id: sel.id,
            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.exitEditMode()
      // 表单验证
      this.$refs.applyForm.validate((valid) => {
        if (!valid) {
          this.$Message.error('请填写完整表单信息')
          return
        }
        // 验证明细
        if (this.applyModal.details === null || this.applyModal.details.length < 1) {
          this.$Message.error('请至少申领一条用品')
          return
        }
        // 验证申请数量
        const invalidDetails = this.applyModal.details.filter(d =>
          !d.apply_quantity || d.apply_quantity <= 0
        )
        if (invalidDetails.length > 0) {
          this.$Message.error('请填写正确的申请数量')
          return
        }
        this.applyModal.saving = true
        const payload = Object.assign({}, this.applyModal.form, {
          details: this.applyModal.details,
          // 确保提交时带上审批人ID
          approver_id: this.approverModal.form.approver_id
        })
        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) {
      const userId = this.$store.state.user.userId
      return (row.approval_status === 0 && row.applicant_id === userId) || (row.approval_status === -1 && row.applicant_id === userId)
    },
    canSubmit (row) {
      const userId = this.$store.state.user.userId
      return (row.approval_status === 0 && row.applicant_id === userId) || (row.approval_status === -1 && row.applicant_id === userId)
    },
    canRevoke (row) {
      const userId = this.$store.state.user.userId
      return (row.approval_status === 1 && row.applicant_id === userId)
    },
    submit (row) {
      // 暂存当前申请ID
      this.approverModal.currentBorrowId = row.id
      // 清空上次选择的审批人
      this.approverModal.form.approver_id = ''
      // 获取审批人列表
      this.fetchApproverList()
      // 打开审批人选择弹窗
      // this.approverModal.visible = true
      this.confirmSubmitWithApprover()
    },
    // 新增：确认选择审批人后提交
    confirmSubmitWithApprover () {
      const approverId = this.approverModal.form.approver_id

      this.approverModal.submitting = true
      // 调用提交接口，携带审批人ID（需后端接口支持）
      submitBorrow({
        id: this.approverModal.currentBorrowId,
        approver_id: approverId, // 新增审批人参数
        approver_name: this.approverModal.form.approver_name
      }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('提交成功')
          this.approverModal.visible = false
          this.fetchList('apply')
        } else {
          this.$Notice.error({ title: '提交失败', desc: ret.data && ret.data.errmsg })
        }
      }).finally(() => {
        this.approverModal.submitting = false
      })
    },
    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; }
/* 搜索区域外层盒：统一间距+背景 */
.search-container {
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
}

/* 行容器：垂直居中+间距 */
.search-row {
  margin: 0 !important;
}

/* 内联表单：消除默认间距 */
.form-inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin: 0;
}

/* 表单项：统一间距+对齐 */
.form-item {
  margin: 0 8px 0 0 !important;
  display: flex;
  align-items: center;
}

/* 输入框/下拉框：统一宽度 */
.form-input {
  width: 180px !important;
}

/* 按钮组：单独样式 */
.form-item-actions {
  margin-left: 16px !important;
}

/* 右侧操作列：居右+内边距 */
.action-col {
  text-align: right;
  padding-right: 16px;
}

/* 响应式适配：小屏幕自动换行 */
@media (max-width: 768px) {
  .form-inline {
    flex-direction: column;
    align-items: flex-start;
  }
  .form-item {
    margin: 8px 0 !important;
    width: 100%;
  }
  .form-input {
    width: 100% !important;
  }
  .action-col {
    text-align: left;
    padding: 16px 0 0 0;
  }
}
/* 添加一些样式来美化编辑状态 */
.ivu-table-cell {
  position: relative;
}

.edit-icon {
  opacity: 0;
  transition: opacity 0.2s;
}

.ivu-table-row:hover .edit-icon {
  opacity: 1;
}
.mr5 {
  margin-right: 5px;
}
</style>
