package com.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.om.entity.dto.PushInfo;
import com.om.entity.po.*;
import com.om.entity.vo.AppVO;
import com.om.entity.vo.DignosisPageVO;
import com.om.entity.vo.PcbInfoVO;
import com.om.exception.BadReqException;
import com.om.mapper.AppMapper;
import com.om.mapper.ClientMapper;
import com.om.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.om.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bmmx
 * @since 2024-03-11
 */
@Service
@Slf4j
public class AppServiceImpl extends ServiceImpl<AppMapper, App> implements IAppService {

    @Resource
   private IUserService userService;
    @Resource
   private IAppVersionDescribeService describeService;

  @Resource
    private IAppsClientsService clientsService;
    @Resource
    private ClientMapper clientMapper;

    @Resource
    private PushUtil pushUtil;

    @Override
    public Result add(AppVO appVO) {
        App app = new App();
        BeanUtil.copyProperties(appVO,app);
        this.save(app);
        Integer appId = app.getId();

        //appClient
        for (int i = 0; i < appVO.getClientNums().length; i++) {

            AppsClients appsClients = new AppsClients();
            appsClients.setAppId(appId);
            appsClients.setClientNum(appVO.getClientNums()[i]);
            clientsService.save(appsClients);
        }


        for (int i = 0; i < appVO.getLanguage().length; i++) {

            AppVersionDescribe describe = new AppVersionDescribe();
            describe.setAppId(appId);
            describe.setLanguage(appVO.getLanguage()[i]);
            describe.setDescription(appVO.getDescription()[i]);
            describeService.save(describe);
        }
        return  Result.ok();
    }

    @Override
    public Result delete(Integer id) {

        removeById(id);
        LambdaQueryWrapper<AppVersionDescribe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppVersionDescribe::getAppId,id);
        boolean info = describeService.remove(queryWrapper);
        //还有关联表删除
        LambdaQueryWrapper<AppsClients> clientsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        clientsLambdaQueryWrapper.eq(AppsClients::getAppId,id);
        clientsService.remove(clientsLambdaQueryWrapper);
        return Result.ok();
    }

    @Override
    public Result downloadFile(AppVO app) {
        return null;
    }

    @Override
    public Result getPageList(Integer pageIndex, Integer pageSize, String username) {
        Page<App> page = this.lambdaQuery()
                .like(StringUtils.isNotBlank(username), App::getAdmin, username)
                .page(new Page<>(pageIndex, pageSize));
        List<App> infoList = page.getRecords();

        //返回的List集合
        List<AppVO> appInfoVOS = new ArrayList<>();
        for (int i = 0; i < infoList.size(); i++) {
            //传输的类型
            AppVO appVO = new AppVO();

            App appInfo = infoList.get(i);
            //先copy基本数据
            BeanUtil.copyProperties(appInfo,appVO);

            Integer id = appInfo.getId();
            //先取语言和描述信息
            LambdaQueryWrapper<AppVersionDescribe> describeQueryWrapper = new LambdaQueryWrapper<>();
            describeQueryWrapper.eq(AppVersionDescribe::getAppId,id);
            List<AppVersionDescribe> describeList = describeService.list(describeQueryWrapper);
            //把取出来的数据存入俩个字符串中
            String [] l = new String[describeList.size()];
            String [] d = new String[describeList.size()];

            for (int i1 = 0; i1 < describeList.size(); i1++) {
                l[i1] = describeList.get(i1).getLanguage();
                d[i1] = describeList.get(i1).getDescription();
            }
            appVO.setDescription(d);
            appVO.setLanguage(l);
            String fileName = appVO.getFileName();
            int lastIndexOf = fileName.lastIndexOf(".");
            if (lastIndexOf != -1) {
                appVO.setVersionNum(fileName.substring(0,lastIndexOf));
            }else {
                appVO.setVersionNum("");
            }
            String clientNums = appInfo.getClientNums();
            String[] n = clientNums.substring(1, clientNums.length() - 1).split(",");
            //在取出来客户端编号
            for (int j = 0; j < n.length; j++) {
                String clientNum = n[j];
                LambdaQueryWrapper<Client> clientLambdaQueryWrapper = new LambdaQueryWrapper<>();
                clientLambdaQueryWrapper.eq(Client::getNumber,clientNum);
                Client client = clientMapper.selectOne(clientLambdaQueryWrapper);
                if (client != null) {
                    n[j] = client.getName();
                }else {
                    n[j] = "";
                }

            }
            appVO.setClientNames(n);

            appInfoVOS.add(appVO);
        }

        Page<AppVO> appVOPage = new Page<>();
        BeanUtil.copyProperties(page,appVOPage);

        appVOPage.setRecords(appInfoVOS);

        return Result.ok(appVOPage);
    }

    @Override
    @Transactional
    public Result edit(AppVO appVO) {
        App app = getById(appVO.getId());
        LambdaQueryWrapper<App> infoQueryWapper = new LambdaQueryWrapper<>();
        infoQueryWapper.eq(App::getId,app.getId());
        BeanUtil.copyProperties(appVO,app);

        this.update(app,infoQueryWapper);

        //修改客户端id
        String[] clientNum = appVO.getClientNums();

        LambdaQueryWrapper<AppsClients> clientQueryWrapper = new LambdaQueryWrapper<>();
        clientQueryWrapper.eq(AppsClients::getAppId,appVO.getId());
        clientsService.remove(clientQueryWrapper);
        for (int i = 0; i < clientNum.length; i++) {
            AppsClients clients = new AppsClients();
            clients.setAppId(appVO.getId());
            clients.setClientNum(clientNum[i]);
            log.info("修改之后添加的");
            clientsService.save(clients);
        }

        //没有进行描述和语言进行修改
        String[] language = appVO.getLanguage();
        String[] description = appVO.getDescription();
        LambdaQueryWrapper<AppVersionDescribe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppVersionDescribe::getAppId,appVO.getId());
        describeService.remove(queryWrapper);
        for (int i = 0; i < language.length; i++) {
            AppVersionDescribe describe = new AppVersionDescribe();
            describe.setAppId(appVO.getId());
            describe.setDescription(description[i]);
            describe.setLanguage(language[i]);
            describeService.save(describe);
        }

        return Result.ok();
    }

    @Override
    public Result pushVCI(Integer id) {

        App byId = this.getById(id);
        if(BeanUtil.isEmpty(byId)){
            throw new BadReqException("该app版本不存在");
        }
        PushInfo pushInfo = new PushInfo();
        pushInfo.setPushInfoType(3);
        String jsonString = GsonUtils.toJsonString(JSONUtil.createObj().set("message","有VCI固件更新"));
        pushInfo.setJson(jsonString);
        String clientNums = byId.getClientNums();
        String[] clientNumList = clientNums.substring(1, clientNums.length() - 1).split(",");
        String[] tokens = new String[clientNumList.length];
        for (int i = 0; i < clientNumList.length; i++) {
            LambdaQueryWrapper<Client> clientLambdaQueryWrapper = new LambdaQueryWrapper<>();
            clientLambdaQueryWrapper.eq(Client::getNumber,clientNumList[i]);
            Client client = clientMapper.selectOne(clientLambdaQueryWrapper);
            tokens[i] = client.getDeviceToken();
        }

        try {
            pushUtil.sendAndroidListcastJSON(tokens,pushInfo);
        } catch (Exception e) {
            throw new BadReqException("推送失败！");
        }
        return Result.ok();
    }
}
