package com.bohuikeji.frame.module.admin.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysApp;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.service.ISysAppService;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.utils.JwtTokenUtil;
import com.bohuikeji.frame.module.admin.utils.MinioUtil;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

@Api(tags = {"系统相关接口"})
@RestController
@RequestMapping("/api/sys")
@Slf4j
@RequiredArgsConstructor
public class SysApi extends ApiController {

    final ISysConfigService configService;
    final RedisUtil redisUtil;
    final ISysAppService appService;

    /**
     * 获取游客token
     * @return
     */
    @ApiOperation("获取游客token")
    @GetMapping("/token")
    public APIEntity getToken(HttpServletRequest request){
        return APIEntity.success(JwtTokenUtil.crateToken(request));
    }

    /**
     * 上传文件
     * @return
     */
    @ApiOperation("客户端上传文件")
    @PostMapping("/upload/files")
    public APIEntity uploadFiles(@RequestParam("files") MultipartFile[] files){
        return APIEntity.success(MinioUtil.uploadFiles(files));
    }

    /**
     * 上传文件
     * @return
     */
    @ApiOperation("数据迁移上传文件")
    @PostMapping("/data/upload/files")
    public APIEntity dataUploadFiles(@RequestParam("files") MultipartFile[] files,String folder){
        return APIEntity.success(MinioUtil.dataUploadFiles(folder,files));
    }

