package io.renren.modules.admin.controller;

import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.admin.entity.AttendersEntity;
import io.renren.modules.admin.entity.MemberEntity;
import io.renren.modules.admin.service.AttendersService;
import io.renren.modules.admin.service.MeetingService;
import io.renren.modules.admin.service.MemberService;


/**
 *
 * @author huwhois
 * @email huwhois@163.com
 * @date 2020-12-10 14:56:04
 */
@RestController
@RequestMapping("admin/invitation")
public class InvitationController  {
    @Autowired
    private AttendersService attendersService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MeetingService meetingService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @RequiresPermissions("admin:invitation:list")
    public R list(@RequestParam Map<String, Object> params){
        if (!params.containsKey("meetingId")) {
            return R.error("会议id不可为空");
        }

        PageUtils page = memberService.queryInvitationPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 是否参会
     */
    @PostMapping("/isreceipt")
    @RequiresPermissions("admin:invitation:isreceipt")
    public R isreceipt(@RequestBody Map<String, Object> params){
        if (!params.containsKey("meetingId") || !params.containsKey("id")) {
            return R.error("会议id不可为空 or 会员id不可为空");
        }
        Long meetingId = Long.valueOf(params.get("meetingId").toString());
        Long id = Long.valueOf(params.get("id").toString());
        
        MemberEntity member = memberService.getById(id);
        if (member == null || !meetingService.meetingExist(meetingId)) {
            return R.error("会员不存在 or 会议不存在");
        }

        Long aid = params.get("aid") == null ? 0L : Long.valueOf(params.get("aid").toString());
        int receipt = Integer.valueOf(params.get("receipt").toString());

        if (receipt==1 && aid==null || aid==0) {
            AttendersEntity attenders = new AttendersEntity();
            attenders.setMeetingId(meetingId);
            attenders.setMemberId(id);
            attendersService.save(attenders);

            return R.ok();
        }

        if (receipt==0 && aid!=null && aid!=0) {
            attendersService.removeById(aid);
            return R.ok();
        }

        return null;
    }
}
