package com.zcloud.fire.check.domain.model;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.exception.BizException;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.jjb.saas.framework.domain.model.BaseE;
import com.zcloud.fire.check.domain.enums.FireDeviceTypeEnum;
import com.zcloud.fire.check.domain.utils.DepartmentPathUtil;
import com.zcloud.gbscommon.excelEntity.*;
import com.zcloud.gbscommon.utils.ExcelUtils;
import com.zcloud.gbscommon.utils.Tools;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * web-domain
 *
 * @Author zhaokai
 * @Date 2025-11-26 10:12:34
 */
@Data
public class FireDeviceE extends BaseE {
    //主键
    private Long id;
    //业务主键id
    private String fireDeviceId;
    //企业id
    private Long corpinfoId;
    //消防区域id
    private String fireRegionId;
    //消防点位id
    private String firePointId;
    //部门id
    private Long departmentId;
    //消防器材类型
    private String fireDeviceType;
    //消防器材类型名称
    private String fireDeviceTypeName;
    //器材编号
    private String fireDeviceCode;
    //有效期开始时间
    private LocalDate validityStartTime;
    //有效期结束时间
    private LocalDate validityEndTime;
    //存放地点
    private String storageLocation;
    //乐观锁
    private Integer version;
    //创建人
    private Long createId;
    //创建人姓名
    private String createName;
    //创建时间
    private LocalDateTime createTime;
    //更新人
    private Long updateId;
    //修改人名称
    private String updateName;
    //更新时间
    private LocalDateTime updateTime;
    //描述
    private String remarks;
    //是否删除
    private String deleteEnum;
    //租户ID
    private Long tenantId;
    //机构ID
    private Long orgId;
    //环境
    private String env;

    private FireRegionE fireRegionE;
    private FirePointE firePointE;


    public void exportFireDeviceTable(HttpServletResponse httpServletResponse, List<FireDeviceExcelExportEntity> listFireDeviceExcelExportEntityList) {
        try {
            ExcelUtils.exportExcel(httpServletResponse, FireDeviceExcelExportEntity.class, "消防设备信息", listFireDeviceExcelExportEntityList);
        } catch (Exception e) {
            throw new BizException("导出失败");
        }
    }

