
package cn.hanghui.outapi.platform.tenant.controller;

import cn.hanghui.outapi.platform.common.config.log.Log;
import cn.hanghui.outapi.platform.common.controller.BaseController;
import cn.hanghui.outapi.platform.common.entity.rest.RestCode;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.utils.AppTokenUtil;
import cn.hanghui.outapi.platform.common.utils.FileUtils;
import cn.hanghui.outapi.platform.tenant.entity.dto.AppApkDeviceTaskDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.AppApkDeviceTaskPageDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.AppApkDeviceTaskReq;
import cn.hanghui.outapi.platform.tenant.entity.dto.AppApkDeviceTaskVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.AppApkDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.AppApkPageDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.AppApkVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.DeviceTaskStatusVo;
import cn.hanghui.outapi.platform.tenant.entity.enums.BusinessTypeEnum;
import cn.hanghui.outapi.platform.tenant.entity.enums.LogTagEnum;
import cn.hanghui.outapi.platform.tenant.service.AppApkService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;


@Slf4j
@Api(tags = "apk包和安装任务")
@RestController
@RequestMapping(value = "/api/v1/app")
public class AppApkController extends BaseController {

    @Value("${web.address}")
    private String address;

    @Autowired
    private AppApkService appApkService;

    @ApiOperation(value = "apk打包上传file", notes = "apk打包上传 file")
    @PostMapping(value = "/apk/upload")
    public RestResult upload(@RequestParam MultipartFile file, @RequestParam String apkVersion, @RequestParam String apkTitle, @RequestParam(value = "id", required = false) Long id) {
        try {
            String filePath = FileUtils.android_apk_base_path;
            String filename = file.getOriginalFilename();
            String path = FileUtils.saveByCopy(filePath, file);
            path = address.concat(path);
            //TODO... 上传成功 保存记录
            AppApkDto dto = new AppApkDto();
            dto.setId(id);
            dto.setApkPath(path);
            dto.setApkTitle(apkTitle != null ? apkTitle : filename);
            dto.setApkVersion(apkVersion);
            return appApkService.add(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.error("服务器异常，上传失败");
        }
    }

    @ApiOperation(value = "apk添加/编辑", notes = "apk添加/编辑")
    @PostMapping(value = "/apk/add")
    @Log(tag = LogTagEnum.APK,title = "添加/编辑APK",businessTypeEnum = BusinessTypeEnum.INSERT_UPDATE)
    public RestResult add(@RequestBody AppApkDto dto) {
        return appApkService.add(dto);
    }

    @ApiOperation(value = "apk删除", notes = "apk删除")
    @PostMapping(value = "/apk/deleted/{id}")
    @Log(tag = LogTagEnum.APK,title = "删除APK",businessTypeEnum = BusinessTypeEnum.DELETE)
    public RestResult del(@PathVariable(value = "id") @ApiParam(value = "id", required = true) Long id) {
        //删除
        return appApkService.del(id);
    }

    @ApiOperation(value = "查询apk列表（分页）")
    @PostMapping("/apk/page")
    public RestResult<IPage<AppApkVo>> pageApk(@RequestBody AppApkPageDto dto) {
        return appApkService.pageApk(dto);
    }

    @ApiOperation(value = "查询apk列表")
    @PostMapping("/apk/list")
    public RestResult<List<AppApkVo>> apkList() {
        return appApkService.apkList();
    }

    @ApiOperation(value = "添加任务", notes = "添加任务")
    @PostMapping(value = "/task/add")
    @Log(tag = LogTagEnum.APK,title = "添加任务",businessTypeEnum = BusinessTypeEnum.INSERT)
    public RestResult addTask(@RequestBody AppApkDeviceTaskDto dto) {
        return appApkService.addTask(dto);
    }

    @ApiOperation(value = "取消任务", notes = "取消任务")
    @PostMapping(value = "/task/cancel/{id}")
    @Log(tag = LogTagEnum.APK,title = "取消任务",businessTypeEnum = BusinessTypeEnum.OTHER)
    public RestResult cancelTask(@PathVariable(value = "id") @ApiParam(value = "id", required = true) Long id) {
        return appApkService.cancelTask(id);
    }

    @ApiOperation(value = "查询安装任务列表（分页）")
    @PostMapping("/task/page")
    public RestResult<IPage<AppApkDeviceTaskVo>> pageTask(@RequestBody AppApkDeviceTaskPageDto dto) {
        return appApkService.pageTask(dto);
    }

    @ApiOperation(value = "获取安装状态列表", notes = "获取任务状态列表")
    @PostMapping(value = "/task/status/query")
    public RestResult<List<DeviceTaskStatusVo>> taskStatus() {
        return RestResult.ok(Arrays.asList(new DeviceTaskStatusVo(0, "等待中"),
                new DeviceTaskStatusVo(1, "下载中"),
                new DeviceTaskStatusVo(2, "完成"),
                new DeviceTaskStatusVo(3, "已取消")));
    }


    @ApiOperation(value = "【设备调用】根据sn获取等待中的任务", notes = "根据sn获取等待中的任务")
    @PostMapping(value = "/task/query")
    public RestResult taskQuery(@RequestBody AppApkDeviceTaskReq req) {
        List<String> tokens = AppTokenUtil.getTokens();
        if (req == null || req.getToken() == null || "".equals(req.getToken().trim()) || !tokens.contains(req.getToken().trim())) {
            return RestResult.error(RestCode.FORBIDDEN.getMsg());
        }

        if (req.getSn() == null || "".equals(req.getSn().trim())) {
            return RestResult.error("参数有误！");
        }
        return appApkService.taskQuery(req);
    }

    @ApiOperation(value = "【设备调用】任务完成上报", notes = "设备调用】任务完成上报")
    @PostMapping(value = "/task/completed/tracking")
    public RestResult taskCompletedTracking(@RequestBody AppApkDeviceTaskReq req) {
        List<String> tokens = AppTokenUtil.getTokens();
        if (req == null || req.getToken() == null || "".equals(req.getToken().trim()) || !tokens.contains(req.getToken().trim())) {
            return RestResult.error(RestCode.FORBIDDEN.getMsg());
        }
        if (req.getSn() == null || "".equals(req.getSn().trim())) {
            return RestResult.error("参数有误！");
        }
        return appApkService.taskTracking(req, 2);
    }


}
