package com.jd.lightapplication.controller;

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

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


@Slf4j
@RestController()
@RequestMapping("/api/meeting/personnel")
@Api(tags = "参会人员")
public class MeetingPersonnelController {

    @Resource
    private MeetingPersonnelService meetingPersonnelService;

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

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

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

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

    @GetMapping("/queryByMeetingId")
    @ApiOperation(value = "5、根据会议id查询所有参会人员")
    public R queryByMeetingId(Long meetingId) {
        LambdaQueryWrapper<MeetingPersonnel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MeetingPersonnel::getMeetingId, meetingId);
        return R.success(meetingPersonnelService.list(wrapper));
    }

    @PostMapping("/saveBath")
    @ApiOperation(value = "6、添加参会人员")
    @Transactional(rollbackFor = Exception.class)
    public R saveBath(@RequestBody List<MeetingPersonnel> meetingPersonnelList) {
        //先删除所有的参会人员
        LambdaQueryWrapper<MeetingPersonnel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MeetingPersonnel::getMeetingId, meetingPersonnelList.get(0).getMeetingId());
        meetingPersonnelService.remove(wrapper);
        //再添加参会人员
        meetingPersonnelList.stream().map(t -> {
            t.setCreateTime(DateUtil.now());
            return t;
        }).collect(Collectors.toList());
        //参会人员添加账号
        meetingPersonnelService.addAccount(meetingPersonnelList);
        return R.success(meetingPersonnelService.saveBatch(meetingPersonnelList));
    }

}