package com.ly.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ly.controller.util.Result;
import com.ly.controller.util.RoleEnum;
import com.ly.controller.util.TokenUtils;
import com.ly.domain.Approval;
import com.ly.domain.Role;
import com.ly.domain.User;
import com.ly.service.ApprovalService;
import com.ly.service.RoleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RequestMapping("/approval")
@RestController
public class ApprovalController {
    @Resource
    private ApprovalService approvalService;



    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        approvalService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        approvalService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(approvalService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(approvalService.getById(id));
    }

    @PostMapping
    public Result save(@RequestBody Approval approval) {
        if (approval.getId() == null) {
            // 新增
            approval.setTime(DateUtil.today());
            approval.setUser(TokenUtils.getCurrentUser().getUsername());
        }
        approvalService.saveOrUpdate(approval);
        return Result.success();
    }

    // 分页查询做一下筛选
    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Approval> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        User currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.tenderee.toString().equals(currentUser.getRole())) {  // 角色是招标人
            queryWrapper.eq("user", currentUser.getUsername()).or().eq("state","审核通过");
        }
        return Result.success(approvalService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}
