package com.izouma.wenlvju.web;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.izouma.wenlvju.domain.Organization;
import com.izouma.wenlvju.domain.Setting;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.OrganizationRepo;
import com.izouma.wenlvju.repo.SettingRepo;
import com.izouma.wenlvju.service.SettingService;
import com.izouma.wenlvju.utils.ObjUtils;
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("/setting")
@AllArgsConstructor
public class SettingController extends BaseController {
    private SettingService   settingService;
    private SettingRepo      settingRepo;
    private OrganizationRepo organizationRepo;

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

            //艺考联盟
            if (orig.getFlag() == 5) {
                Organization organization = organizationRepo.findByAllianceId(record.getId()).orElse(null);
                if (ObjectUtil.isNotNull(organization)) {
                    if (!organization.getName().equals(save.getName())) {
                        organization.setAllianceId(null);
                        organizationRepo.save(organization);
                        List<Organization> organizations = organizationRepo.findAllByNameEquals(record.getName());
                        if (CollUtil.isNotEmpty(organizations)) {
                            organization = organizations.get(0);
                            organization.setAllianceId(record.getId());
                            organizationRepo.save(organization);
                        }
                    }
                } else {
                    List<Organization> organizations = organizationRepo.findAllByNameEquals(record.getName());
                    if (CollUtil.isNotEmpty(organizations)) {
                        organization = organizations.get(0);
                        organization.setAllianceId(record.getId());
                        organizationRepo.save(organization);
                    }
                }
            }
            return save;
        }
        if (record.getParent() == null) {
            record.setFlag(settingRepo.nextSort());
        }
        record = settingRepo.save(record);

        if (record.getFlag() == 5) {
            List<Organization> organizations = organizationRepo.findAllByNameEquals(record.getName());
            if (organizations.size() > 0) {
                Organization organization = organizations.get(0);
                organization.setAllianceId(record.getId());
                organizationRepo.save(organization);
            }
        }

        return record;
    }

    @PostMapping("/all")
    public Page<Setting> all(@RequestBody PageQuery pageQuery) {
        return settingService.all(pageQuery);
    }

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

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

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

    @PostMapping("/allList")
    public List<Setting> allList() {
        return settingService.getTree(settingRepo.findAll());
    }

    @PostMapping("/byFlag")
    public List<Setting> byFlag(int flag) {
        List<Setting> tree = settingService.getTree(settingRepo.findAllByFlag(flag));
        if (CollUtil.isEmpty(tree)) {
            return null;
        }
        return tree.get(0).getChildren();
    }
}

