package com.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.om.entity.dto.*;
import com.om.entity.po.Apps;
import com.om.entity.po.AppsClients;
import com.om.entity.po.AppsDesc;
import com.om.entity.po.Client;
import com.om.entity.vo.AppUpdateVO;
import com.om.exception.BadReqException;
import com.om.exception.BizException;
import com.om.mapper.AppsMapper;
import com.om.service.IAppsClientsService;
import com.om.service.IAppsDescService;
import com.om.service.IAppsService;
import com.om.service.IClientService;
import com.om.utils.*;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 软件应用表 服务实现类
 * </p>
 *
 * @author henry-ong
 * @since 2024-03-12
 */
@Service
public class AppsServiceImpl extends ServiceImpl<AppsMapper, Apps> implements IAppsService {
    private final AppsMapper appsMapper;

    public AppsServiceImpl(AppsMapper appsMapper) {
        this.appsMapper = appsMapper;
    }

    @Resource
    private IAppsClientsService appsClientsService;

    @Resource
    private IAppsDescService appsDescService;

    @Resource
    private HuaweiObsUtil obsUtil;

    @Resource
    private IClientService clientService;
    @Resource
    private PushUtil pushUtil;

    @Override
    public Page<Apps> findApps(Page<Apps> objectPage, String code, String title) {
        return appsMapper.findApps(objectPage, code, title);
    }


    @Override
    public Result AppUpdate(AppDTO dto) {
        String version = dto.getVersion();
        String guid = dto.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);
        String clientNum = guidDTO.getClientNum();
        String language = dto.getLanguage();

        List<Integer> appids = appsClientsService.lambdaQuery()
                .eq(AppsClients::getClientNum, clientNum)
                .list().stream().map(c -> c.getAppId()).collect(Collectors.toList());

        AppUpdateVO vo = new AppUpdateVO();
        if (!appids.isEmpty()) {
            List<Apps> apps = this.listByIds(appids);
            if (!apps.isEmpty()) {
                Apps apps1 = apps.stream().max(Comparator.comparing(Apps::getCreateTime)).get();

                int result = VersionComparator.compareVersions(version, apps1.getVersion());
                if (result >= 0 ){
                    return Result.ok().message("没有APP更新").result(24001);
                }
                vo.setFileName(apps1.getFileName());
                vo.setFileSize((long) (Double.valueOf(apps1.getFileSize()) * 1024 * 1024));
                vo.setVersion(apps1.getVersion());
                AppsDesc appsDesc = appsDescService.lambdaQuery()
                        .eq(AppsDesc::getAppId, apps1.getId())
                        .eq(AppsDesc::getLanguage, language)
                        .one();
                if (BeanUtil.isNotEmpty(appsDesc)) {
                    vo.setDescription(appsDesc.getDescription());
                } else {
                    vo.setDescription("");
                }
                String uploadUrl = obsUtil.getUploadUrl(apps1.getFileName(), "apps");
                vo.setUrl(uploadUrl);
                vo.setIsUpdate("1");
            }
            return Result.ok(vo);
        }

        return Result.ok().message("没有APP更新").result(24001);
    }

    @SneakyThrows
    @Override
    public Result push(Integer id) {
        //根据id查询
        Apps apps = this.getById(id);
        if (BeanUtil.isEmpty(apps)) {
            throw new BadReqException("该应用软件不存在");
        }
        PushInfo pushInfo = new PushInfo();
        pushInfo.setPushInfoType(1);

        AppInfo appInfo = new AppInfo();
        appInfo.setFileName(apps.getFileName());
        appInfo.setVersion(apps.getVersion());
        appInfo.setFileSize((long) (Double.valueOf(apps.getFileSize())*1024*1024));
        appInfo.setUrl(apps.getSavePath());

        List<Describe> describeList = new ArrayList<>();

        List<AppsDesc> appsDescList = appsDescService.lambdaQuery()
                .eq(AppsDesc::getAppId, id)
                .list();
        if (!appsDescList.isEmpty()){
            for (AppsDesc appsDesc : appsDescList) {
                Describe describe = new Describe();
                describe.setLanguage(appsDesc.getLanguage());
                describe.setDescription(appsDesc.getDescription());
                describeList.add(describe);
            }
        }
        appInfo.setDescribeList(describeList);

        List<AppsClients> appsClientsList = appsClientsService.lambdaQuery()
                .eq(AppsClients::getAppId, id)
                .list();


        if (!appsClientsList.isEmpty()) {
            List<String> clientNums = appsClientsList.stream().map(c -> c.getClientNum()).collect(Collectors.toList());
            String[] tokens = new String[clientNums.size()];
            for (String clientNum : clientNums) {
                int i = 0;
                Client client = clientService.lambdaQuery()
                        .eq(Client::getNumber, clientNum)
                        .one();
                if (BeanUtil.isNotEmpty(client)) {
                    tokens[i] = client.getDeviceToken();
                    i++;
                }
            }
            //调用工具类
            String jsonString = GsonUtils.toJsonString(appInfo);
            pushInfo.setJson(jsonString);
            try {
                pushUtil.sendAndroidListcastJSON(tokens,pushInfo);
            } catch (Exception e) {
                throw new BizException("推送失败！！！");
            }
        }

        return Result.ok();
    }

}
