package com.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.om.entity.dto.AppBaseDTO;
import com.om.entity.dto.GuidDTO;
import com.om.entity.dto.PushInfo;
import com.om.entity.dto.VciQueryPageDTO;
import com.om.entity.po.*;
import com.om.entity.vo.*;
import com.om.exception.BadReqException;
import com.om.mapper.UserMapper;
import com.om.mapper.VciInfoMapper;
import com.om.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.om.utils.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bmmx
 * @since 2024-02-27
 */
@Service
public class VciInfoServiceImpl extends ServiceImpl<VciInfoMapper, VciInfo> implements IVciInfoService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private IUserVciService userVciService;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private ISdkClientsService sdkClientsService;

    @Resource
    private ISdkVersionInfoService sdkVersionInfoService;

    @Resource
    private ISdkVersionDescribeService sdkVersionDescribeService;

    @Resource
    private IPcbVersionInfoService pcbVersionInfoService;

    @Resource
    private IAppService appService;

    @Resource
    private IAppVersionDescribeService appVersionDescribeService;

    @Resource
    private IAppsClientsService appsClientsService;

    @Resource
    private HuaweiObsUtil obsUtil;

    @Resource
    private PushUtil pushUtil;


    @Override
    public Result addVci(VciInfo vciInfo) {
        if (BeanUtil.isEmpty(vciInfo)){
            throw new BadReqException("参数为空");
        }
        if(vciInfo.getVciNum() == null){
            throw new BadReqException("参数为空");
        }

        VciInfo one = this.lambdaQuery()
                .eq(VciInfo::getVciNum, vciInfo.getVciNum())
                .one();
        if (BeanUtil.isNotEmpty(one)){
            throw new BadReqException("该VCI设备已存在");
        }

        vciInfo.setCreateTime(LocalDateTime.now());
        vciInfo.setUpdateTime(LocalDateTime.now());
        this.save(vciInfo);
        return Result.ok();
    }

    @Override
    public Result addList(List<VciInfo> vciInfos) {
        if (BeanUtil.isEmpty(vciInfos)){
            throw new BadReqException("参数为空");
        }

        for (VciInfo vciInfo : vciInfos) {
            vciInfo.setCreateTime(LocalDateTime.now());
            vciInfo.setUpdateTime(LocalDateTime.now());
        }

        this.saveBatch(vciInfos);
        return Result.ok();
    }

    @Override
    public Result deleteByNum(String vciNum) {

        //根据vciNum查询
        VciInfo one = this.lambdaQuery()
                .eq(VciInfo::getVciNum, vciNum)
                .one();

        if (BeanUtil.isEmpty(one)){
            throw new BadReqException("vci设备不存在");
        }

        //判断客户端账号和vci关联表
        List<UserVci> userVciList = userVciService.lambdaQuery()
                .eq(UserVci::getVciInfoId, one.getId())
                .list();
        if (!userVciList.isEmpty()){
            throw new BadReqException("该vci设备已被客户端账号绑定，不能删除");
        }

        //删除
        this.removeById(one);
        return Result.ok();
    }

    @Override
    public Result updateState(Integer id, Integer state) {
        //根据id查询
        VciInfo vciInfo = this.getById(id);

        if (BeanUtil.isEmpty(vciInfo)){
            throw new BadReqException("vci设备不存在");
        }
        vciInfo.setState(state);
        this.updateById(vciInfo);
        return Result.ok();
    }

    @Override
    public Result getList() {
        List<VciInfo> list = this.list();
        return Result.ok(list);
    }

    @Override
    public Result<List<UserVciVO>> getUserList(Integer vciId) {
        VciInfo vciInfo = this.getById(vciId);
        if (BeanUtil.isEmpty(vciInfo)){
            throw new BadReqException("该vci不存在");
        }
        List<UserVci> list = userVciService.lambdaQuery()
                .eq(UserVci::getVciInfoId, vciId)
                .list();

        if (CollectionUtil.isEmpty(list)){
            return Result.ok(Collections.emptyList());
        }
        List<UserVciVO> vos= new ArrayList<>();
        for (UserVci userVci : list) {
            Integer userId = userVci.getUserId();
            User user = userMapper.selectById(userId);
            UserVciVO userVciVO = BeanUtil.copyProperties(userVci, UserVciVO.class);
            userVciVO.setUsername(user.getUsername());
            vos.add(userVciVO);
        }


        return Result.ok(vos);
    }

    @Override
    public Result<VciQueryPageVO> getPageList(VciQueryPageDTO dto) {
        Integer pageIndex = dto.getPageIndex();
        Integer pageSize = dto.getPageSize();
        String vciNum = dto.getVciNum();


        Page<VciInfo> page = this.lambdaQuery()
                .like(vciNum != null, VciInfo::getVciNum, vciNum)
                .orderByDesc(VciInfo::getCreateTime)
                .page(new Page<>(pageIndex, pageSize));

        VciQueryPageVO vo = new VciQueryPageVO();
        vo.setCurrent((int) page.getCurrent());
        vo.setSize((int) page.getSize());
        vo.setPages((int) page.getPages());
        vo.setTotal((int) page.getTotal());

        if (vciNum != null){
            vo.setSearchCount(true);
        }

        List<VciInfo> records = page.getRecords();
        vo.setRecords(records);
        return Result.ok(vo);
    }

    @Override
    public Result VciUpdate(AppBaseDTO dto) {
        if (BeanUtil.isEmpty(dto)){
           return Result.fail("未获取到数据").result(ResultCode.NO_DATA);
        }

        String guid = dto.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);
        String clientNum = guidDTO.getClientNum();
        String language = dto.getLanguage();
        Integer userId = guidDTO.getUserId();

        AppSDKVO appSDKVO = new AppSDKVO();
        List<SDKData> sdkData = new ArrayList<>();
        List<AppData> appData = new ArrayList<>();

        //根据客户端clientNum查询sdk
        List<Integer> sdkIds = sdkClientsService.lambdaQuery()
                .eq(SdkClients::getClientNum, clientNum)
                .list().stream().map(c -> c.getSdkId()).collect(Collectors.toList());
        if (!sdkIds.isEmpty()){
            List<SdkVersionInfo> sdkVersionInfos = sdkVersionInfoService.listByIds(sdkIds);
            for (SdkVersionInfo sdkVersionInfo : sdkVersionInfos) {
                SDKData sdk = BeanUtil.copyProperties(sdkVersionInfo, SDKData.class);

                int lastIndexOf = sdkVersionInfo.getFileName().lastIndexOf(".");
                sdk.setVersion(sdkVersionInfo.getFileName());
                if (lastIndexOf != -1){
                    sdk.setVersion(sdkVersionInfo.getFileName().substring(0, lastIndexOf));
                }
                String uploadUrl = obsUtil.getUploadUrl(sdkVersionInfo.getFileName(), "appv");
                sdk.setUrl(uploadUrl);
                sdk.setFileSize((long) (Double.valueOf(sdkVersionInfo.getFileSize())*1024*1024));
                sdk.setFileName(sdkVersionInfo.getFileName());
                //根据pcbId查询pcb
                PcbVersionInfo pcbVersionInfo = pcbVersionInfoService.getById(sdkVersionInfo.getPcbId());
                if(BeanUtil.isEmpty(pcbVersionInfo)){
                    throw new BadReqException("该PCB版本不存在！！！");
                }

                SdkVersionDescribe sdkVersionDescribe = sdkVersionDescribeService.lambdaQuery()
                        .eq(SdkVersionDescribe::getSdkId, sdkVersionInfo.getId())
                        .eq(SdkVersionDescribe::getLanguage, language)
                        .one();

                if (!BeanUtil.isEmpty(sdkVersionDescribe)){
                    sdk.setDescription(sdkVersionDescribe.getDescription());
                }else{
                    sdk.setDescription("");
                }

                sdk.setPcbVersion(pcbVersionInfo.getVersionNum());
                sdkData.add(sdk);
            }
        }


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

        if (!appIds.isEmpty()){
            List<App> apps = appService.listByIds(appIds);
            if (apps.isEmpty()){
                return Result.error().result(ResultCode.SERVICE_HANDLE_ERROR);
            }
            for (App app : apps) {
                AppData appData1 = BeanUtil.copyProperties(app, AppData.class);
                int lastIndexOf = app.getFileName().lastIndexOf(".");
                appData1.setVersion(app.getVersionNum());
                if (lastIndexOf != -1){
                    appData1.setVersion(app.getFileName().substring(0, lastIndexOf));
                }
                appData1.setUrl(app.getSavePath());
                appData1.setFileSize((long) (Double.valueOf(app.getFileSize())*1024*1024));
                appData1.setFileName(app.getFileName());
                AppVersionDescribe appVersionDescribe = appVersionDescribeService.lambdaQuery()
                        .eq(AppVersionDescribe::getAppId, app.getId())
                        .eq(AppVersionDescribe::getLanguage, language)
                        .one();
                if (!BeanUtil.isEmpty(appVersionDescribe)){
                    appData1.setDescription(appVersionDescribe.getDescription());
                }else {
                    appData1.setDescription("");
                }



                Integer sdkId = app.getSdkId();
                //根据sdkid查询sdk版本
                SdkVersionInfo sdkVersionInfo = sdkVersionInfoService.getById(sdkId);
                if (!BeanUtil.isEmpty(sdkVersionInfo)){
                    appData1.setMinSdkVersion("");
                    int lastIndexOf1 = sdkVersionInfo.getFileName().lastIndexOf(".");
                    if (lastIndexOf1 != -1){
                        appData1.setMinSdkVersion(sdkVersionInfo.getFileName().substring(0, lastIndexOf1));
                    }
                }
                appData.add(appData1);
            }
        }



        appSDKVO.setAppData(appData);
        appSDKVO.setSdkData(sdkData);
        return Result.ok(appSDKVO);
    }

    @Override
    public Result pushVCI(Integer id) {
        VciInfo vciInfo = this.getById(id);
        if (BeanUtil.isEmpty(vciInfo)){
            throw new BadReqException("该VCI设备不存在");
        }

        PushInfo pushInfo = new PushInfo();
        pushInfo.setPushInfoType(3);

    /*    com.om.entity.dto.VciInfo vciInfo1 = new com.om.entity.dto.VciInfo();
        List<SDKData> sdkData = new ArrayList<>();
        List<AppData> appData = new ArrayList<>();
*/

        String json = "{}";
     //   pushInfo.setJson(JSONUtil.createObj().append("message", "有vci固件升级了"));
       // pushUtil.sendAndroidListcastJSON();

        return null;
    }


}
