package com.izouma.wenlvju.web;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.izouma.wenlvju.domain.Organization;
import com.izouma.wenlvju.repo.SettingRepo;
import com.izouma.wenlvju.service.OrganizationService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.OrganizationRepo;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.SecurityUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
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;

@RestController
@RequestMapping("/organization")
@AllArgsConstructor
public class OrganizationController extends BaseController {
    private OrganizationService organizationService;
    private OrganizationRepo    organizationRepo;
    private SettingRepo         settingRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Organization save(@RequestBody Organization record) {
        if (record.getId() != null) {
            Organization orig = organizationRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));

            // 艺考联盟
            if (!orig.getName().equals(record.getName())) {
                settingRepo.findByNameLikeAndFlag(record.getName(), 5)
                        .ifPresent(setting -> {
                            if (!organizationRepo.findByAllianceIdAndIdIsNot(setting.getId(), record.getId())
                                    .isPresent()) {
                                record.setAllianceId(setting.getId());
                            }

                        });
            }

            if (StrUtil.isNotBlank(record.getUscc())) {
                Organization byUscc = organizationRepo.findByUscc(record.getUscc());
                if (ObjectUtil.isNotNull(byUscc)) {
                    if (!byUscc.getId().equals(record.getId())) {
                        throw new BusinessException("该统一社会信用代码已被注册");
                    }
                }
            }

            ObjUtils.merge(orig, record);
            return organizationRepo.save(orig);
        }
        record.setUserId(SecurityUtils.getAuthenticatedUser().getId());
        if (StrUtil.isNotBlank(record.getUscc())) {
            Organization byUscc = organizationRepo.findByUscc(record.getUscc());
            if (ObjectUtil.isNotNull(byUscc)) {
                throw new BusinessException("该统一社会信用代码已被注册");
            }
        }
        return organizationRepo.save(record);
    }


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

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

    @GetMapping("/getByUserId/{userId}")
    public Organization getByUserId(@PathVariable Long userId) {
        return organizationRepo.findByUserId(userId).orElseThrow(new BusinessException("无记录"));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        organizationService.del(id);
    }

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

