package com.izouma.jmrh.web;

import cn.licoy.encryptbody.annotation.decrypt.AESDecryptBody;
import com.izouma.jmrh.annotations.OperLog;
import com.izouma.jmrh.domain.OrgInfo;
import com.izouma.jmrh.domain.User;
import com.izouma.jmrh.dto.OrgInfoDTO;
import com.izouma.jmrh.enums.AuditStatus;
import com.izouma.jmrh.repo.UserRepo;
import com.izouma.jmrh.service.OrgInfoService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.OrgInfoRepo;
import com.izouma.jmrh.utils.ObjUtils;
import com.izouma.jmrh.utils.SecurityUtils;
import com.izouma.jmrh.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/orgInfo")
@AllArgsConstructor
public class OrgInfoController extends BaseController {
    private OrgInfoService orgInfoService;
    private OrgInfoRepo    orgInfoRepo;
    private UserRepo       userRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    @OperLog(value = "企业管理-编辑", type = "编辑")
    public OrgInfo save(@RequestBody OrgInfo record) {
        if (record.getId() != null) {
            OrgInfo orig = orgInfoRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return orgInfoRepo.save(orig);
        }
        OrgInfo save = orgInfoRepo.save(record);
        User user = new User();
        user.setId(record.getUserId());
        user.setOrgInfo(save);
        userRepo.updateUser(user);
        return save;
    }

    @GetMapping("/my")
    public User my() {
        return SecurityUtils.getAuthenticatedUser();
    }

    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<OrgInfo> all(PageQuery pageQuery) {
        Page<OrgInfo> page = orgInfoRepo.findAll(toSpecification(pageQuery, OrgInfo.class), toPageRequest(pageQuery));
        return new PageImpl<>(page.stream()
                .parallel()
                .peek(orgInfo -> orgInfo.setNickname(userRepo.findById(orgInfo.getUserId())
                        .map(User::getNickname)
                        .orElse(null)))
                .collect(Collectors.toList()), page.getPageable(), page.getTotalElements());
    }

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

    @GetMapping("/urlListSupplyDemand")
    public Page<Map<String, Object>> listSupplyDemand(PageQuery pageQuery) {
        long id = Long.parseLong(String.valueOf(pageQuery.getQuery().get("id")));
        String[] split = pageQuery.getSort().split(",");
        Sort sort = new Sort(split[1].equals("desc") ? Sort.Direction.DESC : Sort.Direction.ASC, split[0]);
        Page<Map<String, Object>> created_at = orgInfoRepo
                .listSupplyDemand(id, PageRequest.of(pageQuery.getPage(), pageQuery.getSize(), sort));
        return created_at;
    }

    @GetMapping("/getAllCount/{id}")
    public Map<String, Object> getAllCount(@PathVariable Long id) {
        return orgInfoService.getAllCount(id);
    }

    @PostMapping("/del/{id}")
    @OperLog(value = "企业管理-删除", type = "删除")
    public void del(@PathVariable Long id) {
        orgInfoRepo.deleteById(id);
    }

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

    @PostMapping("/audit")
    @OperLog(value = "企业管理-审核", type = "审核")
    public void audit(@RequestParam Long id, @RequestParam boolean pass) {
        OrgInfo orgInfo = orgInfoRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        orgInfo.setStatus(pass ? AuditStatus.PASS : AuditStatus.DENY);
        orgInfo.setAuditTime(LocalDateTime.now());
        orgInfoRepo.save(orgInfo);
    }

    @PostMapping("/saveAll")
    public void saveAll() {
        userRepo.saveAll(userRepo.findAll());
    }

    @PostMapping("/upload")
    public void upload(MultipartFile file) throws IOException {
        orgInfoService.upload(file);
    }
}

