<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" 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 }">
            <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 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="请输入部门名称或ID" style="width: 150px" />
            </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>
      </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>
        <Table :data="detailModal.approvals" size="small" border>
          <TableColumn title="节点" key="node_index" />
          <TableColumn title="审批人" key="approver_name" />
          <TableColumn title="结果" key="approver_result" :render="renderApproveResult" />
          <TableColumn title="时间" key="approver_time" />
          <TableColumn title="意见" key="comment" />
        </Table>
      </div>
      <div slot="footer"><Button type="primary" @click="detailModal.visible=false">关闭</Button></div>
    </Modal>
  </div>
</template>

<script>
import {
  getLeaveList,
  saveLeaveApplication,
  submitLeaveApplication,
  revokeLeaveApplication,
  getPendingList,
  approveLeave,
  rejectLeave,
  getApprovalHistory,
  getLeaveStats,
  getLeaveById
} from '@/api/key-dm-leave'
import { getDictList } from '@/api/common'

export default {
  name: 'key-dm-leave-index',
  data () {
    return {
      activeTab: 'apply',
      filters: { apply: { name: '' } },
      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' },
        { 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' },
        { 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' }
      ],
      applyModal: { visible: false, isEdit: false, saving: false, form: {} },
      approveModal: { visible: false, record: {}, comment: '', submitting: false },
      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')
  },
  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: getLeaveList, 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 || {}
          if (tab === 'history') this.tables.history = data.results || []
          else if (tab === 'pending') this.tables.pending = data.results || []
          else if (tab === 'query') this.tables.query = data.results || []
          else this.tables.apply = 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) },
    loadLeaveTypes () {
      getDictList({ type: 'leave_type' }).then(res => {
        let list = res.data
        if (list) {
          list = (res.data.data || res.data.results) || []
        }
        this.leaveTypes = Array.isArray(list) ? list.map(it => ({ id: it.value || it.dictValue, type_name: it.label || it.name })) : []
      })
    },
    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: '' }
      this.applyModal.visible = true
    },
    openEdit (row) {
      this.applyModal.isEdit = true
      this.applyModal.form = Object.assign({}, row)
      this.applyModal.visible = true
    },
    saveApply () {
      this.applyModal.saving = true
      saveLeaveApplication(this.applyModal.form).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
    },
    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) {
          this.detailModal.data = ret.data.data || {}
          this.detailModal.approvals = ret.data.data.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) {
          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; }
</style>