    public static List<FireDeviceE> parseImportTemplateData(MultipartFile file,
                                                            List<DepartmentE> departmentEList,
                                                            List<UserE> userEList,
                                                            List<FireDeviceE> fireDeviceEList,
                                                            List<FireRegionE> fireRegionEList,
                                                            List<FirePointE> firePointEList) {
        List<FireDeviceExcelImportEntity> list = new ArrayList<>();
        try {
            ExcelUtils.readBatchBySheetAndRow(file, FireDeviceExcelImportEntity.class, list, 0, 2);
            if (list.isEmpty()) {
                throw new BizException("文件为空");
            }
        } catch (Exception e) {
            throw new BizException("文件解析失败");
        }
        if (CollUtil.isEmpty(departmentEList)) {
            throw new BizException("该企业不存在部门信息，请添加部门后重新导入");
        }

//        Map<String, DepartmentE> departmentEMap = departmentEList.stream().collect(Collectors.toMap(DepartmentE::getName, DepartmentE -> DepartmentE));
        Map<String, DepartmentE> departmentEMap = DepartmentPathUtil.buildDepartmentPathMap(departmentEList);

        Map<String, FireDeviceE> fireDeviceEMap = fireDeviceEList.stream().collect(Collectors.toMap(FireDeviceE::getFireDeviceCode, FireDeviceE -> FireDeviceE));
        Map<String, FireRegionE> fireRegionEMap = fireRegionEList.stream().collect(Collectors.toMap(FireRegionE::getFireRegionCode, FireRegionE -> FireRegionE));
        Map<String, FirePointE> firePointEMap = firePointEList.stream().collect(Collectors.toMap(FirePointE::getFirePointCode, FirePointE -> FirePointE));

        List<String> fireDeviceCodeList = fireDeviceEList.stream().map(FireDeviceE::getFireDeviceCode).collect(Collectors.toList());
        // 错误消息集合
        List<String> errList = new ArrayList<>();
        List<FireDeviceE> fireDeviceList = new ArrayList<>();
        // Note: Need to create user maps for validation
        Map<Long, List<UserE>> userEMap = userEList.stream()
                .collect(Collectors.groupingBy(UserE::getDepartmentId));
        //过滤掉手机号为空的

        Map<String, UserE> userEMapByPhone = userEList.stream()
                .filter(user -> StringUtils.isNotEmpty(user.getPhone()))
                .collect(Collectors.toMap(UserE::getPhone, user -> user));


        for (int i = 0; i < list.size(); i++) {
            FireDeviceE fireDeviceE = new FireDeviceE();
            FireDeviceExcelImportEntity entity = list.get(i);
            if (entity == null) {
                errList.add("第" + (i + 2) + "行数据不能为空。");
                continue;
            }

            // 消防器材编号
            if (StringUtils.isEmpty(entity.getFireDeviceCode())) {
                errList.add("第" + (i + 2) + "行消防器材编号不能为空。");
                continue;
            } else {
                if (CollUtil.isNotEmpty(fireDeviceEMap)) {
                    if (fireDeviceEMap.get(entity.getFireDeviceCode()) != null) {
                        errList.add("第" + (i + 2) + "行消防器材编号与系统内消防器材编号重复。");
                        continue;
                    }
                }
                if (!fireDeviceCodeList.contains(entity.getFireDeviceCode())) {
                    fireDeviceCodeList.add(entity.getFireDeviceCode());
                    fireDeviceE.setFireDeviceCode(entity.getFireDeviceCode());
                } else {
                    errList.add("第" + (i + 2) + "行消防器材编号在导入表格中名称重复。");
                    continue;
                }
            }
            if(StringUtils.isEmpty(entity.getFireRegionName())){
                errList.add("第" + (i + 2) + "行消防区域不能为空。");
                continue;
            }

            if(StringUtils.isEmpty(entity.getDepartmentName1()) &&
                    StringUtils.isEmpty(entity.getDepartmentName2()) &&
                    StringUtils.isEmpty(entity.getDepartmentName3()) &&
                    StringUtils.isEmpty(entity.getDepartmentName4()) &&
                    StringUtils.isEmpty(entity.getDepartmentName5())){
                errList.add("第" + (i+3) + "行责任部门不能全部为空。");
            }else{
                String departmentName = entity.getDepartmentName1();
                if(StringUtils.isNotEmpty(entity.getDepartmentName2())){
                    departmentName += "=" + entity.getDepartmentName2();
                }
                if(StringUtils.isNotEmpty(entity.getDepartmentName3())){
                    departmentName += "=" + entity.getDepartmentName3();
                }
                if(StringUtils.isNotEmpty(entity.getDepartmentName4())){
                    departmentName += "=" + entity.getDepartmentName4();
                }
                if(StringUtils.isNotEmpty(entity.getDepartmentName5())){
                    departmentName += "=" + entity.getDepartmentName5();
                }

                DepartmentE department = departmentEMap.get(departmentName);
                if (department == null) {
                    errList.add("第" + (i + 2) + "行：未找到名称为“" + departmentName + "”的责任部门。");
                    continue;
                } else {
                    fireDeviceE.setDepartmentId(department.getId());
                    // 负责人校验
                    if (StringUtils.isEmpty(entity.getUserPhone())) {
                        errList.add("第" + (i + 2) + "行负责人手机号不能为空。");
                        continue;
                    } else {
                        UserE user = userEMapByPhone.get(entity.getUserPhone());
                        List<UserE> usersInDept = userEMap.get(department.getId());
                        if (user == null) {
                            errList.add("第" + (i + 2) + "行：未找到手机号为“" + entity.getUserPhone() + "”的负责人手机号");
                            continue;
                        } else if (usersInDept == null || !usersInDept.contains(user)) {
                            errList.add("第" + (i + 2) + "行：部门“" + departmentName + "”下未找到负责人手机号“" + entity.getUserPhone() + "”。");
                            continue;
                        }
                    }
                }

            }

           /* // 时间校验
            if (StringUtils.isNotEmpty(entity.getValidityStartTime())) {
                try {
                         // 定义输入格式
                        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日");
                        LocalDate date = LocalDate.parse(entity.getValidityStartTime(), inputFormatter);
                        fireDeviceE.setValidityStartTime(date);
                } catch (DateTimeParseException e) {
                    errList.add("第" + (i + 2) + "行有效期开始时间格式错误");
                    continue;
                }
            }

            if (StringUtils.isNotEmpty(entity.getValidityEndTime())) {
                try {
                       // 定义输入格式
                        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日");
                        // 解析日期并设置时间为00:00:00
                        LocalDate date = LocalDate.parse(entity.getValidityEndTime(), inputFormatter);
                        fireDeviceE.setValidityEndTime(date);
                } catch (DateTimeParseException e) {
                    errList.add("第" + (i + 2) + "行有效期结束时间格式错误");
                    continue;
                }
            }*/

            // 验证器材类型
            if (StringUtils.isEmpty(entity.getFireDeviceTypeName())) {
                errList.add("第" + (i + 2) + "行消防器材类型不能为空。");
                continue;
            } else {
                FireDeviceTypeEnum fireDeviceTypeEnum = FireDeviceTypeEnum.getByDescription(entity.getFireDeviceTypeName());
                if (fireDeviceTypeEnum == null) {
                    errList.add("第" + (i + 2) + "行：未找到“" + entity.getFireDeviceTypeName() + "”的消防器材类型。");
                    continue;
                } else {
                    fireDeviceE.setFireDeviceType(fireDeviceTypeEnum.getCode().toString());
                    fireDeviceE.setFireDeviceTypeName(fireDeviceTypeEnum.getDescription());
                }
            }

            // 存放地点
            if (StringUtils.isEmpty(entity.getStorageLocation())) {
                errList.add("第" + (i + 2) + "行存放地点不能为空。");
                continue;
            } else {
                fireDeviceE.setStorageLocation(entity.getStorageLocation());
            }
            // 区域校验
            if (StringUtils.isEmpty(entity.getFireRegionCode())) {
                errList.add("第" + (i + 2) + "行消防区域不能为空。");
                continue;
            } else {

                FireRegionE fireRegion = fireRegionEMap.get(entity.getFireRegionCode());
                if (fireRegion == null) {
                    //新增
                    fireRegion = new FireRegionE();
                    fireRegion.setFireRegionName(entity.getFireRegionName());
                    fireRegion.setFireRegionCode(entity.getFireRegionCode());
                    fireRegion.setDepartmentId(fireDeviceE.getDepartmentId());
                    fireDeviceE.setFireRegionE(fireRegion);
                } else {
                    fireDeviceE.setFireRegionId(fireRegion.getFireRegionId());
                }
            }

            // 点位校验
            if (StringUtils.isEmpty(entity.getFirePointName())) {
                errList.add("第" + (i + 2) + "行消防点位名称不能为空。");
                continue;
            } else {
                FirePointE firePoint = firePointEMap.get(entity.getFirePointCode());
                if (firePoint == null) {
                    //新增
                    firePoint = new FirePointE();
                    firePoint.setFirePointName(entity.getFirePointName());
                    firePoint.setFirePointCode(entity.getFirePointCode());
                    firePoint.setDepartmentId(fireDeviceE.getDepartmentId());
                    UserE userE = userEMapByPhone.get(entity.getUserPhone());
                    firePoint.setUserId(userE.getId());
                    fireDeviceE.setFirePointE(firePoint);
                } else {
                    fireDeviceE.setFirePointId(firePoint.getFirePointId());
                }
            }

            fireDeviceE.setCorpinfoId(AuthContext.getTenantId());
            fireDeviceE.setFireDeviceId(Tools.get32UUID());

            fireDeviceList.add(fireDeviceE);
        }

        if (CollUtil.isNotEmpty(errList)) {
            throw new BizException("导入信息有误，请检查后重新导入。错误信息:" + String.join("", errList));
        }
        return fireDeviceList;
    }
}

