package cn.chnmuseum.party.web.controller;

import cn.chnmuseum.party.common.log.MethodLog;
import cn.chnmuseum.party.common.log.OperModule;
import cn.chnmuseum.party.common.log.OperType;
import cn.chnmuseum.party.common.validator.groups.Add;
import cn.chnmuseum.party.common.validator.groups.Update;
import cn.chnmuseum.party.model.TAppVersion;
import cn.chnmuseum.party.model.TUser;
import cn.chnmuseum.party.service.TAppVersionService;
import cn.chnmuseum.party.web.controller.base.BaseController;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 *  前端控制器
 * </pre>
 *
 * @author Danny Lee
 * @since 2021-03-29
 */
@Slf4j
@RestController
@RequestMapping("/tAppVersion")
@Api(tags = {"APP版本操作接口"})
public class TAppVersionController extends BaseController {

    @Resource
    private TAppVersionService tAppVersionService;

    @PostMapping("/save")
    @RequiresAuthentication  //@RequiresPermissions("t:app:version:save")
    @ApiOperation(value = "添加", notes = "添加")
    @MethodLog(operModule = OperModule.APPVERSION, operType = OperType.ADD)
    public Map<String, Object> saveTAppVersion(@Validated(value = {Add.class}) TAppVersion tAppVersion) {
        final LambdaQueryWrapper<TAppVersion> eq = Wrappers.<TAppVersion>lambdaQuery().eq(TAppVersion::getAppVersion, tAppVersion.getAppVersion().trim());
        final List<TAppVersion> list = this.tAppVersionService.list(eq);
        if (!list.isEmpty() && list.size() > 1) {
            // 保存失败
            return getFailResult("版本号不能重复");
        }

        TUser user = getcurUser();
        // 默认不为当前版本
        if (tAppVersion.getIsCurrent() == null) {
            tAppVersion.setIsCurrent(0);
        }
        tAppVersion.setUserId(user.getId());
        tAppVersion.setUserName(user.getUserName());
        // 如果有其他版本是当前版本状态,将其当前版本状态取消
        QueryWrapper<TAppVersion> qw = new QueryWrapper<>();
        qw.eq("is_current", 1);
        List<TAppVersion> currentList = tAppVersionService.list(qw);
        if (currentList != null && currentList.size() > 0 && tAppVersion.getIsCurrent() == 1) {
            currentList.forEach(c -> {
                c.setIsCurrent(0);
            });
            tAppVersionService.updateBatchById(currentList);
        }
        // 保存业务节点信息
        boolean result = tAppVersionService.save(tAppVersion);
        // 返回操作结果
        if (result) {
            return getSuccessResult();
        } else {
            // 保存失败
            return getFailResult();
        }
    }

    @PutMapping("/update")
    @RequiresAuthentication  //@RequiresPermissions("t:app:version:update")
    @ApiOperation(value = "修改信息", notes = "修改信息")
    @MethodLog(operModule = OperModule.APPVERSION, operType = OperType.UPDATE)
    public Map<String, Object> updateTAppVersion(@Validated(value = {Update.class}) TAppVersion tAppVersion) {
        // 默认不为当前版本
        if (tAppVersion.getIsCurrent() == null) {
            tAppVersion.setIsCurrent(0);
        }
        // 如果有其他版本是当前版本状态,将其当前版本状态取消
        QueryWrapper<TAppVersion> qw = new QueryWrapper<>();
        qw.eq("is_current", 1);
        List<TAppVersion> currentList = tAppVersionService.list(qw);
        if (currentList != null && currentList.size() > 0 && tAppVersion.getIsCurrent() == 1) {
            currentList.stream().forEach(c -> {
                c.setIsCurrent(0);
            });
            tAppVersionService.updateBatchById(currentList);
        }
        // 更新版本信息
        boolean flag = tAppVersionService.updateById(tAppVersion);

        if (flag) {
            return getSuccessResult();
        }
        return getFailResult();
    }

    @DeleteMapping("/delete/{id}")
    @RequiresAuthentication  //@RequiresPermissions("t:app:version:delete")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "标识ID", paramType = "path", dataType = "String")
    })
    @MethodLog(operModule = OperModule.APPVERSION, operType = OperType.DELETE)
    public Map<String, Object> deleteTAppVersion(@PathVariable("id") String id) {
        boolean result = tAppVersionService.removeById(id);
        if (result) {
            return getSuccessResult();
        }
        return getFailResult();
    }

    @GetMapping("/getList")
    @RequiresAuthentication  //@RequiresPermissions("t:app:version:list")
    @ApiOperation(value = "获取全部列表(无分页)", notes = "获取全部列表(无分页)")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "isCurrent", value = "是否为当前版本 0:否 1:是", paramType = "query", dataType = "String")
    })
    @MethodLog(operModule = OperModule.APPVERSION, operType = OperType.SELECT)
    public Map<String, Object> getTAppVersionList(String isCurrent) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq(StringUtils.isNotEmpty(isCurrent), "is_current", isCurrent).orderByDesc("update_time");
        List<TAppVersion> tAppVersionList = tAppVersionService.list(qw);
        return getResult(tAppVersionList);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isCurrent", value = "是否为当前版本 0:否 1:是", paramType = "query", dataType = "String")
    })
    @PostMapping("/getPageList")
    @RequiresAuthentication  //@RequiresPermissions("t:app:version:page")
    @ApiOperation(value = "获取分页列表", notes = "获取分页列表")
    @MethodLog(operModule = OperModule.APPVERSION, operType = OperType.SELECT)
    public Map<String, Object> getTAppVersionPageList(LocalDate startDate, LocalDate endDate, String isCurrent) {
        LambdaQueryWrapper<TAppVersion> queryWrapper = new LambdaQueryWrapper<>();
        // 查询是否为当前版本
        if (StringUtils.isNotBlank(isCurrent)) {
            queryWrapper.like(TAppVersion::getIsCurrent, isCurrent);
        }
        // 查询时间范围
        if (startDate != null && endDate != null) {
            queryWrapper.ge(TAppVersion::getUpdateTime, startDate.atTime(0, 0, 0))
                    .le(TAppVersion::getUpdateTime, endDate.atTime(23, 59, 59));
        }

        queryWrapper.select().orderByDesc(TAppVersion::getUpdateTime);
        Page<TAppVersion> page = this.tAppVersionService.page(getPage(), queryWrapper);
        return getResult(page);
    }

    @ApiOperation(value = "获取详情", notes = "获取详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识ID", dataType = "String", paramType = "path")
    })
    @GetMapping("/get/{id}")
    @RequiresAuthentication  //@RequiresPermissions("t:app:version:get:id")
    @MethodLog(operModule = OperModule.APPVERSION, operType = OperType.SELECT)
    public Map<String, Object> getById(@PathVariable("id") String id) {
        TAppVersion tAppVersion = tAppVersionService.getById(id);
        return getResult(tAppVersion);
    }

}