package com.securitycontrol.screen.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;
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.DateTimeHelper;
import com.securitycontrol.common.core.utils.aes.StringHelper;
import com.securitycontrol.common.core.web.domain.AjaxResult;
import com.securitycontrol.entity.screen.dto.ScreenParamDto;
import com.securitycontrol.entity.screen.vo.DeviceValueVo;
import com.securitycontrol.entity.system.SystemGlobal;
import com.securitycontrol.entity.system.base.vo.ProVo;
import com.securitycontrol.screen.mapper.XcIndexMapper;
import com.securitycontrol.screen.service.XcIndexService;
import com.securitycontrol.system.api.RemoteFileService;
import com.securitycontrol.system.api.RemoteSourceService;
import com.securitycontrol.system.api.domain.SysFile;
import com.securitycontrol.system.api.domain.TbSourceFile;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.TIMEOUT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 现场施工 大屏首页接口层
 * @author 黑子
 */
@Slf4j
@Service
public class XcIndexServiceImpl  implements XcIndexService {

    @Autowired
    private XcIndexMapper mapper;
    @Resource
    private RemoteSourceService remoteSourceService;
    @Resource
    private RemoteFileService remoteFileService;

    @Override
    public AjaxResult getProDetails(ScreenParamDto dto) {
        Map<String ,Object> map= Maps.newHashMap();
        try{
            System.err.println(dto.getBidCode());
            ProVo proVo=mapper.getProDetails(dto.getBidCode());
           Result<List<TbSourceFile>> result=remoteSourceService.getSourceFile(proVo.getProId(), SystemGlobal.PRO_IMAGE, SecurityConstants.INNER);
            if(result.getCode()==SystemGlobal.SUCCESS_CODE){
                List<ProVo.FileData> list2 = new ArrayList<>();
                List<TbSourceFile> list=result.getData();
                list.forEach(fileVo->{
                    Result<SysFile> result2 = remoteFileService.getImgBase64(fileVo.getFileId(), SecurityConstants.INNER);
                    if (result2 != null && result2.getCode() == HttpStatus.SUCCESS && result2.getData() != null) {
                        String jsonString = JSON.toJSONString(result2.getData());
                        JSONObject item = JSON.parseObject(jsonString);
                        String  base64 = item.getString("url");
                        ProVo.FileData fileData = new ProVo.FileData();
                        fileData.setFileId(fileVo.getFileId());
                        fileData.setBase64Url(base64);
                        fileData.setFileSourceType(fileVo.getSourceType());
                        list2.add(fileData);
                    }

                });
                proVo.setFileData(list2);
            }
            map.put("data",proVo);
            map.put("code",200);
            return AjaxResult.success(map);
        }catch (Exception e){
            map.put("data","");
            map.put("code",201);
            log.error(e.toString(),e);
        }
        return AjaxResult.success(map);
    }

    /**
     * 查询实时环境检测数据
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getProJcData(ScreenParamDto dto) {
           try{
               dto.setTypeCode(SystemGlobal.HJ_TYPE);
               List<DeviceValueVo> list=mapper.getProJcData(dto);
               return AjaxResult.success(list);
           }catch (Exception e){
               log.error(e.toString(),e);
           }
        return AjaxResult.success(new  ArrayList<DeviceValueVo>());
    }

    /**
     * 查询项目施工风险数据
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getProRisk(ScreenParamDto dto) {
        Map<String ,Object> map= Maps.newHashMap();
        try{
            List<String> dayList=new ArrayList<>();
            List<Integer> weekRisk=new ArrayList<>();
            List<Integer> warnList=new ArrayList<>();
               String day=DateTimeHelper.getNowDay();
               //获取近一周的数据
                for (int i = 1; i <SystemGlobal.WEEK_DAY-1; i++) {
                     String   nextDay=DateTimeHelper.getDayAddOrReduce(day,i-7);
                     dayList.add(nextDay);
                }
                dayList.add(day);
            map.put("day",dayList);
            for (String time:dayList) {
                dto.setStartTime(time);
                int  weekNum=mapper.getWeekRiskNum(dto);
                int  warnNum=mapper.getWarnNum(dto);
                weekRisk.add(weekNum);
                warnList.add(warnNum);
            }
            map.put("week",weekRisk);
            map.put("warn",warnList);

        }catch (Exception e){
            log.error(e.toString(),e);
        }
         return   AjaxResult.success(map);
    }

    @Override
    public AjaxResult getProcess(ScreenParamDto dto) {
        try{
            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);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return null;
    }

    @Override
    public AjaxResult getProMoney(ScreenParamDto dto) {
        Map<String, Object> dataMap = Maps.newHashMap();
        try{
            List<String> monList=new ArrayList<String>();
            List<String> costList=new ArrayList<String>();
            ProVo proVo=mapper.getProDetails(dto.getBidCode());
            String startTime=proVo.getPlanStartTime();
            String  time=DateTimeHelper.getNowMonth();
            String nowTime=startTime.substring(0,7);
            if(DateTimeHelper.compareMonth(startTime,time)){
                monList.add(nowTime);
                while(!time.equals(nowTime)){
                    nowTime=DateTimeHelper.getAddMonth(nowTime,1);
                    monList.add(nowTime);
                }
            }else{
                monList.add(nowTime);
            }

            for (String times:monList) {
                String  cost=mapper.getProCost(times,dto.getBidCode());
                if(StringHelper.isNotEmpty(cost)){
                    costList.add(cost);
                }else{
                    costList.add("0");
                }
            }
            dataMap.put("time",monList);
            dataMap.put("cost",costList);
            dataMap.put("proCost", StringUtils.isNotEmpty(proVo.getProCost()) ? proVo.getProCost() : "0");
            return AjaxResult.success(dataMap);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return AjaxResult.success(dataMap);
    }
}
