package com.securitycontrol.background.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.securitycontrol.background.mapper.IAppMapper;
import com.securitycontrol.background.service.IAppService;
import com.securitycontrol.common.core.constant.Constant;
import com.securitycontrol.common.core.constant.HttpStatus;
import com.securitycontrol.common.core.constant.SecurityConstants;
import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.utils.StringUtils;
import com.securitycontrol.common.core.utils.aes.AesCbcUtils;
import com.securitycontrol.common.core.utils.aes.DateTimeHelper;
import com.securitycontrol.common.core.web.domain.AjaxResult;
import com.securitycontrol.entity.background.dto.ParamDto;
import com.securitycontrol.entity.background.vo.HumanManageVo;
import com.securitycontrol.entity.background.vo.ProjectCostVo;
import com.securitycontrol.entity.background.vo.VehicleVo;
import com.securitycontrol.entity.system.base.vo.ProVo;
import com.securitycontrol.entity.system.vo.ResourceFileVo;
import com.securitycontrol.system.api.RemoteFileService;
import com.securitycontrol.system.api.domain.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author：cwchen
 * @date：2024-03-28-17:36
 * @version：1.0
 * @description：App业务逻辑层
 */
@Service(value = "IAppService")
@Slf4j
public class AppServiceImpl implements IAppService {

    @Resource(name = "IAppMapper")
    private IAppMapper mapper;

    @Resource
    private RemoteFileService remoteFileService;

