package com.jd.lightapplication.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jd.lightapplication.common.lang.R;
import com.jd.lightapplication.model.MeetingArrange;
import com.jd.lightapplication.service.MeetingArrangeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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


@Slf4j
@RestController()
@RequestMapping("/api/meeting/arrange")
@Api(tags = "议程安排")
public class MeetingArrangeController {

    @Resource
    private MeetingArrangeService meetingArrangeService;

    @GetMapping("/list")
    @ApiOperation(value = "1、分页查询")
    public R queryPageBean(Page page) {
        return R.success(meetingArrangeService.page(page));
    }

    @PostMapping("/addBean")
    @ApiOperation(value = "2、新增")
    public R addBean(@RequestBody MeetingArrange meetingArrange) {
        meetingArrangeService.save(meetingArrange);
        return R.success();
    }

    @PostMapping("/updateBean")
    @ApiOperation(value = "3、修改")
    public R updateBean(@RequestBody MeetingArrange meetingArrange) {
        meetingArrangeService.updateById(meetingArrange);
        return R.success();
    }

    @PostMapping("/deleteById")
    @ApiOperation(value = "4、删除")
    public R deleteById(long id) {
        meetingArrangeService.removeById(id);
        return R.success();
    }

    @GetMapping("/queryByMeetingId")
    @ApiOperation(value = "5、根据会议id查询所有议程安排")
    public R queryByMeetingId(Long meetingId) {
        LambdaQueryWrapper<MeetingArrange> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MeetingArrange::getMeetingId, meetingId);
        wrapper.orderByAsc(MeetingArrange::getSort);
        return R.success(meetingArrangeService.list(wrapper));
    }

    @PostMapping("/saveBath")
    @ApiOperation(value = "6、添加议程安排")
    @Transactional(rollbackFor = Exception.class)
    public R saveBath(@RequestBody List<MeetingArrange> meetingArrangeList) {
        //先删除所有的议程安排
        LambdaQueryWrapper<MeetingArrange> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MeetingArrange::getMeetingId, meetingArrangeList.get(0).getMeetingId());
        meetingArrangeService.remove(wrapper);
        //再添加议程安排
        meetingArrangeList.stream().map(t -> {
            t.setCreateTime(DateUtil.now());
            return t;
        }).collect(Collectors.toList());
        return R.success(meetingArrangeService.saveBatch(meetingArrangeList));
    }

}