    /**
     * 派送员安卓端获取更新
     * @return
     */
    @ApiOperation(value = "派送员APP检查更新——安卓",hidden = true)
    @GetMapping("/courier/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name="appid",value="appid",dataType="String", paramType = "query",example ="__UNI__AA5AF7F" ),
            @ApiImplicitParam(name="version",value="版本号",dataType="Integer", paramType = "query",example = "100")})
    public APIEntity courierUpdate(@ApiIgnore @RequestAttribute("JwtUserId") Integer id, String appid, String version){
        log.error("&&&&&&&&&&&&&&&&&&&&&&&&&&&&骑手APP热更新&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
        log.error("&&&&&&&&&&&&&&&&&&&&&&&&&&&&当前版本：{}&&&&&&&&&&&&&&&&&&&&&&&&&&&&",version);
        SysConfig sys=configService.getOneByKey("qishou_apk_version");
        log.error("&&&&&&&&&&&&&&&&&&&&&&&&&&&&最新版本：{}&&&&&&&&&&&&&&&&&&&&&&&&&&&&",sys.getConfigValue());
        if(!sys.getConfigValue().equals(version)){
            JSONObject json=new JSONObject();
            json.put("url",sys.getConfigDataOne());
            json.put("desc",sys.getConfigDataTwo());
            redisUtil.set("courier:version:"+id,version, TimeUnit.DAYS.toSeconds(30));
            return APIEntity.success(json);
        }
        if(sys.getConfigValue().equals(version)){
            redisUtil.del("courier:version:"+id);
            redisUtil.set("courier:version:"+id,version,TimeUnit.DAYS.toSeconds(30));
        }
        return APIEntity.fail("暂无更新！");
    }
    /**
     * 派送员安卓端获取更新
     * @return
     */
    @ApiOperation(value = "客户端APP热更新——安卓",hidden = true)
    @GetMapping("/customer/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name="version",value="版本号",dataType="String", paramType = "query",example = "100")})
    public APIEntity customerUpdate(String version){
        SysApp app=getUpdate(version,"client_android_install");
        if (app!=null){
            return APIEntity.success(app.toUploadJson());
        }
        SysApp hot=getUpdate(version,"client_android_hot");
        if (hot!=null){
            return APIEntity.success(hot.toUploadJson());
        }
        JSONObject json=new JSONObject();
        json.put("state",false);
        return APIEntity.success(json);
    }

    /**
     * 客户端APP强制更新
     * @return
     */
    @ApiOperation(value = "客户端APP强制更新——安卓",hidden = true)
    @GetMapping("/customer/force/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name="version",value="版本号",dataType="String", paramType = "query",example = "100")})
    public APIEntity customerForceUpdate(String version){
        SysConfig sys=configService.getOneByKey("customer_force_apk_version");
        String sVersion = version.replace(".", "");
        String lVersion = sys.getConfigValue().replace(".", "");
        JSONObject json=new JSONObject();
        if (Integer.parseInt(lVersion)>Integer.parseInt(sVersion)) {
            // 去除掉小数点后，转为整数型，对比版本大小
            json.put("url",sys.getConfigDataOne());
            json.put("state",true);
            json.put("newVersion",sys.getConfigDataTwo());
            json.put("desc",sys.getConfigMark().replaceAll("。","\r\n"));
            return APIEntity.success(json);
        }else {
            json.put("state",false);
        }
        return APIEntity.success(json);
    }


    /**
     * 派送员安卓端获取更新
     * @return
     */
    @ApiOperation(value = "客户端APP热更新——IOS",hidden = true)
    @GetMapping("/customer/ios/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name="version",value="版本号",dataType="String", paramType = "query",example = "100")})
    public APIEntity customerUpdateIOS(String version){
        SysApp app=getUpdate(version,"client_ios_install");
        if (app!=null){
            return APIEntity.success(app.toUploadJson());
        }
        SysApp hot=getUpdate(version,"client_ios_hot");
        if (hot!=null){
            return APIEntity.success(hot.toUploadJson());
        }
        JSONObject json=new JSONObject();
        json.put("state",false);
        return APIEntity.success(json);
    }

    /**
     * 客户端APP强制更新
     * @return
     */
    @ApiOperation(value = "客户端APP强制更新——IOS",hidden = true)
    @GetMapping("/customer/force/ios/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name="version",value="版本号",dataType="String", paramType = "query",example = "100")})
    public APIEntity customerForceUpdateIOS(String version){
        SysApp app=getUpdate(version,"client_ios_install");
        if (app!=null){
            return APIEntity.success(app);
        }
        JSONObject json=new JSONObject();
        json.put("state",false);
        return APIEntity.success(json);
    }


    @ApiOperation(value = "骑手端APP热更新——安卓",hidden = true)
    @GetMapping("/update/courier")
    @ApiImplicitParams({
            @ApiImplicitParam(name="version",value="版本号",dataType="String", paramType = "query",example = "100")})
    public APIEntity courierUpdate(String version){
        SysApp app=getUpdate(version,"courier_android_install");
        if (app!=null){
            return APIEntity.success(app.toUploadJson());
        }
        SysApp hot=getUpdate(version,"courier_android_hot");
        if (hot!=null){
            return APIEntity.success(hot.toUploadJson());
        }
        JSONObject json=new JSONObject();
        json.put("state",false);
        return APIEntity.success(json);
    }

    @ApiOperation(value = "骑手端APP强制更新——安卓",hidden = true)
    @GetMapping("/force/update/courier")
    @ApiImplicitParams({
            @ApiImplicitParam(name="version",value="版本号",dataType="String", paramType = "query",example = "100")})
    public APIEntity courierForceUpdate(String version){
        SysApp app=getUpdate(version,"courier_android_install");
        if (app!=null){
            return APIEntity.success(app.toUploadJson());
        }
        JSONObject json=new JSONObject();
        json.put("state",false);
        return APIEntity.success(json);
    }

    /**
     * APP统一更新接口
     * @param version 当前版本号
     * @param role APP类型
     * @param system 系统类型
     * @return
     */
    @ApiOperation(value = "APP统一更新接口",notes = "优先返回安装包更新，若无安装包更新则返回热更新包，前端需要更具(type字段)判断")
    @GetMapping("/app/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name="version",value="版本号",dataType="String", paramType = "query",example = "1.3.25",required = true),
            @ApiImplicitParam(name="role",value="APP类型(courier:骑手端,client:客户端,admin:管理端)",dataType="String", paramType = "",example = "client",required = true),
            @ApiImplicitParam(name="system",value="系统类型(android:安卓,ios:苹果)默认：android",dataType="String", paramType = "String",example = "android")})
    public APIEntity<SysApp> appUpdate(String version, String role, String system){
        if(StringUtils.isBlank(version)){
            return APIEntity.fail("参数错误，参数：version为空");
        }
        if(StringUtils.isBlank(role)){
            return APIEntity.fail("参数错误，参数：role为空");
        }
        if (StringUtils.isBlank(system)){system="android";}
        version=version.toLowerCase(Locale.ROOT);
        role=role.toLowerCase(Locale.ROOT);
        system=system.toLowerCase(Locale.ROOT);
        String[] chis={role,system,"install"};
        SysApp app=appService.selectOneByColumn("app_key",String.join("_",chis));
        if (app==null){
            return APIEntity.fail("参数错误，未找到更新APP");
        }
        if (versionComp(version,app.getVersion())){
            return APIEntity.success(app);
        }
        chis[2]="hot";
        app=appService.selectOneByColumn("app_key",String.join("_",chis));
        if (app==null){
            return APIEntity.fail("参数错误，未找到更新APP");
        }
        if (versionComp(version,app.getVersion())){
            return APIEntity.success(app);
        }
        return APIEntity.fail("暂无更新");
    }


    /**
     * 获取更新结果
     * @param version 当前版本
     * @param key APP_KEY标识
     * @return
     */
    @JsonIgnore
    private SysApp getUpdate(String version, String key){
        SysApp app=appService.selectOneByColumn("app_key",key);
        if(versionComp(version,app.getVersion())){
            return app;
        }
        return null;
    }


    /**
     * 版本号比较
     * @param oldVersion 旧版
     * @param newVersion 新版
     * @return
     */
    /*public static boolean versionComp(String oldVersion,String newVersion){
        String[] oldSp =oldVersion.split("[.]");
        String[] newSp =newVersion.split("[.]");
        for (int i = 0; i < oldSp.length; i++) {
            if (Integer.parseInt(newSp[i])>Integer.parseInt(oldSp[i])){
                return true;
            }
        }
        return false;
    }*/

    public static boolean versionComp(String oldVersion,String newVersion){
        String oldSion = oldVersion.replace(".", "");
        String newSion = newVersion.replace(".", "");
        if (Integer.parseInt(newSion)>Integer.parseInt(oldSion)) {
            log.error("新版本：{},旧版本：{}",newVersion,oldVersion);
            return true;
        }
        return false;
    }
}
