package com.testor.module.accident.model.template;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.testor.common.core.utils.StringUtils;
import com.testor.module.accident.model.domain.AccidentPersonnel;
import com.testor.module.accident.model.dto.AccidentReportDetail;
import lombok.Data;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 事故信息详情导出模板
 */
@Data
public class AccidentReportDetailTemplate {

    @ExcelProperty("序号")
    @ColumnWidth(8)
    private String number;

    @ExcelProperty("当前机构名称")
    @ColumnWidth(20)
    private String currentOrgName;

    @ExcelProperty("经营部名称")
    @ColumnWidth(20)
    private String businessDeptName;

    @ExcelProperty("大区名称")
    @ColumnWidth(15)
    private String regionName;

    @ExcelProperty("事故发生时间")
    @ColumnWidth(20)
    private String accidentTime;

    @ExcelProperty("事故等级（国家）")
    @ColumnWidth(15)
    private String accidentLevelCountry;

    @ExcelProperty("事故等级（集团）")
    @ColumnWidth(15)
    private String accidentLevel;

    @ExcelProperty("受伤人数")
    @ColumnWidth(10)
    private String reportCount;

    @ExcelProperty("直接经济损失")
    @ColumnWidth(15)
    private String directEconomicLoss;

    @ExcelProperty("损失工作日")
    @ColumnWidth(15)
    private String lostWorkingDays;

    @ExcelProperty("事故类型")
    @ColumnWidth(20)
    private String accidentType;

    @ExcelProperty("涉及集团八大类风险")
    @ColumnWidth(30)
    private String groupRisk;

    @ExcelProperty("涉及危险作业类型")
    @ColumnWidth(30)
    private String dangerousHomeworkCategory;

    @ExcelProperty("受伤部位")
    @ColumnWidth(20)
    private String injuredArea;

    @ExcelProperty("事故详细经过")
    @ColumnWidth(40)
    private String accidentPassed;

    @ExcelProperty("事故直接原因和间接原因")
    @ColumnWidth(40)
    private String accidentCause;

    @ExcelProperty("改善措施")
    @ColumnWidth(40)
    private String improvements;

    @ExcelProperty("人员追责问责情况")
    @ColumnWidth(30)
    private String personnelAccountabilityStatus;

    @ExcelProperty("备注")
    @ColumnWidth(30)
    private String remarks;

    // 人员信息相关字段
    @ExcelProperty("人员归属类型")
    @ColumnWidth(20)
    private String personnelBelongType;

    @ExcelProperty("人员年龄")
    @ColumnWidth(15)
    private String personnelAge;

    @ExcelProperty("人员性别")
    @ColumnWidth(15)
    private String personnelSex;

    // 转换方法：从AccidentReportDetail转换为Template
    public static AccidentReportDetailTemplate fromAccidentReportDetail(AccidentReportDetail detail) {
        if (detail == null) {
            return null;
        }

        AccidentReportDetailTemplate template = new AccidentReportDetailTemplate();

        // 复制基本字段
        template.setCurrentOrgName(detail.getCurrentOrgName());
        template.setBusinessDeptName(detail.getBusinessDeptName());
        template.setRegionName(detail.getRegionName());

        // 格式化日期
        if (detail.getAccidentTime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            template.setAccidentTime(sdf.format(detail.getAccidentTime()));
        }

        template.setAccidentLevelCountry(detail.getAccidentLevelCountry());
        template.setAccidentLevel(detail.getAccidentLevel());
        template.setReportCount(detail.getReportCount() != null ? String.valueOf(detail.getReportCount()) : "0");
        template.setDirectEconomicLoss(formatBigDecimal(detail.getDirectEconomicLoss()));
        template.setLostWorkingDays(detail.getLostWorkingDays());
        template.setAccidentType(detail.getAccidentType());
        template.setGroupRisk(detail.getGroupRisk());
        template.setDangerousHomeworkCategory(detail.getDangerousHomeworkCategory());
        template.setInjuredArea(detail.getInjuredArea());
        template.setAccidentPassed(detail.getAccidentPassed());
        template.setAccidentCause(detail.getAccidentCause());
        template.setImprovements(detail.getImprovements());
        template.setPersonnelAccountabilityStatus(detail.getPersonnelAccountabilityStatus());
        template.setRemarks(detail.getRemarks());

        // 处理人员信息
        if (!CollectionUtils.isEmpty(detail.getAccidentPersonnelList())) {
            template.setPersonnelBelongType(formatPersonnelBelongType(detail.getAccidentPersonnelList()));
            template.setPersonnelAge(formatPersonnelAge(detail.getAccidentPersonnelList()));
            template.setPersonnelSex(formatPersonnelSex(detail.getAccidentPersonnelList()));
        } else {
            template.setPersonnelBelongType("无");
            template.setPersonnelAge("无");
            template.setPersonnelSex("无");
        }

        return template;
    }

    private static String formatBigDecimal(BigDecimal value) {
        if (value == null) {
            return "0";
        }
        return value.toString();
    }

    /**
     * 格式化人员归属类型
     * 0: 承包商人员, 1: 企业人员
     */
    private static String formatPersonnelBelongType(List<AccidentPersonnel> personnelList) {
        if (CollectionUtils.isEmpty(personnelList)) {
            return "";
        }

        List<String> belongTypes = new ArrayList<>();
        for (AccidentPersonnel person : personnelList) {
            String belongType = person.getBelongType();
            if (StringUtils.hasText(belongType)) {
                if ("0".equals(belongType)) {
                    belongTypes.add("承包商人员");
                } else if ("1".equals(belongType)) {
                    belongTypes.add("企业人员");
                } else {
                    belongTypes.add(belongType); // 如果是其他值，保持原样
                }
            }
        }

        return String.join(", ", belongTypes);
    }

    /**
     * 格式化人员年龄
     */
    private static String formatPersonnelAge(List<AccidentPersonnel> personnelList) {
        if (CollectionUtils.isEmpty(personnelList)) {
            return "";
        }

        return personnelList.stream()
                .map(person -> {
                    if (person.getAge() != null) {
                        return String.valueOf(person.getAge());
                    }
                    return "";
                })
                .filter(StringUtils::hasText)
                .collect(Collectors.joining(", "));
    }

    /**
     * 格式化人员性别
     */
    private static String formatPersonnelSex(List<AccidentPersonnel> personnelList) {
        if (CollectionUtils.isEmpty(personnelList)) {
            return "";
        }

        return personnelList.stream()
                .map(person -> {
                    String sex = person.getSex();
                    if ("0".equals(sex)) {
                        return "男";
                    } else if ("1".equals(sex)) {
                        return "女";
                    } else {
                        return sex != null ? sex : "";
                    }
                })
                .filter(StringUtils::hasText)
                .collect(Collectors.joining(", "));
    }

    /**
     * 批量转换方法
     */
    public static List<AccidentReportDetailTemplate> fromAccidentReportDetailList(List<AccidentReportDetail> detailList) {
        if (CollectionUtils.isEmpty(detailList)) {
            return Collections.emptyList();
        }

        return detailList.stream()
                .map(AccidentReportDetailTemplate::fromAccidentReportDetail)
                .collect(Collectors.toList());
    }
}
