<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择部门" filterable style="width: 240px" @change="handleQuery">
          <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="月份范围">
        <el-date-picker
          v-model="monthRange[0]"
          type="month"
          value-format="YYYYMM"
          placeholder="起始月份"
          style="width: 150px"
        />
        <span class="el-range-separator" style="margin: 0 5px">-</span>
        <el-date-picker
          v-model="monthRange[1]"
          type="month"
          value-format="YYYYMM"
          placeholder="结束月份"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 报表表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      :row-class-name="tableRowClassName"
      style="width: 100%"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column label="部门" prop="deptName" align="center" width="120" fixed />
      <el-table-column label="项目名称" prop="projectName" align="left" min-width="180" fixed />
      <el-table-column label="项目编号" prop="projectCode" align="center" width="150" fixed />

      <!-- 汇总列 -->
      <el-table-column label="汇总" prop="rowTotal" align="center" width="80">
        <template #default="scope">
          {{ Number(scope.row.rowTotal) === 0 ? '' : Number(scope.row.rowTotal).toFixed(1) }}
        </template>
      </el-table-column>

      <!-- 动态人员列 -->
      <el-table-column v-for="col in columns" :key="col.prop" :label="col.label" :prop="col.prop" align="center" width="80">
        <template #default="scope">
          {{ formatHours(scope.row[col.prop]) }}
        </template>
      </el-table-column>

      <!-- 备注列 (跨部门) -->
      <el-table-column label="备注" prop="remark" align="center" width="100" fixed="right">
        <template #default="scope">
          <span v-if="scope.row.isCrossDept" style="color: black; font-weight: bold">跨部门</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部统计 -->
  </div>
</template>

<script setup name="ProjectPersonnelReport" lang="ts">
import { allListDept } from '@/api/system/dept';
import { getProjectPersonnelReport } from '@/api/oa/erp/timesheetReport';
import { FormInstance } from 'element-plus';
import { ComponentInternalInstance } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(false);
const showSearch = ref(true);
const deptOptions = ref<any[]>([]);
const monthRange = ref<[string, string]>(['', '']);
const queryRef = ref<FormInstance>();

const columns = ref<Array<{ label: string; prop: string }>>([]);
const tableData = ref<Array<any>>([]);

const queryParams = ref({
  deptId: undefined
});

/** 获取部门 */
const getDeptList = async () => {
  const res = await allListDept({ deptCategory: '03' } as any);
  deptOptions.value = res.data;
};

/** 查询报表 */
const getList = async () => {
  if (!queryParams.value.deptId) {
    proxy?.$modal.msgWarning('请选择部门');
    return;
  }
  loading.value = true;
  const params = {
    deptId: queryParams.value.deptId,
    startTime: monthRange.value[0],
    endTime: monthRange.value[1]
  };

  try {
    const res = await getProjectPersonnelReport(params);
    if (res.data) {
      columns.value = res.data.columns || [];
      tableData.value = res.data.rows || [];
    } else {
      tableData.value = [];
      columns.value = [];
    }
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  monthRange.value = ['', ''];
  handleQuery();
};

const handleExport = () => {
  proxy?.download(
    'oa/erp/timesheetReport/exportProjectPersonnel',
    {
      deptId: queryParams.value.deptId,
      startTime: monthRange.value[0],
      endTime: monthRange.value[1]
    },
    `项目人员工时统计报表_${new Date().getTime()}.xlsx`
  );
};

/** 行样式 */
const tableRowClassName = ({ row }: { row: any }) => {
  if (row.isCrossDept) {
    return 'warning-row';
  }
  return '';
};

/** 格式化工时 */
const formatHours = (val: any) => {
  if (val === undefined || val === null || val === '' || Number(val) === 0) return '';
  return Number(val).toFixed(1);
};

/** 合计行逻辑 */
const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: string[] = [];

  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '总计';
      return;
    }
    // 项目名称、编号、备注不统计
    if (['projectName', 'projectCode', 'remark', 'deptName'].includes(column.property)) {
      sums[index] = '';
      return;
    }

    // 计算列总和
    const values = data.map((item: any) => Number(item[column.property]));
    if (!values.every((value: any) => Number.isNaN(value))) {
      const sum = values.reduce((prev: any, curr: any) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
      sums[index] = sum === 0 ? '' : sum.toFixed(1);
    } else {
      sums[index] = '';
    }
  });

  return sums;
};



onMounted(() => {
  getDeptList();
});
</script>

<style scoped>
:deep(.warning-row) {
  background-color: #fcf6ec;
  /* Element Plus Warning Light Color or Custom Yellow */
  background-color: #ffffcc !important;
}
</style>