    @Override
    public AjaxResult getProBrief(ParamDto dto) {
        ProVo proVo = new ProVo();
        try {
            proVo = mapper.getProBrief(dto);
            if(Objects.nonNull(proVo)){
                List<ProVo.FileData> list = new ArrayList<>();
                List<ResourceFileVo> resourceFileVos = mapper.getFiles(proVo.getProId());
                if (CollectionUtils.isNotEmpty(resourceFileVos)) {
                    for (ResourceFileVo fileVo : resourceFileVos) {
                        String base64 = null;
                        Result<SysFile> result = remoteFileService.getImgBase64(fileVo.getFileId(), SecurityConstants.INNER);
                        if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
                            String jsonString = JSON.toJSONString(result.getData());
                            JSONObject item = JSON.parseObject(jsonString);
                            base64 = item.getString("url");
                        }
                        ProVo.FileData fileData = new ProVo.FileData();
                        fileData.setFileId(fileVo.getFileId());
                        fileData.setBase64Url(base64);
                        fileData.setFileSourceType(fileVo.getSourceType());
                        list.add(fileData);
                    }
                }
                proVo.setFileData(list);
            }
        } catch (Exception e) {
            log.error("工程简介", e);
        }
        return AjaxResult.success(proVo);
    }

    @Override
    public AjaxResult getProsByUser(ParamDto dto) {
        List<Map<String, String>> list = new ArrayList<>();
        try {
            list = mapper.getProsByUser(dto);
        } catch (Exception e) {
            log.error("当前登录人绑定的工程");
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getPersonnelList(ParamDto dto) {
        List<HumanManageVo> list = new ArrayList();
        try {
            list = mapper.getPersonnelList(dto);
            for (HumanManageVo vo : list) {
                String decryptIdNumber = AesCbcUtils.decrypt(vo.getIdNumber());
                if (decryptIdNumber != null) {
                    vo.setIdNumber(decryptIdNumber);
                    vo.setSex(getGenderByIdCard(decryptIdNumber));
                } else {
                    vo.setSex(getGenderByIdCard(vo.getIdNumber()));
                }
            }
        } catch (Exception e) {
            log.error("人员管理", e);
        }
        return AjaxResult.success(list);
    }

    public static String getGenderByIdCard(String idCard) {
        if (StringUtils.isNotEmpty(idCard)) {
            if (idCard.length() == Constant.ID_CARD || idCard.length() == Constant.ID_CARD2) {
                idCard = idCard.length() == 15 ? idCard.substring(0, 6) + "19" + idCard.substring(6) : idCard;
                char genderCode = idCard.charAt(16);
                return (genderCode % 2) == 0 ? "女" : "男";
            }
        }
        return null;
    }

    @Override
    public AjaxResult getCarList(ParamDto dto) {
        List<VehicleVo> list = new ArrayList();
        try {
            list = mapper.getCarList(dto);
        } catch (Exception e) {
            log.error("人员管理", e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult proProgress(ParamDto dto) {
        Map<String, Object> dataMap = new HashMap<>(16);
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            list = mapper.getProBasicInfo(dto);
            Map<String, List<Map<String, Object>>> map = list.stream().collect(Collectors.groupingBy(item -> {
                return String.valueOf(item.get("bidCode"));
            }));
            map.forEach((k, v) -> {
                // 根据每个工程的工序计划及进度填报计算效率
                BigDecimal value = new BigDecimal("0");
                BigDecimal value2 = new BigDecimal("0");
                BigDecimal multipleValue = new BigDecimal("100");
                for (int i = 0; i < v.size(); i++) {
                    if (Objects.nonNull(v.get(i).get("planId")) && Objects.nonNull(v.get(i).get("planProgress")) && Objects.nonNull(v.get(i).get("gxWeight"))) {
                        BigDecimal bigDecimal = new BigDecimal(String.valueOf(v.get(i).get("gxWeight")));
                        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(v.get(i).get("planProgress")));
                        value = value.add(bigDecimal.multiply(bigDecimal2).divide(multipleValue, 3, BigDecimal.ROUND_HALF_UP));
                    }
                }
                // 计划开始时间、计划结束时间、实际进度、计划工期
                String planStartTime = String.valueOf(v.get(0).get("planStartTime"));
                String planEndTime = String.valueOf(v.get(0).get("planEndTime"));
                String nowDate = DateTimeHelper.getNowDate();
                Long dayDifference = DateTimeHelper.getDayDifference(planStartTime, planEndTime);
                dataMap.put("planStartTime", planStartTime);
                dataMap.put("planEndTime", planEndTime);
                dataMap.put("value", value.doubleValue());
                dataMap.put("durationDay", dayDifference);

                Long planStartTimeTamp = DateTimeHelper.convertDateStringToTimestamp(planStartTime, "yyyy-MM-dd");
                Long planEndTimeTamp = DateTimeHelper.convertDateStringToTimestamp(planEndTime, "yyyy-MM-dd");
                Long nowDateTamp = DateTimeHelper.convertDateStringToTimestamp(nowDate, "yyyy-MM-dd");
                // 计划进度
                if (nowDateTamp < planStartTimeTamp) {
                    dataMap.put("value2", new Double(0));
                } else if (nowDateTamp > planEndTimeTamp) {
                    dataMap.put("value2", new Double(100));
                } else {
                    // 工程已施工天数
                    Long residueDay = DateTimeHelper.getDayDifference(planStartTime, nowDate);
                    // 剩余工期
                    Long residueDay2 = DateTimeHelper.getDayDifference(nowDate, planEndTime);
                    BigDecimal dayDifferenceBd = BigDecimal.valueOf(dayDifference);
                    BigDecimal residueDayBd = BigDecimal.valueOf(residueDay);
                    value2 = value2.add(residueDayBd.divide(dayDifferenceBd, 3, BigDecimal.ROUND_HALF_UP).multiply(multipleValue));
                    dataMap.put("value2", value2.doubleValue());
                    dataMap.put("residueDay", residueDay2);
                }
            });
        } catch (Exception e) {
            log.error("项目进度");
        }
        return AjaxResult.success(dataMap);
    }

    @Override
    public AjaxResult alarmLists(ParamDto dto) {
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            list = mapper.alarmLists(dto);
        } catch (Exception e) {
            log.error("告警", e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult proManagement(ParamDto dto) {
        Map<String, Object> dataMap = new HashMap<>(16);
        ProVo vo = new ProVo();
        JSONObject item = new JSONObject();
        List<Map<String, Object>> proGxPlanList = new ArrayList<>();
        List<ProjectCostVo> proCostList = new ArrayList<>();
        try {
            // 工程详情
            vo = mapper.getProBrief(dto);
            AjaxResult ajaxResult = proProgress(dto);
            String jsonString = JSON.toJSONString(ajaxResult.get("data"));
            item = JSON.parseObject(jsonString);
            // 施工进度
            proGxPlanList = mapper.getProGxPlan(dto);
            if(CollectionUtils.isNotEmpty(proGxPlanList)){
                proGxPlanList.forEach(mapData->{
                    String proType = String.valueOf(mapData.get("proType"));
                    String bidCode = String.valueOf(mapData.get("bidCode"));
                    String gxId = String.valueOf(mapData.get("gxId"));
                    String name = mapper.getGtOrGxName(proType, bidCode, gxId);
                    mapData.put("name",name);
                });
            }
            // 标段工程成本
            proCostList = mapper.getProCost(dto);
        } catch (Exception e) {
            log.error("工程管理", e);
        }
        dataMap.put("vo",vo);
        dataMap.put("item",item);
        dataMap.put("proGxPlan",proGxPlanList);
        dataMap.put("proCost",proCostList);
        return AjaxResult.success(dataMap);
    }
}
