<template>
  <div class="hrm-page">
    <section class="hero">
      <div>
        <h2>HRM 工作台</h2>
        <p class="subtitle">汇总视图 · 快速进入各子模块</p>
        <div class="entry-actions">
          <router-link to="/hrm/org">
            <el-button type="info" plain icon="el-icon-s-custom">组织与员工</el-button>
          </router-link>
          <router-link to="/hrm/attendance">
            <el-button type="warning" plain icon="el-icon-s-flag">考勤与排班</el-button>
          </router-link>
          <router-link to="/hrm/requests">
            <el-button type="primary" icon="el-icon-s-claim">申请与审批</el-button>
          </router-link>
          <router-link to="/hrm/payroll">
            <el-button type="success" plain icon="el-icon-coin">薪酬与指标</el-button>
          </router-link>
          <router-link to="/oa/taskHistory">
    <el-button type="default" plain icon="el-icon-tickets">审批历史</el-button>
  </router-link>
        </div>
      </div>
      <div class="hero-stat">
        <div class="stat-card" v-for="card in heroStats" :key="card.key">
          <div class="label">{{ card.label }}</div>
          <div class="value">{{ card.value }}</div>
          <div class="desc">{{ card.desc }}</div>
        </div>
      </div>
    </section>

    <section class="panel-grid">
      <el-card class="metal-panel" shadow="hover">
        <div slot="header" class="panel-header">
          <span>我的待办</span>
          <el-button size="mini" icon="el-icon-refresh" @click="loadTodo">刷新</el-button>
        </div>
        <el-table :data="todoList" height="320" v-loading="todoLoading" stripe>
          <el-table-column label="任务" prop="taskId" min-width="120">
            <template slot-scope="scope">
              <span class="pill">{{ scope.row.taskId }}</span>
              <span class="muted">实例: {{ scope.row.instId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="节点" prop="nodeId" min-width="120" />
          <el-table-column label="状态" prop="status" min-width="100">
            <template slot-scope="scope">
              <el-tag :type="statusType(scope.row.status)">{{ scope.row.status || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="到期" prop="expireTime" min-width="140">
            <template slot-scope="scope">{{ formatDate(scope.row.expireTime) }}</template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" min-width="160" show-overflow-tooltip />
        </el-table>
      </el-card>

      <el-card class="metal-panel" shadow="hover">
        <div slot="header" class="panel-header">
          <span>流程历史</span>
          <div class="actions-inline">
            <el-input v-model="flowQuery.instId" placeholder="实例ID" size="mini" style="width: 160px" clearable
              @keyup.enter.native="loadFlowActions" />
            <el-button size="mini" type="primary" @click="loadFlowActions">查询</el-button>
          </div>
        </div>
        <el-table :data="flowActions" height="320" v-loading="flowLoading" stripe>
          <el-table-column label="动作" prop="action" min-width="120">
            <template slot-scope="scope">
              <el-tag size="small" type="info">{{ scope.row.action }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="执行人" prop="actionUserId" min-width="120" />
          <el-table-column label="备注" prop="remark" min-width="180" show-overflow-tooltip />
          <el-table-column label="时间" prop="createTime" min-width="160">
            <template slot-scope="scope">{{ formatDate(scope.row.createTime) }}</template>
          </el-table-column>
        </el-table>
      </el-card>
    </section>

    <section class="panel-grid triple">
      <el-card class="metal-panel mini" shadow="hover">
        <div slot="header" class="panel-header">
          <span>组织与员工概览</span>
          <router-link to="/hrm/org"><el-button size="mini" type="text">进入</el-button></router-link>
        </div>
        <ul class="summary-list">
          <li><span>组织数量</span><strong>{{ summary.orgCount }}</strong></li>
          <li><span>员工数量</span><strong>{{ summary.empCount }}</strong></li>
          <li><span>在职员工</span><strong>{{ summary.activeEmp }}</strong></li>
        </ul>
      </el-card>

      <el-card class="metal-panel mini" shadow="hover">
        <div slot="header" class="panel-header">
          <span>考勤与排班概览</span>
          <router-link to="/hrm/attendance"><el-button size="mini" type="text">进入</el-button></router-link>
        </div>
        <ul class="summary-list">
          <li><span>班次</span><strong>{{ summary.shiftCount }}</strong></li>
          <li><span>排班记录</span><strong>{{ summary.scheduleCount }}</strong></li>
          <li><span>异常考勤</span><strong class="error">{{ summary.attendException }}</strong></li>
        </ul>
      </el-card>

      <el-card class="metal-panel mini" shadow="hover">
        <div slot="header" class="panel-header">
          <span>申请与审批概览</span>
          <router-link to="/hrm/requests"><el-button size="mini" type="text">进入</el-button></router-link>
        </div>
        <ul class="summary-list">
          <li><span>请假单</span><strong>{{ summary.leaveCount }}</strong></li>
          <li><span>加班单</span><strong>{{ summary.otCount }}</strong></li>
          <li><span>待审批</span><strong class="warning">{{ summary.pendingReq }}</strong></li>
        </ul>
      </el-card>

      <el-card class="metal-panel mini" shadow="hover">
        <div slot="header" class="panel-header">
          <span>薪酬与指标概览</span>
          <router-link to="/hrm/payroll"><el-button size="mini" type="text">进入</el-button></router-link>
        </div>
        <ul class="summary-list">
          <li><span>薪酬方案</span><strong>{{ summary.planCount }}</strong></li>
          <li><span>批次</span><strong>{{ summary.runCount }}</strong></li>
          <li><span>工资条</span><strong>{{ summary.payslipCount }}</strong></li>
        </ul>
      </el-card>
    </section>
  </div>
</template>

<script>
import {
  listAttendCalc,
  listEmployee,
  listFlowAction,
  listLeaveReq,
  listOrg,
  listSchedule,
  listShift,
  listTodoFlowTask
} from '@/api/hrm';

export default {
  name: 'HrmWorkbench',
  data () {
    return {
      heroStats: [
        { key: 'todo', label: '待办', value: '—', desc: '待处理任务' },
        { key: 'employee', label: '员工', value: '—', desc: '在册人数' },
        { key: 'attendance', label: '考勤', value: '—', desc: '本周异常' }
      ],
      summary: {
        orgCount: 0,
        empCount: 0,
        activeEmp: 0,
        shiftCount: 0,
        scheduleCount: 0,
        attendException: 0,
        leaveCount: 0,
        otCount: 0,
        pendingReq: 0,
        planCount: 0,
        runCount: 0,
        payslipCount: 0
      },
      todoList: [],
      todoLoading: false,
      flowActions: [],
      flowLoading: false,
      flowQuery: { instId: '' }
    }
  },
  created () {
    this.loadTodo()
    this.loadFlowActions()
    this.loadSummary()
  },
  methods: {
    statusType (status) {
      if (!status) return 'info'
      const map = {
        pending: 'warning',
        draft: 'info',
        approved: 'success',
        rejected: 'danger',
        active: 'success',
        inactive: 'info'
      }
      return map[status] || 'info'
    },
    formatDate (val) {
      if (!val) return ''
      const date = new Date(val)
      const pad = n => (n < 10 ? `0${n}` : n)
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
    },
    loadTodo () {
      this.todoLoading = true
      listTodoFlowTask()
        .then(res => {
          this.todoList = res.data || []
          this.heroStats.find(i => i.key === 'todo').value = this.todoList.length
        })
        .catch(err => {
          console.error('加载待办任务失败:', err)
          this.$message.error('加载待办任务失败，可能是超管用户无角色导致')
          this.todoList = []
          this.heroStats.find(i => i.key === 'todo').value = 0
        })
        .finally(() => {
          this.todoLoading = false
        })
    },
    loadFlowActions () {
      if (this.flowQuery.instId && !/^\d+$/.test(this.flowQuery.instId)) {
        this.$message.warning('实例ID需为数字')
        return
      }
      this.flowLoading = true
      listFlowAction({ pageNum: 1, pageSize: 10, instId: this.flowQuery.instId })
        .then(res => {
          this.flowActions = res.rows || res.data || []
        })
        .catch(err => {
          console.error('加载流程历史失败:', err)
          this.$message.error('加载流程历史失败')
          this.flowActions = []
        })
        .finally(() => {
          this.flowLoading = false
        })
    },
    async loadSummary () {
      try {
        const [orgRes, empRes, shiftRes, scheduleRes, attendRes, leaveRes, otRes, planRes, runRes, payslipRes] =
          await Promise.all([
            listOrg({ pageNum: 1, pageSize: 999 }),
            listEmployee({ pageNum: 1, pageSize: 999 }),
            listShift({ pageNum: 1, pageSize: 200 }),
            listSchedule({ pageNum: 1, pageSize: 200 }),
            listAttendCalc({ pageNum: 1, pageSize: 200 }),
            listLeaveReq({ pageNum: 1, pageSize: 200 }),
            // listPayPlan({ pageNum: 1, pageSize: 200 }),
            // listPayRun({ pageNum: 1, pageSize: 200 }),
            // listPayslip({ pageNum: 1, pageSize: 200 })
          ])
        const orgs = orgRes.rows || []
        const emps = empRes.rows || []
        const shifts = shiftRes.rows || []
        const schedules = scheduleRes.rows || []
        const attends = attendRes.rows || []
        const leaves = leaveRes.rows || []
        const ots = otRes.rows || []
        const plans = planRes.rows || []
        const runs = runRes.rows || []
        const payslips = payslipRes.rows || []

        this.summary.orgCount = orgs.length
        this.summary.empCount = emps.length
        this.summary.activeEmp = emps.filter(e => e.status === 'active').length
        this.summary.shiftCount = shifts.length
        this.summary.scheduleCount = schedules.length
        this.summary.attendException = attends.filter(a => a.exceptionMsg).length
        this.summary.leaveCount = leaves.length
        this.summary.otCount = ots.length
        this.summary.pendingReq = [...leaves, ...ots].filter(i => i.status === 'pending').length
        this.summary.planCount = plans.length
        this.summary.runCount = runs.length
        this.summary.payslipCount = payslips.length
        this.heroStats.find(i => i.key === 'employee').value = this.summary.empCount
        this.heroStats.find(i => i.key === 'attendance').value = this.summary.attendException
      } catch (err) {
        console.error('加载汇总数据失败:', err)
        // 静默失败，不影响页面显示
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.hrm-page {
  padding: 16px 20px 32px;
  background: #f8f9fb;
}

.hero {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: linear-gradient(90deg, #fafafa 0%, #ffffff 100%);
  border: 1px solid #e6e8ed;
  border-radius: 12px;
  padding: 18px 22px;
  margin-bottom: 18px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.03);

  h2 {
    margin: 0;
    font-weight: 700;
    color: #303133;
  }

  .subtitle {
    margin: 8px 0 12px;
    color: #606266;
  }
}

.entry-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.hero-stat {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  min-width: 340px;
}

.stat-card {
  background: #fff;
  border: 1px solid #e6e8ed;
  border-radius: 8px;
  padding: 12px;
  min-width: 90px;

  .label {
    color: #909399;
    font-size: 12px;
  }

  .value {
    font-size: 22px;
    font-weight: 700;
    color: #1f2d3d;
    margin: 4px 0;
  }

  .desc {
    color: #a0a3ad;
    font-size: 12px;
  }
}

.panel-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 14px;

  &.triple {
    grid-template-columns: repeat(3, 1fr);
  }
}

.metal-panel {
  border: 1px solid #d7d9df;
  border-radius: 10px;
  background: #fff;
}

.metal-panel.mini {
  min-height: 180px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.actions-inline {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pill {
  display: inline-block;
  padding: 2px 8px;
  background: #f4f5f7;
  border-radius: 12px;
  margin-right: 6px;
}

.muted {
  color: #a0a3ad;
  font-size: 12px;
}

.summary-list {
  list-style: none;
  margin: 0;
  padding: 0 4px;

  li {
    display: flex;
    justify-content: space-between;
    padding: 6px 0;
    color: #606266;

    strong {
      color: #303133;
    }

    .error {
      color: #e76f51;
    }

    .warning {
      color: #e6a23c;
    }
  }
}

@media (max-width: 1200px) {

  .panel-grid,
  .panel-grid.triple {
    grid-template-columns: 1fr;
  }
}
</style>
