package com.tofly.feesapi.sfgl.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.sfgl.entity.YyWyjjmrq;
import com.tofly.feesapi.sfgl.service.YyWyjjmrqService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/yywyjjmrq")
@Api(tags = "违约金减免日期接口")
public class YyWyjjmrqController {

    @Autowired
    private YyWyjjmrqService yyWyjjmrqService;

    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public ResultRespone getYyWyjjmrqPage(Page page, @ModelAttribute YyWyjjmrq yyWyjjmrq) {
        return ResultRespone.success(yyWyjjmrqService.page(page, Wrappers.query(yyWyjjmrq)));
    }

    @GetMapping("/list")
    @ApiOperation(value = "返回list数据", response = YyWyjjmrq.class, responseContainer = "List")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", dataType = "String"),
            @ApiImplicitParam(name = "yxbz", value = "有效标识", dataType = "String")
    })
    public ResultRespone<List<YyWyjjmrq>> getYyWyjjmrqList(String year, String yxbz) {
        return ResultRespone.success(yyWyjjmrqService.lambdaQuery()
                .apply(StringUtil.isNotEmpty(year), String.format("to_char(jmrq,'yyyy')='%s'", year))
                .eq(StringUtil.isNotNull(yxbz), YyWyjjmrq::getYxbz, yxbz)
                .list());
    }

    @ApiOperation(value = "新增或修改违约金减免日期")
    @PostMapping("/saveorupdate")
    public ResultRespone save(@RequestBody YyWyjjmrq yyWyjjmrq) {
        if (yyWyjjmrq.getJmrq() == null) {
            return ResultRespone.failed("减免日期不能为空");
        }
        if (yyWyjjmrq.getYxbz() == null) {
            return ResultRespone.failed("有效标志不能为空");
        }
        if (!yyWyjjmrq.getYxbz().equals("0") && !yyWyjjmrq.getYxbz().equals("1")) {
            return ResultRespone.failed("有效标志只能为0或1");
        }

        long count = yyWyjjmrqService.lambdaQuery()
                .eq(YyWyjjmrq::getJmrq, yyWyjjmrq.getJmrq())
                .count();
        yyWyjjmrq.setCzrybm(SecurityUtils.getUserId().toString());
        yyWyjjmrq.setCzryxm(SecurityUtils.getUser().getRealName());
        if (count > 0) {
            return ResultRespone.success(yyWyjjmrqService.updateById(yyWyjjmrq));
        }
        return ResultRespone.success(yyWyjjmrqService.save(yyWyjjmrq));
    }
}
