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.InstitutionDTO;
import com.izouma.zhirongip.enums.ApplyStatus;
import com.izouma.zhirongip.enums.AuthorityName;
import com.izouma.zhirongip.repo.PersonalRepo;
import com.izouma.zhirongip.repo.UserRepo;
import com.izouma.zhirongip.security.Authority;
import com.izouma.zhirongip.service.InstitutionService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.InstitutionRepo;
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("/institution")
@AllArgsConstructor
public class InstitutionController extends BaseController {
    private final InstitutionService institutionService;
    private final InstitutionRepo    institutionRepo;
    private final PersonalRepo       personalRepo;
    private final UserRepo           userRepo;

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


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

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

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

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<InstitutionDTO> 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) {
        institutionService.audit(id, pass, remark);
    }

    @PreAuthorize("hasRole('INSTITUTION')")
    @GetMapping("/my")
    public Institution my() {
        return institutionRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId());
    }
}

