package com.izouma.zhirongip.web;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.zhirongip.domain.Institution;
import com.izouma.zhirongip.domain.Personal;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.dto.PersonalDTO;
import com.izouma.zhirongip.enums.ApplyStatus;
import com.izouma.zhirongip.enums.AuthorityName;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.InstitutionRepo;
import com.izouma.zhirongip.repo.PersonalRepo;
import com.izouma.zhirongip.repo.UserRepo;
import com.izouma.zhirongip.security.Authority;
import com.izouma.zhirongip.service.PersonalService;
import com.izouma.zhirongip.utils.ObjUtils;
import com.izouma.zhirongip.utils.SecurityUtils;
import com.izouma.zhirongip.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/personal")
@AllArgsConstructor
public class PersonalController extends BaseController {
    private final PersonalService personalService;
    private final PersonalRepo    personalRepo;
    private final InstitutionRepo institutionRepo;
    private final UserRepo        userRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Personal save(@RequestBody Personal record) {
        if (record.getId() != null) {
            Personal orig = personalRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            orig.setStatus(ApplyStatus.PENDING);
            return personalRepo.save(orig);
        }
        Personal byUserId = personalRepo.findByUserId(record.getUserId());
        if (ObjectUtil.isNotNull(byUserId)) {
            throw new BusinessException("已申请");
        }
        Institution institution = institutionRepo.findByUserId(record.getUserId());
        if (ObjectUtil.isNotNull(institution)) {
            throw new BusinessException("已申请机构认证");
        }
        record.setStatus(ApplyStatus.PENDING);
        return personalRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<PersonalDTO> all(@RequestBody PageQuery pageQuery) {
        return personalService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    public Personal get(@PathVariable Long id) {
        return personalRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        Personal personal = personalRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        userRepo.findById(personal.getUserId()).ifPresent(user -> {
            Set<Authority> authoritySet = user.getAuthorities();
            authoritySet.remove(Authority.get(AuthorityName.ROLE_PERSONAL));
            userRepo.save(user);
        });
        personalRepo.softDelete(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<PersonalDTO> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("审核")
    @PostMapping("/audit")
    public void audit(@RequestParam Long id, @RequestParam boolean pass, String remark) {
        personalService.audit(id, pass, remark);
    }

    @PreAuthorize("hasRole('PERSONAL')")
    @GetMapping("/my")
    public Personal my() {
        return personalRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId());
    }
}

