package com.tuoheng.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.entity.domain.Question;
import com.tuoheng.admin.entity.domain.Tenant;
import com.tuoheng.admin.entity.domain.ThMission;
import com.tuoheng.admin.entity.dto.index.AirportDetailDto;
import com.tuoheng.admin.entity.dto.index.QuestionListDto;
import com.tuoheng.admin.entity.request.index.GetAirportDetailDto;
import com.tuoheng.admin.entity.request.index.GetQuestionListDto;
import com.tuoheng.admin.entity.vo.MissionVO;
import com.tuoheng.admin.enums.MarkTypeEnum;
import com.tuoheng.admin.enums.TaskStatusEnum;
import com.tuoheng.admin.mapper.QuestionMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.mapper.ThMissionMapper;
import com.tuoheng.admin.service.IndexService;
import com.tuoheng.common.common.BaseQuery;
import com.tuoheng.common.config.CommonConfig;
import com.tuoheng.common.utils.HttpUtils;
import com.tuoheng.common.utils.JacksonUtil;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.common.utils.StringUtils;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author chenjiandong
 * @description: TODO
 * @date 2022/12/26 10:24
 */
@Service
@Slf4j
public class IndexServiceImpl implements IndexService {

    @Autowired
    private ThMissionMapper thMissionMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Override
    @Transactional(readOnly = true)
    public IPage<MissionVO> getMissionList(BaseQuery baseQuery){
        Page<ThMission> page = new Page<>();
        page.setSize(baseQuery.getLimit() != null ? baseQuery.getLimit() : 10);
        page.setCurrent(baseQuery.getPage() != null ? baseQuery.getPage() : 0);
        LambdaQueryWrapper<ThMission> queryMission=new LambdaQueryWrapper<>();
        queryMission.eq(ThMission::getTenantId,ShiroUtils.getTenantId())//xz
                .eq(ThMission::getMark,MarkTypeEnum.VALID.getCode())
                .orderByDesc(ThMission::getCreateTime);
        queryMission.in(ThMission::getStatus, Arrays.asList(TaskStatusEnum.FLIGHT.getCode(),TaskStatusEnum.WAIT.getCode()));
        IPage<ThMission> thMissionIPage = thMissionMapper.selectPage(page, queryMission);
        List<ThMission> records = thMissionIPage.getRecords();
        List<MissionVO> result=new ArrayList<>();
        records.forEach(mission->{
            MissionVO missionVO=new MissionVO();
            BeanUtils.copyProperties(mission,missionVO);
            //获取最后一次的飞行时间
            result.add(missionVO);
        });

        IPage<MissionVO> resultPage=new Page<>();
        resultPage.setCurrent(thMissionIPage.getCurrent());
        resultPage.setPages(thMissionIPage.getPages());
        resultPage.setSize(thMissionIPage.getSize());
        resultPage.setTotal(thMissionIPage.getTotal());
        resultPage.setRecords(result);
        return resultPage;
    }

    @Override
    public JsonResult getAirportDetail(Integer airportId){
        String url = CommonConfig.airportURL + "/api/airportInterface/getAirportStatus";
        String param = "airportId=" + airportId;
        String result = HttpUtils.sendGet(url, param);
        JsonResult jsonResult = JacksonUtil.json2pojo(result, JsonResult.class);
        AirportDetailDto airportDetailDto = new AirportDetailDto();
        JSONObject dataObject = (JSONObject) JSONObject.toJSON(jsonResult.getData());
        JSONObject wthJson = dataObject.getJSONObject("WTH");
        if(Objects.nonNull(wthJson)){
            JSONObject parmJson = wthJson.getJSONObject("parmNew");

            BigDecimal hum = parmJson.getBigDecimal("Hum").divide(new BigDecimal(10), 1, BigDecimal.ROUND_HALF_UP);
            airportDetailDto.setHum(hum + "rh");
            BigDecimal tmp = parmJson.getBigDecimal("Tmp").divide(new BigDecimal(10), 1, BigDecimal.ROUND_HALF_UP);
            airportDetailDto.setTmp(tmp + "℃");

            airportDetailDto.setWspd(parmJson.getString("WSPD") + "m/s")
                    .setWdir(parmJson.getString("WDIR") + "度")
                    .setRainfull(parmJson.getString("Rainfull") + "mm")
                    .setWdirName(parmJson.getString("WDIRNAME"));
            //用角度表示风向，是把圆周分成360度，北风(N)是0度(即360度)，东风(E)是90度，南风(S)是180度，西风(W)是270度
            BigDecimal hpa = parmJson.getBigDecimal("Hpa");
            if(hpa != null){
                BigDecimal mpa = hpa.divide(new BigDecimal(100000), 1, BigDecimal.ROUND_HALF_UP);
                airportDetailDto.setHpa(mpa + "Mpa");
                airportDetailDto.setHpa(hpa + "Mpa");
            }
        }
        JSONObject tahJson = dataObject.getJSONObject("TAH");
        if(Objects.nonNull(tahJson)){
            JSONObject parmJson = tahJson.getJSONObject("parmNew");
            BigDecimal hum = parmJson.getBigDecimal("Hum").divide(new BigDecimal(10), 1, BigDecimal.ROUND_HALF_UP);
            airportDetailDto.setHum(hum + "rh");
            BigDecimal tmp = parmJson.getBigDecimal("Tmp").divide(new BigDecimal(10), 1, BigDecimal.ROUND_HALF_UP);
            airportDetailDto.setTmp(tmp + "℃");
        }
        JSONObject mountJson = dataObject.getJSONObject("mount");
        JSONArray mountEquipmentList = mountJson.getJSONArray("mountEquipmentList");
        StringBuilder sb = new StringBuilder();
        if (Objects.nonNull(mountEquipmentList)) {
            for(int i = 0; i < mountEquipmentList.size(); i++){
                JSONObject equipment = mountEquipmentList.getJSONObject(i);
                String name = equipment.getString("name");
                sb.append(name);
                if(i < mountEquipmentList.size()-1){
                    sb.append("、");
                }
            }
            vo.setMountName(sb.toString());
        }
        airportDetailDto.setStatus(dataObject.getString("status"));
        return JsonResult.success(airportDetailDto);
    }

    @Override
    @Transactional(readOnly = true)
    public List<QuestionListDto> getQuestionList(GetQuestionListDto getQuestionListDto){
        getQuestionListDto.setTenantId(ShiroUtils.getTenantId());//新增
        if(ObjectUtil.isNotEmpty(getQuestionListDto.getStartTime()) && ObjectUtil.isNotEmpty(getQuestionListDto.getEndTime())){
            getQuestionListDto.setStartTime(getQuestionListDto.getStartTime() + " 00:00:00");
            getQuestionListDto.setEndTime(getQuestionListDto.getEndTime() + " 23:59:59");
        }

        List<QuestionListDto> questionListDtoList = questionMapper.getIndexQuestion(getQuestionListDto);
        for(QuestionListDto questionListDto : questionListDtoList){
            if(questionListDto.getHandlerImage() != null){
                String[] imgHanders = questionListDto.getHandlerImage().split(",");
                for (int i = 0; i < imgHanders.length; i++) {
                    imgHanders[i] = CommonConfig.imageURL + imgHanders[i];
                }
                String handerImg = StringUtils.join(imgHanders, ",");
                questionListDto.setHandlerImage(handerImg);
            }
        }
        return questionListDtoList;
    }
}
