package com.sptg.permissions.biz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.util.VersionUtil;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.device.api.stream.DeviceUpdateProduceInterface;
import com.sptg.permissions.api.dto.AppPackageDto;
import com.sptg.permissions.api.entity.AppPackage;
import com.sptg.permissions.api.feigns.AppPackageFeign;
import com.sptg.permissions.biz.service.AppPackageServiceInterface;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * title: AppPackageController
 * package: com.sptg.permissions.biz.controller
 * description:app安装包-控制器
 *
 *
 *
 */
@RestController
@RequiredArgsConstructor
public class AppPackageController implements AppPackageFeign {

    private final AppPackageServiceInterface appPackageServiceInterface;

    private final DeviceUpdateProduceInterface deviceUpdateProduceInterface;

    @Override
    @PostMapping(value = "/appPackage/pagingQuery")
    public ResultBean<Page> pagingQuery(@RequestBody PageBean<AppPackage, AppPackageDto> pageBean) {
        Page<AppPackage> page = this.appPackageServiceInterface.pagingQuery(pageBean);
        return new ResultBean<>(ResultEnum.SUCCESS,page);
    }

    @Override
    @PostMapping(value = "/appPackage/add")
    public ResultBean<Boolean> addEntity(@RequestBody AppPackageDto dto) {
        boolean result = this.appPackageServiceInterface.insert(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    @Override
    @PostMapping(value = "/appPackage/edit")
    public ResultBean<Boolean> editEntity(@RequestBody AppPackageDto dto) {
        boolean result = this.appPackageServiceInterface.updateById(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    @Override
    @GetMapping(value = "/appPackage/getEntity/{id}")
    public AppPackage getEntity(@PathVariable(value = "id") Long id) {
        return this.appPackageServiceInterface.selectById(id);
    }

    @Override
    @PostMapping(value = "/appPackage/delete")
    public ResultBean<Boolean> deleteEntity(@RequestBody AppPackageDto dto) {
        AppPackage appPackage = this.appPackageServiceInterface.selectById(dto.getId());
        Assert.notNull(appPackage,"APP安装包信息为空！");
        if(!appPackage.getOrgPosition().contains(dto.getOrgPosition())){
            new ResultBean<>(ResultEnum.FORBIDDEN);
        }
        //更新删除状态
        dto.setStatus(OperationConstant.MINUS_ONE);
        boolean result = this.appPackageServiceInterface.updateById(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    @Override
    @PostMapping(value = "/appPackage/updateEnable")
    public ResultBean<Boolean> updateEnable(@RequestBody AppPackageDto dto) {
        AppPackage appPackage = this.appPackageServiceInterface.selectById(dto.getId());
        Assert.notNull(appPackage,"APP安装包信息为空！");
        if(!appPackage.getOrgPosition().contains(dto.getOrgPosition())){
            new ResultBean<>(ResultEnum.FORBIDDEN);
        }
        //更新启用状态
        boolean result = this.appPackageServiceInterface.updateById(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    @Override
    @PostMapping(value = "/appPackage/getNewestVersion")
    public AppPackage getNewestVersion(@RequestBody AppPackage appPackage) {
        Wrapper<AppPackage> wrapper = new EntityWrapper<>();
        wrapper.eq("s_device_factory",appPackage.getDeviceFactory());
        wrapper.eq("s_device_model_number",appPackage.getDeviceModelNumber());
        wrapper.eq("i_is_enable",1);
        wrapper.eq("i_status", 0);
        //  查询版本列表
        List<AppPackage> list = this.appPackageServiceInterface.selectList(wrapper);
        //  没有相匹配的版包
        if (list.isEmpty()){
            return null;
        }
        //  过滤小于等于当前版本的包
        if (StringUtils.hasText(appPackage.getVersion())){
            list = list.stream()
                    .filter(item -> VersionUtil.compareTo(appPackage.getVersion(), item.getVersion()))
                    .collect(Collectors.toList());
            if (list.isEmpty()){
                return null;
            }
        }
        //  降序排序
        list.sort((app1,app2) -> VersionUtil.compareTo(app1.getVersion(),app2.getVersion()) ? 0 : -1);
        //  返回最大的版本
        return list.get(0);
    }

    @Override
    @PostMapping(value = "/appPackage/appPackageCheck")
    public AppPackage appPackageCheck(@RequestBody AppPackage appPackage) {
        Wrapper<AppPackage> wrapper = new EntityWrapper<>();
        //删除状态
        wrapper.eq("i_status",OperationConstant.ZERO);
        //设备类型
        wrapper.eq("i_device_type",OperationConstant.ONE);
        //启用状态
        wrapper.eq("i_is_enable",OperationConstant.ONE);
        //平台标识
        wrapper.eq("s_platform",appPackage.getPlatform());
        //  查询版本列表
        List<AppPackage> list = this.appPackageServiceInterface.selectList(wrapper);
        //  没有相匹配的版包
        if (list.isEmpty()){
            return null;
        }
        //  过滤小于等于当前版本的包
        if (StringUtils.hasText(appPackage.getVersion())){
            list = list.stream()
                    .filter(item -> VersionUtil.compareTo(appPackage.getVersion(), item.getVersion()))
                    .collect(Collectors.toList());
            if (list.isEmpty()){
                return null;
            }
        }
        //  降序排序
        list.sort((app1,app2) -> VersionUtil.compareTo(app1.getVersion(),app2.getVersion()) ? 0 : -1);
        //  返回最大的版本
        return list.get(0);
        /*//版本号
        if (version != null){
            wrapper.gt("l_version",version);
        }
        //根据版本号降序排序
        wrapper.orderBy("l_version",false);

        List<AppPackage> list = this.appPackageServiceInterface.selectList(wrapper);
        //  没有相匹配的版包
        if (list.isEmpty()){
            return null;
        }
        return list.get(0);*/
    }

    @Override
    @PostMapping(value = "/appPackage/getListByLikeVersion")
    public ResultBean<AppPackage> getListByLikeVersion(@RequestBody AppPackageDto appPackageDto) {
        return new ResultBean<>(ResultEnum.SUCCESS,this.appPackageServiceInterface.getListByLikeVersion(appPackageDto));
    }

    /**
     * 根据型号和设备厂商获取升级包
     * @param model 设备型号
     * @param factory 设备厂商
     * @return
     */
    @Override
    @PostMapping(value = "/appPackage/getListByModelAndFactory/{model}/{factory}")
    public List<AppPackage> getListByModelAndFactory(@PathVariable(value = "model") String model,  @PathVariable(value = "factory") String factory) {
        Assert.notNull(factory,"APP安装包设备厂商不能为空");
        Assert.notNull(model,"APP安装包设备型号不能为空");
        return this.appPackageServiceInterface.getListByModelAndFactory(model, factory);
    }

    @Override
    @GetMapping(value = "/appPackage/checkPackageNameIsExist")
    public boolean checkPackageNameIsExist(@RequestParam("packageName") String packageName) {
        List<AppPackage> list = this.appPackageServiceInterface.getListByPackageName(packageName);
        if (list != null && list.size() > 0){
            return true;
        }
        return false;
    }

    @Override
    @PostMapping(value = "/appPackage/setRestore")
    public boolean setRestore(@RequestBody List<String> appIds) {
        Assert.notEmpty(appIds, "请选择需要设置成恢复版的升级包");
        List<Long> ids = appIds.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
        List<AppPackage> appPackages = this.appPackageServiceInterface.selectBatchIds(ids);
        Map<String, String> factoryModelMap = new HashMap<>();
        List<AppPackage> updateAppPackages = new ArrayList<>();
        for(int i = 0; i < appPackages.size(); i++){
            AppPackage appPackage = appPackages.get(i);
            String factory = factoryModelMap.get(appPackage.getDeviceModelNumber());
            String model = appPackage.getDeviceModelNumber();
            if(factoryModelMap.containsKey(factory)){
                if(factoryModelMap.get(model).equals(model)){ //不能允许相同型号相同厂商的记录，即不能允许同时设置两个相同型号和厂商的升级包为恢复版
                    Assert.notEmpty(appIds, "请选择不同设备型号和厂商的升级包");
                }else{
                    factoryModelMap.put(factory, model);
                    updateAppPackages.add(appPackage);
                }
            }else{
                factoryModelMap.put(factory, model);
                updateAppPackages.add(appPackage);
            }
        }
        for(AppPackage appPackage : updateAppPackages){
            String model = appPackage.getDeviceModelNumber();
            String factory = appPackage.getDeviceFactory();
            AppPackage oldRestore = this.appPackageServiceInterface.getRestoreWithModelAndFactory(model, factory);
            if(oldRestore != null){
                oldRestore.setRestore(OperationConstant.ZERO);
                boolean b = this.appPackageServiceInterface.updateById(oldRestore); //将旧的恢复包修改为正常包，即替换恢复包
                if(b){
                    appPackage.setRestore(OperationConstant.ONE);
                    if(this.appPackageServiceInterface.updateById(appPackage)){//替换成新的恢复包
                        //下发最新恢复包到设备上
                        appPackage.setUpdateMethod(4);
                        Message<AppPackage> build = MessageBuilder.withPayload(appPackage).build();
                        this.deviceUpdateProduceInterface.output().send(build);
                    }
                }else{
                    continue;
                }
            }else{
                appPackage.setRestore(OperationConstant.ONE);
                if(this.appPackageServiceInterface.updateById(appPackage)){//替换成新的恢复包
                    //下发最新恢复包到设备上
                    appPackage.setUpdateMethod(4);
                    Message<AppPackage> build = MessageBuilder.withPayload(appPackage).build();
                    this.deviceUpdateProduceInterface.output().send(build);
                }
            }
        }
        return true;
    }

    @Override
    @PostMapping(value = "/appPackage/getRestore/{model}/{factory}")
    public AppPackage getRestore(@PathVariable(value = "model") String model, @PathVariable(value = "factory") String factory) {
        Assert.notNull(model, "版本包型号不能为空");
        Assert.notNull(factory, "版本包厂商不能为空");
        AppPackage restorePackage = this.appPackageServiceInterface.getRestoreWithModelAndFactory(model, factory);
        return restorePackage;
    }

    @Override
    @GetMapping(value = "/appPackage/checkVersionIsExist")
    public boolean checkVersionIsExist(@RequestParam("version") String version) {
        List<AppPackage> list = this.appPackageServiceInterface.getListByVersion(version);
        if (list != null && list.size() > 0){
            return true;
        }
        return false;
    }
}
