package com.ichangzuo.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ichangzuo.common.result.PageResult;
import com.ichangzuo.common.result.Result;
import com.ichangzuo.common.result.ResultCode;
import com.ichangzuo.system.model.bo.SwVersionBO;
import com.ichangzuo.system.model.entity.*;
import com.ichangzuo.system.model.query.SwVersionPageQuery;
import com.ichangzuo.system.service.impl.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/software")
@RequiredArgsConstructor
public class SoftwareController {
    private final SoftwareServiceImpl softwareService;
    private final FontServiceImpl fontService;
    private final SwVersionServiceImpl versionService;
    private final SwDecribeServiceImpl decribeService;
    private final StatisticsServiceImpl statisticsService;

    @Operation(summary = "分页列表")
    @GetMapping("/page")
    public PageResult<SwVersion> pagedSoftware(SwVersionPageQuery queryParams ) {
        IPage<SwVersion> result = versionService.page(queryParams);
        return PageResult.success(result);
    }

    @GetMapping("/list")
    public Result<List<Software>> listSoftware(){
        List<Software> list = softwareService.list();
        return Result.success(list);
    }

    @GetMapping("/listFont")
    public Result<List<Font>> listFont(){
        List<Font> list = fontService.list();
        return Result.success(list);
    }

    @GetMapping("/lastVersion/{id}/{os}")
    public Result<SwVersionBO> getVersion(
            @Parameter(description = "软件ID(2:ac;3:pro;4:cz)") @PathVariable Integer id,
            @Parameter(description = "操作系统(0:pc;1:android;2:ios)") @PathVariable Integer os
    ){
        int innerId = os;

        if( id==3 ){
            os = 0;
            innerId = 6;
        }
        else if( id==2 && os!=0 ){
            innerId += 2;
        }

        SwVersion version = versionService.lastVersion(id, innerId);

        SwDescribe describe = decribeService.getOne(new LambdaQueryWrapper<SwDescribe>()
                                                    .eq(SwDescribe::getSoftwareId, id)
                                                    .eq(SwDescribe::getOs, os)
                                                    .orderByDesc(SwDescribe::getSoftwareDescribeId)
                                                    .last("limit 1")
                                            );

        SwVersionBO bo = null;
        if(version!=null){
            bo = new SwVersionBO();
            bo.setSoftwareId(id);
            bo.setOs(os);
            bo.setVersion(version.getVersionMajor() + "." + version.getVersionMinor() + "."
                        + version.getVersionModify() + "." + version.getVersionBuild());
            bo.setPackageSize(version.getInstallSize());
            bo.setReleaseDate(version.getReleaseTime());
            bo.setDescribe(version.getDescribeText());
            bo.setInstallPath(version.getInstallPath());

            if(describe!=null) {
                bo.setPictures(describe.getDescribe().split(","));
            }
        }

        return Result.success(bo);
    }

    @PutMapping(value = "/update")
    public Result<?> updateVersion( @RequestBody SwVersion version ) {
        int result = versionService.update(version);
        if(result==-1)
            return Result.failed(ResultCode.PARAM_VERSION_ERROR);
        else if(result==-2)
            return Result.failed(ResultCode.DATABASE_ERROR);

        return Result.success();
    }

    @GetMapping("/maxVersion")
    public Result<?> lastVersion(
            @Parameter(description = "软件ID(2:ac;3:pro;4:cz)") @RequestParam Integer softwareId,
            @Parameter(description = "操作系统(0:pc;1:android;2:ios)") @RequestParam Integer innerId
    ){
        Map<String, Integer> result = new HashMap<>();
        SwVersion version = versionService.lastVersion(softwareId, innerId);
        result.put("major", version!=null ? version.getVersionMajor() : 0);
        result.put("minor", version!=null ? version.getVersionMinor() : 0);
        result.put("modify", version!=null ? version.getVersionModify() : 0);
        result.put("build", version!=null ? version.getVersionBuild() : 0);

        return Result.success(result);
    }

    /**
     * 统计软件下载次数
     * */
    @PutMapping(value = "/swDownload")
    public Result<?> swDownload(
            @Parameter(description = "软件ID(2:ac;3:pro;4:cz)") @RequestParam Integer softwareId,
            @Parameter(description = "操作系统(0:pc;1:android;2:ios)") @RequestParam Integer os){
        int innerId = os;

        if( softwareId==3 ){
            os = 0;
            innerId = 6;
        }
        else if( softwareId==2 && os!=0 ){
            innerId += 2;
        }

        SwVersion version = versionService.lastVersion(softwareId, innerId);
        version.setDownloadNum(version.getDownloadNum()+1);
        versionService.update(version);

        statisticsService.statistics(version.getInnerId(),"download_num", 1);

        return Result.success();
    }

    /**
     * 删除软件版本
     * @param ids
     * @param state
     * @return
     */
    @PutMapping(value = "/{ids}")
    public Result<?> setByIds(
            @Parameter(description = "消息ID，多个以英文逗号(,)分割") @PathVariable String ids,
            @Parameter(description = "设置参数 0=启用 1=禁用") @RequestParam Integer state
    ) {
        boolean result = versionService.setByIds(ids,state);
        return Result.judge(result);
    }
}
