<template>
  <div class="key-dm-leave-wrapper">
    <Tabs v-model="activeTab" @on-click="handleTabChange" class="tabsCls">
      <TabPane label="请假申请" name="apply">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="8">
              <span>姓名：</span>
              <Input v-model="filters.apply.name" placeholder="请输入姓名" style="width: 60%" />
            </Col>
            <Col span="8">
              <span>审批人：</span>
              <Select v-model="selectedApprovalUser" style="width: 60%">
                <Option v-for="opt in leaveApprovalOptions" :key="opt.id" :value="opt.id">{{ opt.name }}</Option>
              </Select>
            </Col>
            <Col span="8" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('apply')">搜索</Button>
              <Button class="mr10" @click="handleReset('apply')">重置</Button>
              <Button type="success" @click="openApplyModal">申请</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.apply" :columns="applyColumns" :data="tables.apply">
          <template slot="action" slot-scope="{ row }">
            <Button size="small" @click="openDetail(row)">详细</Button>
            <Button size="small" type="primary" class="mr5" @click="openEdit(row)" v-if="canEdit(row)">修改</Button>
            <Button size="small" type="success" class="mr5" @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 border :loading="loading.pending" :columns="pendingColumns" :data="tables.pending">
          <template slot="action" slot-scope="{ row }">
            <div class="action-buttons">
              <Button size="small" type="primary" @click="openApproveModal(row)">处理</Button>
              <Button size="small" class="mr5" @click="openTransferModal(row)" v-if="canTransfer(row)">转审核</Button>
            </div>
          </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 border :loading="loading.history" :columns="historyColumns" :data="tables.history">
          <template slot="action" slot-scope="{ row }">
            <Button size="small" @click="openHistoryDetail(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>

      <TabPane label="请假申请查询" name="query">
        <Table border :loading="loading.query" :columns="queryColumns" :data="tables.query">
          <template slot="action" slot-scope="{ row }">
            <Button size="small" @click="openDetail(row)">详细</Button>
          </template>
        </Table>
        <Page class="page_style" :total="pagers.query.totalRecord" :current="pagers.query.pageNo" :page-size="pagers.query.pageSize"
          show-total show-sizer @on-change="pageChange('query', $event)" @on-page-size-change="sizeChange('query', $event)" />
      </TabPane>

      <TabPane label="请假统计" name="stats">
        <div class="search-div">
          <Row type="flex" :gutter="16" align="middle">
            <Col span="16">
              <span>开始：</span>
              <DatePicker v-model="statsStart" type="date" placeholder="开始日期" style="min-width:110px;margin-right:20px" />
              <span>结束：</span>
              <DatePicker v-model="statsEnd" type="date" placeholder="结束日期" style="min-width:110px;margin-right:20px" />
              <span>部门：</span>
              <Input v-model="statsDept" placeholder="请输入部门名称" style="width:65%" />
            </Col>
            <Col span="8" class="text-right">
              <Button type="primary" class="mr10" @click="loadStats">统计</Button>
              <Button @click="resetStats">重置</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.stats" :columns="statsColumns" :data="tables.stats" />
      </TabPane>
    </Tabs>

    <!-- 申请弹窗 -->
    <Modal v-model="applyModal.visible" :title="applyModal.isEdit ? '修改请假' : '新增请假'" width="700">
      <Form :model="applyModal.form" :label-width="120" ref="applyForm">
        <FormItem label="请假类型" prop="leave_type_id">
          <Select v-model="applyModal.form.leave_type_id" style="width: 60%">
            <Option v-for="opt in leaveTypes" :key="opt.id" :value="opt.id">{{ opt.type_name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="开始时间" prop="start_time">
          <DatePicker v-model="applyModal.form.start_time" type="datetime" placeholder="请选择开始时间" />
        </FormItem>
        <FormItem label="结束时间" prop="end_time">
          <DatePicker v-model="applyModal.form.end_time" type="datetime" placeholder="请选择结束时间" />
        </FormItem>
        <FormItem label="请假事由" prop="reason">
          <Input type="textarea" v-model="applyModal.form.reason" :rows="3" />
        </FormItem>
        <FormItem label="紧急联系人">
          <Input v-model="applyModal.form.emergency_contact" />
        </FormItem>
        <FormItem label="紧急电话">
          <Input v-model="applyModal.form.emergency_phone" />
        </FormItem>
        <FormItem label="指定审批人" prop="approver_id">
          <Select v-model="applyModal.form.approver_id" style="width: 60%">
            <Option v-for="opt in leaveApprovalOptions" :key="opt.id" :value="opt.id">{{ opt.name }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="applyModal.visible = false">取消</Button>
        <Button type="primary" :loading="applyModal.saving" @click="saveApply">保存</Button>
      </div>
    </Modal>

    <!-- 审核弹窗 -->
    <Modal v-model="approveModal.visible" title="请假审批" width="700">
      <Form :model="approveModal.record" :label-width="120">
        <FormItem label="申请人">
          <span>{{ approveModal.record.user_name }}</span>
        </FormItem>
        <FormItem label="请假类型">
          <span>{{ approveModal.record.leave_type_name }}</span>
        </FormItem>
        <FormItem label="起止时间">
          <span>{{ formatDatetime(approveModal.record.start_time) }} - {{ formatDatetime(approveModal.record.end_time) }}</span>
        </FormItem>
        <FormItem label="请假事由">
          <span>{{ approveModal.record.reason }}</span>
        </FormItem>
        <FormItem label="审批意见" prop="comment">
          <Input type="textarea" v-model="approveModal.comment" :rows="3" 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.user_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.leave_type_name || '-' }}</p></Col></Row>
        <Row class="mt8"><Col span="24"><p><strong>起止时间：</strong>{{ formatDatetime(detailModal.data.start_time) }} - {{ formatDatetime(detailModal.data.end_time) }}</p></Col></Row>
        <Row class="mt8"><Col span="24"><p><strong>请假事由：</strong>{{ detailModal.data.reason || '-' }}</p></Col></Row>
        <Row class="mt8"><Col span="24"><h4>审批记录</h4></Col></Row>
        <div>
          <!-- 详情表格：使用预先定义的列配置渲染 approvals -->
          <Table :data="detailModal.approvals" :columns="detailApprovalColumns" size="small" border />
        </div>
      </div>
      <div slot="footer"><Button type="primary" @click="detailModal.visible=false">关闭</Button></div>
    </Modal>

    <!-- 转审核弹窗 -->
    <Modal v-model="transferModal.visible" title="转审核" width="520">
      <Form :model="transferModal" :label-width="120">
        <FormItem label="选择审批人" prop="approver_id">
          <Select v-model="transferModal.selectedApprover" style="width: 60%">
            <Option v-for="opt in leaveApprovalOptions" :key="opt.id" :value="opt.id">{{ opt.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="备注（可选）">
          <Input type="textarea" v-model="transferModal.comment" :rows="3" placeholder="转交备注（选填）" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="transferModal.visible = false">取消</Button>
        <Button type="primary" :loading="transferModal.processing" @click="confirmTransfer">确定转交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  getLeaveList,
  getLeaveListByUserId,
  saveLeaveApplication,
  submitLeaveApplication,
  revokeLeaveApplication,
  getPendingList,
  approveLeave,
  rejectLeave,
  getApprovalHistory,
  getLeaveStats,
  getLeaveById,
  getLeaveTypeList
} from '@/api/key-dm-leave'
import { transferLeaveApproval } from '@/api/key-dm-leave'
import { getLeaveApprovalPermission } from '@/api/key-dm-user-permission'

export default {
  name: 'key-dm-leave-index',
  data () {
    return {
      activeTab: 'apply',
      filters: { apply: { name: '' } },
      // 下拉：请假审核权限可选人员
      leaveApprovalOptions: [],
      selectedApprovalUser: '',
      tables: { apply: [], pending: [], history: [], query: [], stats: [] },
      pagers: { apply: { pageNo: 1, pageSize: 10, totalRecord: 0 }, pending: { pageNo: 1, pageSize: 10, totalRecord: 0 }, history: { pageNo: 1, pageSize: 10, totalRecord: 0 }, query: { pageNo: 1, pageSize: 10, totalRecord: 0 } },
      loading: { apply: false, pending: false, history: false, query: false, stats: false },
      leaveTypes: [],
      applyColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '申请人', key: 'user_name', align: 'center' },
        { title: '部门', key: 'department_name', align: 'center' },
        { title: '请假类型', key: 'leave_type_name', align: 'center' },
        { title: '起止时间', key: 'start_time', align: 'center', render: (h, { row }) => h('span', `${row.start_time || '-'} ~ ${row.end_time || '-'}`) },
        { title: '时长', key: 'duration', align: 'center' },
        { title: '状态', key: 'status', align: 'center', render: (h, { row }) => h('span', this.mapStatusText(row.status)) },
        { title: '操作', slot: 'action', align: 'center', width: 320 }
      ],
      pendingColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '申请人', key: 'user_name', align: 'center' },
        { title: '请假类型', key: 'leave_type_name', align: 'center' },
        { title: '起止时间', key: 'start_time', align: 'center' },
        { title: '提交时间', key: 'submit_time', align: 'center' },
        { title: '操作', slot: 'action', align: 'center', width: 120 }
      ],
      historyColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '申请人', key: 'user_name', align: 'center' },
        { title: '请假类型', key: 'leave_type_name', align: 'center' },
        { title: '起止时间', key: 'start_time', align: 'center' },
        { title: '审批完成时间', key: 'approval_complete_time', align: 'center' },
        { title: '操作', slot: 'action', align: 'center', width: 100 }
      ],
      queryColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '申请人', key: 'user_name', align: 'center' },
        { title: '状态', key: 'status', align: 'center', render: (h, { row }) => h('span', this.mapStatusText(row.status)) },
        { title: '提交时间', key: 'submit_time', align: 'center' },
        { title: '操作', slot: 'action', align: 'center', width: 100 }
      ],
      statsColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '人员', key: 'user_name', align: 'center' },
        { title: '部门', key: 'department_name', align: 'center' },
        { title: '已通过天数', key: 'passed_days', align: 'center' }
      ],
      detailApprovalColumns: [
        { title: '节点', key: 'node_index', align: 'center' },
        { title: '审批人', key: 'approver_name', align: 'center' },
        { title: '结果', key: 'approver_result', align: 'center', render: (h, { row }) => h('span', this.renderApproveResult(h, { row })) },
        { title: '时间', key: 'approver_time', align: 'center' },
        { title: '意见', key: 'comment', align: 'center' }
      ],
      applyModal: { visible: false, isEdit: false, saving: false, form: {} },
      approveModal: { visible: false, record: {}, comment: '', submitting: false },
      transferModal: { visible: false, selectedApprover: '', comment: '', processing: false, record: {} },
      detailModal: { visible: false, loading: false, data: {}, approvals: [] },
      statsStart: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
      statsEnd: new Date(),
      statsDept: ''
    }
  },
  created () {
    this.loadLeaveTypes()
    this.fetchList('apply')
    this.loadLeaveApprovalOptions()
  },
  methods: {
    handleTabChange (name) {
      this.activeTab = name
      if (name === 'pending') this.fetchList('pending')
      if (name === 'history') this.fetchList('history')
      if (name === 'query') this.fetchList('query')
    },
    fetchList (tab) {
      const apiMap = { apply: getLeaveListByUserId, pending: getPendingList, history: getApprovalHistory, query: getLeaveList }
      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 || {}
          // 后端可能返回时间戳（毫秒）或不同格式，统一转换为可读字符串用于前端展示
          const normalizedResults = (data.results || []).map(item => {
            if (!item) return item
            if (Object.prototype.hasOwnProperty.call(item, 'start_time')) {
              item.start_time = this.formatDisplayDatetime(item.start_time)
            }
            if (Object.prototype.hasOwnProperty.call(item, 'end_time')) {
              item.end_time = this.formatDisplayDatetime(item.end_time)
            }
            // Normalize approver id/name from various backend key possibilities so the edit modal can reflect the selected approver
            item.approver_id = item.approver_id || item.approverId || item.transfer_to_id || item.transferToId || item.deal_user_id || item.dealUserId || ''
            item.approver_name = item.approver_name || item.approverName || item.transfer_to_name || item.transferToName || item.deal_user_name || item.dealUserName || item.update_name || item.update_by_name || ''
            return item
          })
          if (tab === 'history') this.tables.history = normalizedResults
          else if (tab === 'pending') this.tables.pending = normalizedResults
          else if (tab === 'query') this.tables.query = normalizedResults
          else this.tables.apply = normalizedResults
          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 })
    },
    /**
     * Map numeric approval status codes to human-readable text.
     * 0 => 未审批
     * 1 => 审核中
     * 9 => 审核通过
     * other => 显示原始值或通用占位
     */
    mapStatusText (status) {
      if (status === 0 || String(status) === '0') return '未审批'
      if (status === 1 || String(status) === '1') return '审核中'
      if (status === 9 || String(status) === '9') return '审核通过'
      if (status === -1 || String(status) === '-1') return '已驳回'
      if (status === null || status === undefined || status === '') return '-'
      return String(status)
    },
    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) },
    loadLeaveTypes () {
      getLeaveTypeList().then(res => {
        const data = res && res.data
        let results = []

        if (Array.isArray(data)) {
          results = data
        } else if (data) {
          if (Array.isArray(data.results)) results = data.results
          else if (Array.isArray(data.data)) results = data.data
          else if (data.data && Array.isArray(data.data.results)) results = data.data.results
        }

        // Map results into the shape used by the select
        this.leaveTypes = results.map(it => ({ id: it.id, type_name: it.type_name }))
      }).catch(err => {
        // 保持简洁的错误输出，避免抛出未捕获异常
        console.error('loadLeaveTypes error', err)
      })
      
    },
    loadLeaveApprovalOptions () {
      // 从后端获取有请假审批权限的机构/人员列表，并映射为 { id, name } 供 Select 使用
      getLeaveApprovalPermission().then(res => {
        const d = res && res.data
        let results = []
        if (Array.isArray(d)) results = d
        else if (d) {
          if (Array.isArray(d.results)) results = d.results
          else if (Array.isArray(d.data)) results = d.data
          else if (d.data && Array.isArray(d.data.results)) results = d.data.results
        }

        this.leaveApprovalOptions = (results || []).map(it => {
          return {
            id: it.user_id || it.id || it.userId || '',
            name: it.user_name || it.name || it.userName || it.nick || ''
          }
        })
      }).catch(err => {
        console.error('loadLeaveApprovalOptions error', err)
      })
    },
    formatForDbDatetime (val) {
      if (val === null || val === undefined || val === '') return val
      let d = val
      if (typeof val === 'string') {
        // 处理带 T 的 ISO 字符串或其他可解析字符串
        d = new Date(val)
      }
      if (!(d instanceof Date) || isNaN(d.getTime())) {
        // 如果无法解析，直接返回原值（后端可进一步校验）
        return val
      }
      const pad = (n) => (n < 10 ? '0' + n : String(n))
      return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' +
        pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds())
    },
    formatDisplayDatetime (val) {
      if (val === null || val === undefined || val === '') return '-'
      // 数字（毫秒）
      if (typeof val === 'number') return this.formatForDbDatetime(new Date(val))
      // 纯数字字符串（可能是时间戳）
      if (typeof val === 'string' && /^\d+$/.test(val)) {
        try { return this.formatForDbDatetime(new Date(Number(val))) } catch (e) { return val }
      }
      // ISO 字符串带 T
      if (typeof val === 'string' && val.includes('T')) return this.formatDatetime(val)
      // 尝试解析为 Date
      const parsed = new Date(val)
      if (!isNaN(parsed.getTime())) return this.formatForDbDatetime(parsed)
      return val
    },
    openApplyModal () {
      this.applyModal.isEdit = false
      this.applyModal.form = { user_id: '', user_name: '', leave_type_id: '', start_time: '', end_time: '', duration_unit: 2, duration: 0, reason: '', emergency_contact: '', emergency_phone: '', approver_id: this.selectedApprovalUser || '' }
      this.applyModal.visible = true
    },
    openEdit (row) {
      this.applyModal.isEdit = true
      this.applyModal.form = Object.assign({}, row)
      // ensure approver_id exists on form when editing
      if (!this.applyModal.form.approver_id) this.applyModal.form.approver_id = row.approver_id || row.approverId || row.transfer_to_id || ''
      this.applyModal.visible = true
    },
    saveApply () {
      this.applyModal.saving = true

      // 验证开始/结束时间：结束时间必须大于开始时间
      const form = this.applyModal.form || {}
      const parseToDate = (v) => {
        if (v === null || v === undefined || v === '') return null
        if (typeof v === 'number') return new Date(v)
        if (typeof v === 'string') {
          if (/^\d+$/.test(v)) return new Date(Number(v))
          // 把 "YYYY-MM-DD HH:mm:ss" 之类的字符串转换为可解析的 ISO 风格（替换第一个空格为'T'）
          const s = v.includes('T') ? v : v.replace(' ', 'T')
          const parsed = new Date(s)
          return isNaN(parsed.getTime()) ? null : parsed
        }
        if (v instanceof Date) return isNaN(v.getTime()) ? null : v
        const parsed = new Date(v)
        return isNaN(parsed.getTime()) ? null : parsed
      }
      const startDate = parseToDate(form.start_time)
      const endDate = parseToDate(form.end_time)
      if (startDate && endDate) {
        if (endDate.getTime() <= startDate.getTime()) {
          this.applyModal.saving = false
          this.$Message.warning('结束时间必须大于开始时间')
          return
        }
      }

      // 拷贝表单并格式化开始/结束时间为数据库 datetime 字符串
      const payload = Object.assign({}, this.applyModal.form)
      // 同时把审批人姓名一并传回后端（优先使用表单中的 approver_id，否则使用页面选中的 selectedApprovalUser）
      const approverId = payload.approver_id || this.selectedApprovalUser || ''
      const approverOption = (this.leaveApprovalOptions || []).find(opt => opt.id === approverId)
      payload.approver_name = approverOption ? approverOption.name : (payload.approver_name || '')
      if (payload.start_time) payload.start_time = this.formatForDbDatetime(payload.start_time)
      if (payload.end_time) payload.end_time = this.formatForDbDatetime(payload.end_time)

      saveLeaveApplication(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.status === 0 || row.status === -1 },
    canSubmit (row) { return row.status === 0 || row.status === -1 },
    canRevoke (row) { return row.status === 1 },
    submit (row) {
      this.$Modal.confirm({ title: '确认提交',
        content: '确认提交此请假申请进入审批流程？',
        onOk: () => {
          submitLeaveApplication({ 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) {
      revokeLeaveApplication({ 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.comment = ''
      this.approveModal.visible = true
    },
    canTransfer (row) {
      // 仅当当前为审批中（status === 1）时允许转交；可根据需求调整条件
      return row && (row.status === 1 || String(row.status) === '1')
    },
    openTransferModal (row) {
      this.transferModal.record = Object.assign({}, row)
      // 默认选择当前审批人（如果有）
      this.transferModal.selectedApprover = row.approver_id || row.approverId || row.transfer_to_id || ''
      this.transferModal.comment = ''
      this.transferModal.visible = true
    },
    confirmTransfer () {
      if (!this.transferModal.selectedApprover) {
        this.$Message.warning('请选择要转交的审批人')
        return
      }
      this.transferModal.processing = true
      const approverOption = (this.leaveApprovalOptions || []).find(opt => opt.id === this.transferModal.selectedApprover)
      const payload = {
        id: this.transferModal.record.id,
        approver_id: this.transferModal.selectedApprover,
        approver_name: approverOption ? approverOption.name : '',
        comment: this.transferModal.comment || ''
      }
      transferLeaveApproval(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('转交成功')
          this.transferModal.visible = false
          // 刷新待办列表
          this.fetchList('pending')
        } else {
          this.$Notice.error({ title: '转交失败', desc: ret.data && ret.data.errmsg })
        }
      }).finally(() => { this.transferModal.processing = false })
    },
    confirmApprove () {
      this.approveModal.submitting = true
      approveLeave({ id: this.approveModal.record.id, comment: this.approveModal.comment }).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 })
    },
    confirmReject () {
      if (!this.approveModal.comment || !this.approveModal.comment.trim()) { this.$Message.warning('请输入驳回原因'); return }
      this.approveModal.submitting = true
      rejectLeave({ id: this.approveModal.record.id, comment: this.approveModal.comment }).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
      getLeaveById({ id: row.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          const respData = ret.data.data || {}
          this.detailModal.data = respData
          // 优先使用 subTables 中的 approvalRecords（如果存在），否则使用 respData.approvals
          let approvals = []
          if (respData.subTables && Array.isArray(respData.subTables.approvalRecords)) {
            approvals = respData.subTables.approvalRecords.slice()
          } else {
            approvals = respData.approvals || []
          }
          if (!Array.isArray(approvals)) approvals = []
          approvals = approvals.map(item => {
            const nodeIndex = Number(item && (item.node_index || item.nodeIndex))
            return Object.assign({}, item, {
              node_index: isNaN(nodeIndex) ? 0 : nodeIndex,
              approver_time: this.formatDisplayDatetime(item ? item.approver_time : null),
              approver_name: item ? (item.approver_name || item.approverName || '') : ''
            })
          })
          approvals.sort((a, b) => (a.node_index || 0) - (b.node_index || 0))
          this.detailModal.approvals = approvals
        } else this.$Notice.error({ title: '查询失败', desc: ret.data && ret.data.errmsg })
      }).finally(() => { this.detailModal.loading = false })
    },
    openHistoryDetail (row) { this.openDetail(row) },
    renderApproveResult (h, { row }) { return row.approver_result === 1 ? '通过' : (row.approver_result === -1 ? '驳回' : '未处理') },
    formatDatetime (val) { if (!val) return '-'; return String(val).replace('T', ' ') },
    loadStats () {
      this.loading.stats = true
      const params = {
        start: this.statsStart,
        end: this.statsEnd,
        department: this.statsDept
      }
      getLeaveStats({ params }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          console.log("ret.data.data",ret.data.data)
          this.tables.stats = ret.data.data || []
        } else {
          this.$Notice.error({ title: '统计失败', desc: ret.data && ret.data.errmsg })
        }
      }).finally(() => { this.loading.stats = false })
    },
    resetStats () {
      this.statsStart = null
      this.statsEnd = null
      this.statsDept = ''
      this.tables.stats = []
    }
  }
}
</script>

<style scoped>
.key-dm-leave-wrapper { padding: 10px; min-height: 380px;}
.tabsCls { min-height: 380px;}
.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; }
.action-buttons { display: flex; align-items: center; gap: 8px; justify-content: center; }
</style>
