package com.vctgo.system.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vctgo.common.core.exception.ServiceException;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.SysDept;
import com.vctgo.system.api.domain.SysTenant;
import com.vctgo.system.api.domain.SysUser;
import com.vctgo.system.api.domain.dto.SysBranchKindergartenDto;
import com.vctgo.system.api.domain.dto.SysGardenManageDto;
import com.vctgo.system.domain.SysBranchKindergarten;
import com.vctgo.system.domain.SysGardenManage;
import com.vctgo.system.mapper.*;
import com.vctgo.system.service.ISysGardenManageService;
import com.vctgo.system.util.ConstantUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 幼儿园集团管理Service业务层处理
 *
 * @author wanglonghua
 * @date 2023-06-02
 */
@Slf4j
@Service
public class SysGardenManageServiceImpl implements ISysGardenManageService {
    @Autowired
    private SysGardenManageMapper sysGardenManageMapper;

    @Autowired
    private SysBranchKindergartenMapper sysBranchKindergartenMapper;

    @Autowired
    private SysTenantMapper sysTenantMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 查询幼儿园集团管理
     *
     * @param id 幼儿园集团管理主键
     * @return 幼儿园集团管理
     */
    @Override
    public SysGardenManage selectSysGardenManageById(Long id) {
        return sysGardenManageMapper.selectById(id);
    }

    /**
     * 查询幼儿园集团管理列表-分页
     *
     * @param sysGardenManage 幼儿园集团管理
     * @return 幼儿园集团管理
     */
    @Override
    public IPage<SysGardenManage> selectSysGardenManagePage(SysGardenManage sysGardenManage) {
        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L)
                , Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L));
        IPage<SysGardenManage> sysGardenManageIPage = sysGardenManageMapper.selectSysGardenManageList(mpPage, sysGardenManage);
        if (CollectionUtils.isEmpty(sysGardenManageIPage.getRecords())) {
            return new Page<>();
        }
        List<SysGardenManage> sysGardenManageList = sysGardenManageIPage.getRecords();
        sysGardenManageList.forEach(sysGardenManageTmp -> {
            String accountStatus = sysGardenManageTmp.getAccountStatus();
            if (Objects.isNull(accountStatus)) {
                sysGardenManageTmp.setAccountStatus("未开通");
            } else if ("0".equals(accountStatus)) {
                sysGardenManageTmp.setAccountStatus("已开通");
            } else if ("1".equals(accountStatus)) {
                sysGardenManageTmp.setAccountStatus("已禁用");
            }
        });
        return sysGardenManageIPage;
    }

    /**
     * 查询幼儿园集团管理列表
     *
     * @param sysGardenManage 幼儿园集团管理
     * @return 幼儿园集团管理
     */
    @Override
    public List<SysGardenManage> selectSysGardenManageList(SysGardenManage sysGardenManage) {
        List<SysGardenManage> sysGardenManageList = sysGardenManageMapper.selectSysGardenManageList(sysGardenManage);
        LambdaQueryWrapper<SysTenant> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysTenant::getTenantType, ConstantUtils.TENANT_TYPE_1);
        wrapper.eq(SysTenant::getDelFlag, "0");
        List<SysTenant> sysTenantList = sysTenantMapper.selectList(wrapper);
        Map<Long, Long> sysTenantMap = sysTenantList.stream().collect(Collectors.toMap(SysTenant::getGardenId, SysTenant::getId));
