<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { salaryRecordApi, employeeProfileApi } from '@/api/hr.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const employees = ref([])

const searchForm = reactive({ year_month: '', status: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  id: null, user_id: '', year_month: '',
  base_salary: 0, position_salary: 0, performance: 0,
  overtime_pay: 0, subsidy: 0,
  social_insurance: 0, housing_fund: 0, tax: 0,
  absence_deduction: 0, other_deduction: 0,
  actual_amount: 0
})
const isEdit = ref(false)
const autoCompute = ref(true)

const formRules = {
  user_id: [{ required: true, message: '请选择员工', trigger: 'change' }],
  year_month: [{ required: true, message: '请输入工资月份', trigger: 'blur' }]
}

const statusMap = { 0: '待确认', 1: '已确认', 2: '已发放' }
const statusType = { 0: 'warning', 1: 'primary', 2: 'success' }

const computedActual = computed(() => {
  const income = Number(form.base_salary || 0)
    + Number(form.position_salary || 0)
    + Number(form.performance || 0)
    + Number(form.overtime_pay || 0)
    + Number(form.subsidy || 0)
  const deduction = Number(form.social_insurance || 0)
    + Number(form.housing_fund || 0)
    + Number(form.tax || 0)
    + Number(form.absence_deduction || 0)
    + Number(form.other_deduction || 0)
  return Math.round((income - deduction) * 100) / 100
})

watch(computedActual, (val) => {
  if (autoCompute.value) form.actual_amount = val
})

function getDeductionTotal(row) {
  return Number(row.social_insurance || 0)
    + Number(row.housing_fund || 0)
    + Number(row.tax || 0)
    + Number(row.absence_deduction || 0)
    + Number(row.other_deduction || 0)
}

async function fetchList() {
  loading.value = true
  try {
    const res = await salaryRecordApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

async function fetchEmployees() {
  try {
    const res = await employeeProfileApi.getList({ per_page: 500 })
    employees.value = res.data?.list || res.data?.data || []
  } catch {}
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { year_month: '', status: '' }); handleSearch() }

const defaultForm = {
  id: null, user_id: '', year_month: '',
  base_salary: 0, position_salary: 0, performance: 0,
  overtime_pay: 0, subsidy: 0,
  social_insurance: 0, housing_fund: 0, tax: 0,
  absence_deduction: 0, other_deduction: 0,
  actual_amount: 0
}

function handleAdd() {
  isEdit.value = false; autoCompute.value = true
  Object.assign(form, { ...defaultForm })
  dialogVisible.value = true
}

async function handleEdit(row) {
  if (row.status !== 0) { ElMessage.warning('只能编辑待确认记录'); return }
  isEdit.value = true; autoCompute.value = false
  const res = await salaryRecordApi.getDetail(row.id)
  const d = res.data
  Object.assign(form, {
    id: d.id, user_id: d.user_id, year_month: d.year_month,
    base_salary: d.base_salary || 0, position_salary: d.position_salary || 0,
    performance: d.performance || 0, overtime_pay: d.overtime_pay || 0,
    subsidy: d.subsidy || 0, social_insurance: d.social_insurance || 0,
    housing_fund: d.housing_fund || 0, tax: d.tax || 0,
    absence_deduction: d.absence_deduction || 0, other_deduction: d.other_deduction || 0,
    actual_amount: d.actual_amount || 0
  })
  autoCompute.value = true
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await salaryRecordApi.update(form.id, form); ElMessage.success('更新成功') }
      else { await salaryRecordApi.create(form); ElMessage.success('创建成功') }
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  if (row.status !== 0) { ElMessage.warning('只能删除待确认记录'); return }
  await ElMessageBox.confirm('确定删除该工资记录吗？', '删除确认', { type: 'warning' })
  await salaryRecordApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

async function handleConfirm(row) {
  await ElMessageBox.confirm('确认该工资记录？确认后不可编辑。', '确认操作', { type: 'warning' })
  await salaryRecordApi.confirm(row.id); ElMessage.success('确认成功'); fetchList()
}

async function handlePay(row) {
  await ElMessageBox.confirm('确定标记为已发放吗？', '发放确认', { type: 'warning' })
  await salaryRecordApi.pay(row.id); ElMessage.success('发放成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => { fetchList(); fetchEmployees() })
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input v-model="searchForm.year_month" placeholder="工资月份 (如 2024-03)" style="width:200px" clearable @keydown.enter="handleSearch" />
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">工资记录列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增工资记录</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column label="员工" min-width="100">
            <template #default="{ row }">{{ row.user?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="year_month" label="工资月份" width="110" align="center" />
          <el-table-column prop="base_salary" label="基本工资" width="110" align="right" />
          <el-table-column prop="position_salary" label="岗位工资" width="110" align="right" />
          <el-table-column prop="performance" label="绩效" width="100" align="right" />
          <el-table-column prop="overtime_pay" label="加班费" width="100" align="right" />
          <el-table-column prop="subsidy" label="补贴" width="90" align="right" />
          <el-table-column label="扣除合计" width="110" align="right">
            <template #default="{ row }">{{ getDeductionTotal(row).toFixed(2) }}</template>
          </el-table-column>
          <el-table-column label="实发金额" width="120" align="right">
            <template #default="{ row }"><span style="font-weight:700">{{ row.actual_amount }}</span></template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }"><el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] }}</el-tag></template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status===0" size="small" type="success" text @click="handleConfirm(row)">确认</el-button>
              <el-button v-if="row.status===1" size="small" type="success" text @click="handlePay(row)">发放</el-button>
              <el-button v-if="row.status===0" size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button v-if="row.status===0" size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,20,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑工资记录' : '新增工资记录'" width="750px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="员工" prop="user_id">
              <el-select v-model="form.user_id" placeholder="选择员工" filterable style="width:100%">
                <el-option v-for="e in employees" :key="e.id" :label="e.user?.name || e.name || `员工${e.id}`" :value="e.user_id || e.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工资月份" prop="year_month">
              <el-input v-model="form.year_month" placeholder="如 2024-03" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="基本工资">
              <el-input-number v-model="form.base_salary" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="岗位工资">
              <el-input-number v-model="form.position_salary" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="绩效">
              <el-input-number v-model="form.performance" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="加班费">
              <el-input-number v-model="form.overtime_pay" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="补贴">
              <el-input-number v-model="form.subsidy" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24"><el-divider content-position="left">扣除项</el-divider></el-col>
          <el-col :span="8">
            <el-form-item label="社保">
              <el-input-number v-model="form.social_insurance" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公积金">
              <el-input-number v-model="form.housing_fund" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="个税">
              <el-input-number v-model="form.tax" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="缺勤扣款">
              <el-input-number v-model="form.absence_deduction" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="其他扣款">
              <el-input-number v-model="form.other_deduction" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24"><el-divider /></el-col>
          <el-col :span="12">
            <el-form-item label="实发金额">
              <el-input-number v-model="form.actual_amount" :precision="2" style="width:100%" />
              <div style="font-size:12px;color:var(--color-text-secondary)">自动计算：收入合计 - 扣除合计 = {{ computedActual.toFixed(2) }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
