package com.bonus.canteen.core.android.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.bonus.canteen.core.android.dto.AppDTO;
import com.bonus.canteen.core.android.mapper.DeviceMapper;
import com.bonus.canteen.core.android.service.DeviceService;
import com.bonus.canteen.core.android.vo.*;
import com.bonus.canteen.core.cook.domain.CookRecipe;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.houqin.constant.GlobalConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 19814
 */
@Service
public class DeviceServiceImpl implements DeviceService {
    @Resource
    private DeviceMapper mapper;

    private static final Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);

    /**
     * Android 人脸识别 默认 应用ID和应用密钥
     */
    private static final String DEFAULT_APP_ID = "52XE2dQBtdmMsfDMvyKmPCCPyFsc4jvo8TKvAdaYfr28";
    private static final String DEFAULT_APP_KEY = "9YFPa6eiuNQAFnzJUadn4LaR8w1bcw3a5ZWYZB6FB57Y";

    @Override
    public AjaxResult getDeviceInfo(AppDTO dto) {
        //判断设备是否存在
        DeviceInfoVo deviceInfoVo = mapper.getDeviceInfo(dto);
        if (deviceInfoVo == null) {
            return AjaxResult.error("设备不存在");
        }
        List<ParamVO> list = mapper.getParamInfo();
        if (list != null && !list.isEmpty()) {
            for (ParamVO vo : list) {
                String key = vo.getParamKey();
                String value = vo.getParamValue();
                if (key == null) {
                    continue;
                }
                switch (vo.getParamKey()) {
                    case "app_id":
                        deviceInfoVo.setAppId(value);
                        break;
                    case "app_key":
                        deviceInfoVo.setAppKey(value);
                        break;
                    default:
                        break;
                }
            }
        }else{
            // 如果没有参数信息，设置默认值
            deviceInfoVo.setAppId(DEFAULT_APP_ID);
            deviceInfoVo.setAppKey(DEFAULT_APP_KEY);
        }
        deviceInfoVo.setTenantId(String.valueOf(GlobalConstants.TENANT_ID));
        return AjaxResult.success(deviceInfoVo);
    }

    @Override
    public AjaxResult getAppVersion(AppDTO dto) {
        AppVersionVo appVersionVo = mapper.getAppVersion(dto);
        if (appVersionVo == null){
            return AjaxResult.success("无需更新");
        }
        return AjaxResult.success(appVersionVo);
    }

    @Override
    public ParamSettingVO getParamInfo() {
        List<ParamVO> list = mapper.getParamInfo();
        ParamSettingVO paramSettingVO = new ParamSettingVO();
        if (list != null && !list.isEmpty()) {
            for (ParamVO vo : list) {
                String key = vo.getParamKey();
                String value = vo.getParamValue();
                if (key == null) {
                    continue;
                }
                switch (vo.getParamKey()) {
                    case "site_url":
                        paramSettingVO.setIpAddress(value);
                        break;
                    case "face_pass_rate":
                        paramSettingVO.setFacePassRate(value);
                        break;
                    case "mqtt_address":
                        paramSettingVO.setMqttAddress(value);
                        break;
                    case "mqtt_user_name":
                        paramSettingVO.setMqttUserName(value);
                        break;
                    case "mqtt_pass_word":
                        paramSettingVO.setMqttPassword(value);
                        break;
                    case "app_id":
                        paramSettingVO.setAppId(value);
                        break;
                    case "app_key":
                        paramSettingVO.setAppKey(value);
                        break;
                    case "face_prefix":
                        paramSettingVO.setPhotoPrefixes(value);
                        break;
                    case "version":
                        paramSettingVO.setVersion(value);
                        break;
                    default:
                        break;
                }
            }
        }
        return paramSettingVO;
    }


    @Override
    public CookRecipeCompressVO getMenuInfoBySn(String machineSn) {
        CookRecipeCompressVO issueRecipe = new CookRecipeCompressVO();
        //判断当前设备是否存在菜谱
        Long recipeId = mapper.getRecipeIdBySn(machineSn);
        if (recipeId == 0){
            return issueRecipe;
        }
        //查询菜谱信息
        CookRecipe menuRecipe = mapper.getOneById(recipeId);
        //查询所有的detailsId
        List<CookMenuAndroidRecipeDetailVO> menuRecipeDetailList = mapper.selectMenuRecipeDetailLists(recipeId);
        if (ObjectUtil.isEmpty(menuRecipeDetailList)){
            return issueRecipe;
        }
        List<Long> detailIds = menuRecipeDetailList.stream().map(CookMenuAndroidRecipeDetailVO::getDetailId).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(detailIds)){
            return issueRecipe;
        }
        //查询所有的dishesId
        List<CookRecipeDetailCompressVO> recipeDishList = mapper.selectRecipeDishList(detailIds);
        if (ObjectUtil.isEmpty(recipeDishList)){
            return issueRecipe;
        }
        List<Long> dishesIds = recipeDishList.stream().map(CookRecipeDetailCompressVO::getDishesId).collect(Collectors.toList());
        //查询菜品
        List<CookRecipeMealCompressVO> menuList = mapper.getMenuRecipeListByDishesIds(dishesIds);
        //菜品应用日期列表
        List<LocalDate> applyDateList = menuRecipeDetailList.stream().map(CookMenuAndroidRecipeDetailVO::getApplyData).collect(Collectors.toList());
        applyDateList = applyDateList.stream().distinct().collect(Collectors.toList());
        //查询所有的餐次
        List<CookMealTimeVO> mealTimeList = mapper.getMealTimeList(menuRecipe.getStallId());
        List<CookRecipeDateCompressVO> dateList = new ArrayList<>();
        for (LocalDate date : applyDateList){
            CookRecipeDateCompressVO dateCompressVO = new CookRecipeDateCompressVO();
            List<CookRecipeIntervalCompressVO> intervalList = new ArrayList<>();
            for (CookMealTimeVO mealTimeVO : mealTimeList){
                CookRecipeIntervalCompressVO intervalCompressVO = new CookRecipeIntervalCompressVO();
                intervalCompressVO.setIntervalId(Long.valueOf(mealTimeVO.getMealTimeType()));
                intervalCompressVO.setIntervalName(mealTimeVO.getMealTimeName());
                intervalCompressVO.setStartTime(LocalTime.parse(mealTimeVO.getStartTime()));
                intervalCompressVO.setEndTime(LocalTime.parse(mealTimeVO.getEndTime()));
                for (CookMenuAndroidRecipeDetailVO menuAndroidRecipeDetailVO : menuRecipeDetailList){
                    if (mealTimeVO.getMealTimeType().equals(menuAndroidRecipeDetailVO.getMealTimeType())){
                        List<CookRecipeDetailCompressVO> recipeDetailList = recipeDishList.stream().filter(x -> x.getDetailId().equals(menuAndroidRecipeDetailVO.getDetailId())).collect(Collectors.toList());
                        intervalCompressVO.setProductList(recipeDetailList);
                        break;
                    }
                }
                intervalList.add(intervalCompressVO);
            }
            dateCompressVO.setApplyDate(date);
            dateCompressVO.setIntervalList(intervalList);
            dateList.add(dateCompressVO);
        }
        logger.info("menuRecipe : {} ", menuRecipe);

        if(menuRecipe.getRecipeType() !=null){
            issueRecipe.setRecipeType(Integer.valueOf(menuRecipe.getRecipeType()+""));
        }
        issueRecipe.setRecipeId(menuRecipe.getRecipeId());
        if(menuRecipe.getUpdateTime() !=null) {
            issueRecipe.setUptime(menuRecipe.getUpdateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime());
        } else {
            issueRecipe.setUptime(LocalDateTime.now());

        }
        issueRecipe.setDateList(dateList);
        issueRecipe.setMealList(menuList);
        return issueRecipe;
    }


    @Override
    public DeviceTimeIntervalVO intervalConfig(String machineSn) {
        DeviceTimeIntervalVO deviceTimeIntervalVO = new DeviceTimeIntervalVO();
        deviceTimeIntervalVO.setLevel(2);
        Long recipeId = mapper.getRecipeIdBySn(machineSn);
        if (recipeId == 0){
            return new DeviceTimeIntervalVO();
        }
        //查询菜谱信息
        CookRecipe menuRecipe = mapper.getOneById(recipeId);
        if (menuRecipe == null){
            return new DeviceTimeIntervalVO();
        }
        List<DeviceMealtimeVO> basicsTimeIntervals = mapper.getBasicsTimeIntervals(menuRecipe.getStallId());
        if (basicsTimeIntervals == null || basicsTimeIntervals.isEmpty()){
            basicsTimeIntervals = new ArrayList<>();
        }
        deviceTimeIntervalVO.setBasicsTimeIntervals(basicsTimeIntervals);
        return deviceTimeIntervalVO;
    }
}