//        LambdaQueryWrapper<SysBranchKindergarten> wrapperx = Wrappers.lambdaQuery();
//        wrapperx.select(SysBranchKindergarten::getGardenId, SysBranchKindergarten::getId);
//        wrapperx.eq(SysBranchKindergarten::getIsGarden, "Y");
//        wrapperx.eq(SysBranchKindergarten::getKindergartenType, ConstantUtils.KINDERGARTEN_TYPE_2);
//        wrapperx.eq(SysBranchKindergarten::getIsDeleted, ConstantUtils.IS_DELETED_0);
//        List<SysBranchKindergarten> sysBranchKindergartenList = sysBranchKindergartenMapper.selectList(wrapperx);
//        Map<Long,Long> sysBranchKindergartenMap = sysBranchKindergartenList.stream().collect(Collectors.toMap(SysBranchKindergarten::getGardenId, SysBranchKindergarten::getId));
        sysGardenManageList.forEach(obj -> {
            if (sysTenantMap.containsKey(obj.getId())) {
                obj.getParams().put("tenantId", String.valueOf(sysTenantMap.get(obj.getId())));
            } else {
                obj.getParams().put("tenantId", null);
            }
        });
        return sysGardenManageList;
    }

    @Override
    public List<SysGardenManage> selectGardenListByParams(Map<String, Object> params) {
        return sysGardenManageMapper.selectGardenListByParams(params);
    }

    @Override
    public List<Long> selectGardenManageIdList(SysGardenManageDto sysGardenManageDto) {
        return sysGardenManageMapper.selectList(new QueryWrapper<SysGardenManage>().lambda()
                .eq(SysGardenManage::getIsDeleted, ConstantUtils.IS_DELETED_0)
                .like(SysGardenManage::getBelongRegion, sysGardenManageDto.getBelongRegion())
        ).stream().map(SysGardenManage::getId).collect(Collectors.toList());
    }

    /**
     * 新增幼儿园集团管理
     *
     * @param sysGardenManage 幼儿园集团管理
     * @return 结果
     */

    @Override
    public int insertSysGardenManage(SysGardenManage sysGardenManage) {
        return sysGardenManageMapper.insert(sysGardenManage);
    }

    /**
     * 修改幼儿园集团管理
     *
     * @param sysGardenManage 幼儿园集团管理
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateSysGardenManage(SysGardenManage sysGardenManage) {
        //查询变更前的幼儿园基本信息
        SysGardenManage beforeSysGardenManage = this.sysGardenManageMapper.selectById(sysGardenManage.getId());
        int successCount = sysGardenManageMapper.updateById(sysGardenManage);
        if (successCount > 0) {
            //查看平台建立的租户幼儿园名称是否被幼儿园私自改变，判断是否更新系统租户租户表的租户名称
            SysTenant sysTenant = new SysTenant();
            if (!beforeSysGardenManage.getName().equals(sysGardenManage.getName())) {
                sysTenant.setTenantName(sysGardenManage.getName());
                sysTenant.setGardenId(sysGardenManage.getId());
                //如果存在租户，则更新的记录数不为0；如果不存在租户，则更新的记录数为0
                this.sysTenantMapper.updateSysGardenTenantName(sysTenant);
                //更新部门表的集团或者幼儿园名称
                SysDept checkSysDept = new SysDept();
                checkSysDept.setDeptId(sysGardenManage.getId());
                checkSysDept.setDeptName(sysGardenManage.getName());
                checkSysDept.setDeptType(ConstantUtils.DEPT_TYPE_1);
                deptMapper.updateTenantName(checkSysDept);
                //更新人员表的集团或者幼儿园名称
                SysUser checkSysUser = new SysUser();
                checkSysUser.setDeptId(sysGardenManage.getId());
                checkSysUser.setNickName(sysGardenManage.getName());
                userMapper.updateGardenTenantName(checkSysUser);
                //不管平台建立的租户幼儿园名称是否改变，均更新redis缓存中的租户名称
                redisService.deleteObject("tenantList");
            }
        }
        return successCount;
    }

    @Override
    public int logicalDeleteByIds(Long[] ids) {
        Map<String, Object> params = new HashMap<>();
        params.put("idColl", ids);
        params.put("type", "2");
        List<SysBranchKindergarten> existBranchList = sysBranchKindergartenMapper.selectBranchListByParams(params);
        if (CollectionUtils.isNotEmpty(existBranchList)) {
            throw new ServiceException("存在已被引用的集团数据，删除失败！");
        }
        SysGardenManage sysGardenManage = new SysGardenManage();
        sysGardenManage.setUpdateById(SecurityUtils.getUserId());
        sysGardenManage.setUpdateBy(SecurityUtils.getUsername());
        sysGardenManage.setUpdateTime(new Date());
        return sysGardenManageMapper.updateDeletedStatusByIds(ArrayUtil.join(ids, ","), sysGardenManage);
    }

    /**
     * 批量删除幼儿园集团管理
     *
     * @param ids 需要删除的幼儿园集团管理主键
     * @return 结果
     */
    @Override
    public int deleteSysGardenManageByIds(Long[] ids) {
        return sysGardenManageMapper.deleteSysGardenManageByIds(ids);
    }

    /**
     * 删除幼儿园集团管理信息
     *
     * @param id 幼儿园集团管理主键
     * @return 结果
     */
    @Override
    public int deleteSysGardenManageById(Long id) {
        return sysGardenManageMapper.deleteById(id);
    }
}
