package com.vctgo.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vctgo.common.core.exception.ServiceException;
import com.vctgo.common.core.utils.poi.ExcelUtil;
import com.vctgo.common.core.web.controller.BaseController;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.log.annotation.Log;
import com.vctgo.common.log.enums.BusinessType;
import com.vctgo.common.security.annotation.Logical;
import com.vctgo.common.security.annotation.RequiresPermissions;
import com.vctgo.system.api.domain.SysTenant;
import com.vctgo.system.api.domain.dto.SysBranchKindergartenDto;
import com.vctgo.system.domain.SysBranchKindergarten;
import com.vctgo.system.service.ISysBranchKindergartenService;
import com.vctgo.system.service.ISysTenantService;
import com.vctgo.system.util.ConstantUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 幼儿园管理基本信息Controller
 *
 * @author wanglonghua
 * @date 2023-06-05`
 */
@RestController
@RequestMapping("/branch")
public class SysBranchKindergartenController extends BaseController {
    @Autowired
    private ISysBranchKindergartenService sysBranchKindergartenService;

    @Autowired
    private ISysTenantService sysTenantService;

    /**
     * 查询幼儿园管理基本信息列表
     */
    @RequiresPermissions(value = {"system:branch:page", "system:tenant:branch:page"}, logical = Logical.OR)
    @GetMapping("/page")
    public AjaxResult pageList(SysBranchKindergarten sysBranchKindergarten) {
        IPage<SysBranchKindergarten> list = sysBranchKindergartenService.selectSysBranchKindergartenPage(sysBranchKindergarten);
        return AjaxResult.success(list);
    }

    /**
     * 查询幼儿园管理基本信息列表
     */
    @GetMapping("/list/all")
    public AjaxResult list(SysBranchKindergartenDto sysBranchKindergarten) {
        List<SysBranchKindergarten> list = sysBranchKindergartenService.selectSysBranchKindergartenList(sysBranchKindergarten);
        return AjaxResult.success(list);
    }

    /**
     * 导出幼儿园管理基本信息列表
     */
    @RequiresPermissions("system:branch:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBranchKindergartenDto sysBranchKindergarten) {
        List<SysBranchKindergarten> list = sysBranchKindergartenService.selectSysBranchKindergartenList(sysBranchKindergarten);
        ExcelUtil<SysBranchKindergarten> util = new ExcelUtil<SysBranchKindergarten>(SysBranchKindergarten.class);
        util.exportExcel(response, list, "幼儿园管理基本信息数据");
    }

    /**
     * 获取幼儿园管理基本信息详细信息
     */
    @RequiresPermissions("system:branch:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        SysBranchKindergarten sysBranchKindergarten = sysBranchKindergartenService.selectSysBranchKindergartenById(id);
        return AjaxResult.success(sysBranchKindergarten);
    }

    /**
     * 获取幼儿园管理基本信息详细信息
     */
    @GetMapping(value = "/kindergarten/{id}")
    public AjaxResult getKindergartenInfo(@PathVariable("id") Long id) {
        SysBranchKindergarten sysBranchKindergarten = sysBranchKindergartenService.selectSysBranchKindergartenById(id);
        return AjaxResult.success(sysBranchKindergarten);
    }

    /**
     * 根据幼儿园集团ID获取幼儿园列表
     */
    @GetMapping(value = "/kindergarten/list/{gardenId}")
    public AjaxResult getKindergartenListByGardenId(@PathVariable("gardenId") Long gardenId) {
        List<SysBranchKindergarten> sysBranchKindergartenList = sysBranchKindergartenService.getKindergartenListByGardenId(gardenId);
        return AjaxResult.success(sysBranchKindergartenList);
    }

    /**
     * 判断一个幼儿园是否已开通幼儿园租户
     */
    @GetMapping("/detail/{branchId}")
    public AjaxResult branchTenantDetail(@PathVariable Long branchId) {
        SysTenant sysTenant = new SysTenant();
        sysTenant.setBranchId(branchId);
        sysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
        return AjaxResult.success(sysTenantService.selectSysTenantList(sysTenant));
    }

    /**
     * 新增幼儿园管理基本信息
     */
    @RequiresPermissions("system:branch:add")
    @PostMapping
    public AjaxResult add(@RequestBody SysBranchKindergarten sysBranchKindergarten) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id", sysBranchKindergarten.getId());
        paramsMap.put("name", sysBranchKindergarten.getKindergartenName());
        List<SysBranchKindergarten> checkBranchKindergartenList = sysBranchKindergartenService.selectBranchListByParams(paramsMap);
        if (CollectionUtils.isNotEmpty(checkBranchKindergartenList)) {
            throw new RuntimeException("该幼儿园名称已存在，不可重复添加");
        }
        paramsMap.clear();
        paramsMap.put("gardenId", sysBranchKindergarten.getGardenId());
        paramsMap.put("isGarden", sysBranchKindergarten.getIsGarden());
        List<SysBranchKindergarten> branchKindergartenList = sysBranchKindergartenService.selectBranchListByParams(paramsMap);
        if ("Y".equals(sysBranchKindergarten.getIsGarden()) && CollectionUtils.isNotEmpty(branchKindergartenList)) {
            throw new RuntimeException("所选集团下已存在总园，保存失败！");
        }
        return toAjax(sysBranchKindergartenService.insertSysBranchKindergarten(sysBranchKindergarten));
    }

    @GetMapping("/validate")
    public AjaxResult validateData(@RequestBody SysBranchKindergarten sysBranchKindergarten) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("gardenId", sysBranchKindergarten.getGardenId());
        paramsMap.put("isGarden", sysBranchKindergarten.getIsGarden());
        paramsMap.put("id", sysBranchKindergarten.getId());
        List<SysBranchKindergarten> branchKindergartenList = sysBranchKindergartenService.selectBranchListByParams(paramsMap);
        if ("Y".equals(sysBranchKindergarten.getIsGarden()) && CollectionUtils.isNotEmpty(branchKindergartenList)) {
            throw new RuntimeException("所选集团下已存在总园，保存失败！");
        }
        List<SysTenant> sysGardenTenantList = new ArrayList<>();
        if ("2".equals(sysBranchKindergarten.getKindergartenType())) {
            SysTenant gardenSysTenant = new SysTenant();
            gardenSysTenant.setGardenId(sysBranchKindergarten.getGardenId());
            gardenSysTenant.setTenantType(ConstantUtils.TENANT_TYPE_1);
            gardenSysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
            sysGardenTenantList = sysTenantService.selectSysTenantList(gardenSysTenant);
        }
        if (sysGardenTenantList.size() > 1) {
            throw new RuntimeException("所选集团租户数据异常，请联系管理员处理！");
        }
        return AjaxResult.success();
    }

    /**
     * 修改幼儿园管理基本信息
     */
    @Transactional(rollbackFor = Exception.class)
    @PutMapping
    public AjaxResult edit(@RequestBody SysBranchKindergarten sysBranchKindergarten) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id", sysBranchKindergarten.getId());
        paramsMap.put("name", sysBranchKindergarten.getKindergartenName());
        List<SysBranchKindergarten> branchKindergartenList = sysBranchKindergartenService.selectBranchListByParams(paramsMap);
        if (CollectionUtils.isNotEmpty(branchKindergartenList)) {
            throw new RuntimeException("该幼儿园名称已存在，不可重复添加");
        }
        List<SysTenant> sysGardenTenantList = new ArrayList<>();
        if ("2".equals(sysBranchKindergarten.getKindergartenType())) {
            SysTenant gardenSysTenant = new SysTenant();
            gardenSysTenant.setGardenId(sysBranchKindergarten.getGardenId());
            gardenSysTenant.setTenantType(ConstantUtils.TENANT_TYPE_1);
            gardenSysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
            sysGardenTenantList = sysTenantService.selectSysTenantList(gardenSysTenant);
        }
        if (sysGardenTenantList.size() > 1) {
            throw new RuntimeException("所选集团租户数据异常，请联系管理员处理！");
        }

        //独立幼儿园和其他幼儿园没有“是否集团总园”和“所属集团”属性
        if (!"2".equals(sysBranchKindergarten.getKindergartenType())) {
            sysBranchKindergarten.setIsGarden(null);
            sysBranchKindergarten.setGardenId(null);
        }
        int successCount = sysBranchKindergartenService.updateSysBranchKindergarten(sysBranchKindergarten);
        return toAjax(successCount);
    }

    /**
     * 修改幼儿园管理基本信息
     */
    @RequiresPermissions("system:branch:edit")
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/baseInfo")
    public AjaxResult editBaseInfo(@RequestBody SysBranchKindergarten sysBranchKindergarten) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id", sysBranchKindergarten.getId());
        paramsMap.put("name", sysBranchKindergarten.getKindergartenName());
        List<SysBranchKindergarten> repeatBranchKindergartenList = sysBranchKindergartenService.selectBranchListByParams(paramsMap);
        if (CollectionUtils.isNotEmpty(repeatBranchKindergartenList)) {
            throw new RuntimeException("该幼儿园名称已存在，不可重复添加");
        }
        paramsMap.clear();
        paramsMap.put("gardenId", sysBranchKindergarten.getGardenId());
        paramsMap.put("isGarden", sysBranchKindergarten.getIsGarden());
        paramsMap.put("id", sysBranchKindergarten.getId());
        List<SysBranchKindergarten> branchKindergartenList = sysBranchKindergartenService.selectBranchListByParams(paramsMap);
        if ("Y".equals(sysBranchKindergarten.getIsGarden()) && CollectionUtils.isNotEmpty(branchKindergartenList)) {
            throw new RuntimeException("所选集团下已存在总园，保存失败！");
        }
        List<SysTenant> sysGardenTenantList = new ArrayList<>();
        if ("2".equals(sysBranchKindergarten.getKindergartenType())) {
            SysTenant gardenSysTenant = new SysTenant();
            gardenSysTenant.setGardenId(sysBranchKindergarten.getGardenId());
            gardenSysTenant.setTenantType(ConstantUtils.TENANT_TYPE_1);
            gardenSysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
            sysGardenTenantList = sysTenantService.selectSysTenantList(gardenSysTenant);
        }
        if (sysGardenTenantList.size() > 1) {
            throw new RuntimeException("所选集团租户数据异常，请联系管理员处理！");
        }

        //独立幼儿园和其他幼儿园没有“是否集团总园”和“所属集团”属性
        if (!"2".equals(sysBranchKindergarten.getKindergartenType())) {
            sysBranchKindergarten.setIsGarden(null);
            sysBranchKindergarten.setGardenId(null);
        }
        return toAjax(sysBranchKindergartenService.updateBranchBaseInfo(sysBranchKindergarten));
    }

    /**
     * 调整幼儿园的归属关系
     */
    @RequiresPermissions("system:branch:adjust")
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/affiliation")
    public AjaxResult adjustAffiliation(@RequestBody SysBranchKindergarten sysBranchKindergarten) {
        List<SysTenant> sysGardenTenantList = new ArrayList<>();
        if ("2".equals(sysBranchKindergarten.getKindergartenType())) {
            SysTenant gardenSysTenant = new SysTenant();
            gardenSysTenant.setGardenId(sysBranchKindergarten.getGardenId());
            gardenSysTenant.setTenantType(ConstantUtils.TENANT_TYPE_1);
            gardenSysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
            sysGardenTenantList = sysTenantService.selectSysTenantList(gardenSysTenant);
        }
        //确保幼儿园租户归属关系与集团幼儿园组织架构关系统一，一个幼儿园只允许对应一个集团租户
        if (sysGardenTenantList.size() > 1) {
            throw new RuntimeException("所选集团租户数据异常，请联系管理员处理！");
        }
        //判断调整前后的集团是否集团总园
        if ("2".equals(sysBranchKindergarten.getKindergartenType())) {
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("gardenId", sysBranchKindergarten.getGardenId());
            paramsMap.put("isGarden", "Y");
            List<SysBranchKindergarten> branchKindergartenList = sysBranchKindergartenService.selectBranchListByParams(paramsMap);
            if ("Y".equals(sysBranchKindergarten.getIsGarden()) && CollectionUtils.isNotEmpty(branchKindergartenList)) {
                throw new RuntimeException("所选集团下已存在总园，保存失败！");
            }
        } else {
            //独立幼儿园和其他幼儿园没有“是否集团总园”和“所属集团”属性
            sysBranchKindergarten.setIsGarden(null);
            sysBranchKindergarten.setGardenId(null);
        }
        return toAjax(sysBranchKindergartenService.adjustAffiliation(sysBranchKindergarten));
    }

    @GetMapping("/judge/branch")
    public AjaxResult judgeIsAddGardenTenant(@RequestBody SysBranchKindergarten sysBranchKindergarten) {
        Boolean successFlag = true;
        validateData(sysBranchKindergarten);
        Long branchId = sysBranchKindergarten.getId();
        Long gardenId = sysBranchKindergarten.getGardenId();
        String kindergartenType = sysBranchKindergarten.getKindergartenType();

        SysTenant sysBranchTenant = new SysTenant();
        sysBranchTenant.setBranchId(branchId);
        sysBranchTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
        List<SysTenant> sysBranchTenantList = sysTenantService.selectSysTenantList(sysBranchTenant);
        List<SysTenant> sysGardenTenantList = new ArrayList<>();
        if ("2".equals(kindergartenType)) {
            SysTenant sysGardenTenant = new SysTenant();
            sysGardenTenant.setGardenId(gardenId);
            sysGardenTenant.setTenantType(ConstantUtils.TENANT_TYPE_1);
            sysGardenTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
            sysGardenTenantList = sysTenantService.selectSysTenantList(sysGardenTenant);
        }
        //存在幼儿园租户
        if (CollectionUtils.isNotEmpty(sysBranchTenantList) && sysBranchTenantList.size() == 1) {
            if (CollectionUtils.isNotEmpty(sysGardenTenantList) && sysGardenTenantList.size() == 1) {
                successFlag = false;
            }
        } else {
            //正常情况下不会出现此种情况，防止库中数据异常
            if (sysBranchTenantList.size() > 1) {
                throw new ServiceException("幼儿园租户数据异常，请检查");
            }
        }
        return AjaxResult.success(successFlag);
    }


    /**
     * 删除幼儿园管理基本信息
     */
    @RequiresPermissions("system:branch:remove")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysBranchKindergartenService.deleteSysBranchKindergartenByIds(ids));
    }


    /**
     * 逻辑删除幼儿园集团管理
     */
    @RequiresPermissions("system:branch:abandon")
    @PutMapping("/abandon/{ids}")
    public AjaxResult logicalDelete(@PathVariable Long[] ids) {
        return toAjax(sysBranchKindergartenService.logicalDeleteByIds(ids));
    }

    /**
     * 查询幼儿园列表(包括独立幼儿园,有所属集团的幼儿园,集团)
     */
    @GetMapping("/kindergarten/list/all")
    public AjaxResult kindergartenList() {
        List<SysBranchKindergarten> list = sysBranchKindergartenService.kindergartenList();
        return AjaxResult.success(list);
    }

    /**
     * 获取幼儿园Id列表
     */
    @GetMapping(value = "/kindergarten")
    public AjaxResult getKindergartenIdList(@SpringQueryMap SysBranchKindergartenDto sysBranchKindergartenDto) {
        List<Long> idList = sysBranchKindergartenService.selectSysBranchKindergartenIdList(sysBranchKindergartenDto);
        return AjaxResult.success(idList);
    }


    @GetMapping("get")
    public AjaxResult get(@RequestParam(value = "provinceId", required = false) String provinceId,
                          @RequestParam(value = "cityId", required = false) String cityId,
                          @RequestParam(value = "districtId", required = false) String districtId) {
        return AjaxResult.success(sysBranchKindergartenService.getAll(provinceId, cityId, districtId));
    }


    /**
     * 添加
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysBranchKindergartenDto sysBranchKindergartenDto) {
        return AjaxResult.success(sysBranchKindergartenService.add(sysBranchKindergartenDto));
    }

    @GetMapping("/getById/{id}")
    public AjaxResult getById(@PathVariable("id") Long id) {
        return AjaxResult.success(sysBranchKindergartenService.getById(id));
    }

    /**
     * 添加幼儿园并创建默认租户
     * @param sysBranchKindergarten
     * @return
     */
    @PostMapping("/voteAdd")
    public AjaxResult voteAdd(@RequestBody SysBranchKindergarten sysBranchKindergarten) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id", sysBranchKindergarten.getId());
        paramsMap.put("name", sysBranchKindergarten.getKindergartenName());
//        paramsMap.put("verifyStatus", 1);
        List<SysBranchKindergarten> checkBranchKindergartenList = sysBranchKindergartenService.selectBranchListByParams(paramsMap);
        if (CollectionUtils.isNotEmpty(checkBranchKindergartenList)) {
            throw new RuntimeException("该幼儿园名称已存在，不可重复添加");
        }
        return AjaxResult.success(sysBranchKindergartenService.voteInsertSysBranchKindergarten(sysBranchKindergarten));

    }
}
