package com.sundot.airport.attendance.calculator;

import com.sundot.airport.attendance.domain.AttendanceRecord;
import com.sundot.airport.attendance.mapper.AttendanceRecordMapper;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.enums.DeptTypeEnum;
import com.sundot.airport.common.enums.IndicatorTypeEnum;
import com.sundot.airport.common.statistics.AbstractIndicatorCalculator;
import com.sundot.airport.common.statistics.IndicatorCalculationParams;
import com.sundot.airport.common.statistics.TimeDimensionProcessor;
import com.sundot.airport.system.mapper.SysDeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 出勤人次计算器
 * 计算全站出勤人次统计
 */
@Component
public class AttendancePersonCountCalculator extends AbstractIndicatorCalculator<BigDecimal> {

    @Autowired
    private AttendanceRecordMapper attendanceRecordMapper;

    @Autowired
    private TimeDimensionProcessor timeDimensionProcessor;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public BigDecimal calculate(IndicatorCalculationParams params) {
        // 确保时间范围已计算
        timeDimensionProcessor.calculateTimeRange(params);

        // 查询全站出勤记录
        AttendanceRecord record = new AttendanceRecord();
        record.setAttendanceDateStart(params.getStartTime());
        record.setAttendanceDateEnd(params.getEndTime());
        if (params.getDeptId() != null) {
            // 按部门统计（大队、科室、班组等）
            SysDept sysDept = sysDeptMapper.selectDeptById(params.getDeptId());
            if (DeptTypeEnum.TEAMS.getCode().equals(sysDept.getDeptType())) {
                record.setTeamCode(params.getDeptId().toString());
            } else if (DeptTypeEnum.MANAGER.getCode().equals(sysDept.getDeptType())) {
                record.setDepartmentCode(params.getDeptId().toString());
            } else if (DeptTypeEnum.BRIGADE.getCode().equals(sysDept.getDeptType())) {
                record.setBrigadeCode(params.getDeptId().toString());
            } else if (DeptTypeEnum.STATION.getCode().equals(sysDept.getDeptType())) {
                record.setStationCode(params.getDeptId().toString());
            }
        }

        // 查询考勤记录
        List<AttendanceRecord> records = attendanceRecordMapper.selectAttendanceRecordList(record);

        // 返回出勤人次
        return new BigDecimal(records.size());
    }

    @Override
    public String getIndicatorType() {
        return IndicatorTypeEnum.ATTENDANCE_PERSONS.getCode();
    }

    @Override
    public String getIndicatorName() {
        return IndicatorTypeEnum.ATTENDANCE_PERSONS.getName();
    }

    @Override
    public String getIndicatorDescription() {
        return "全站出勤人次统计";
    }

}