package com.yida.data.common.service;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.school.EduYidaAppAccount;
import com.yida.data.common.core.entity.system.*;
import com.yida.data.common.core.entity.user.EduUserDept;
import com.yida.data.common.core.entity.user.enums.UserDeptTypeEnum;
import com.yida.data.common.core.utils.NumberUtil;
import com.yida.data.common.core.utils.RedisUtil;
import com.yida.data.system.feign.*;
import com.yida.data.user.feign.RemoteUserDeptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class CommonService {

    private final RemoteDeptService remoteDeptService;
    private final RemoteAppService remoteAppService;
    private final RemoteYidaAppService remoteYidaAppService;
    private final RemoteYidaAppAccountService remoteYidaAppAccountService;
    private final RemotePayWxConfigService remotePayWxConfigService;
    private final RemoteHolidayService remoteHolidayService;
    private final RemoteCommonService remoteCommonService;
    private final RemoteUserDeptService remoteUserDeptService;
    private final RemotePayTypeService remotePayTypeService;
    private final RemoteUnionPayConfigService remoteUnionPayConfigService;

    private final RedisService redisService;

    public Dept getDept(Long deptId) {
        if (deptId == null) {
            return null;
        }
        //查询学校信息
        Dept dept = (Dept) redisService.hget(CachePrefixConstant.SYS_DEPT_DATA, deptId.toString());
        if (dept == null) {
            dept = remoteDeptService.getInfoByIdNoPermission(deptId).getData();
            redisService.hset(CachePrefixConstant.SYS_DEPT_DATA, deptId.toString(), dept);
        }
        return dept;
    }

    /**
     * 查询家校部门信息
     *
     * @param deptId 家校部门id
     * @return com.yida.data.common.core.entity.user.EduUserDept
     * @author ZYJ
     * @date 2021/11/24 15:11
     */
    public EduUserDept getUserDept(Long deptId) {
        // 查询家校部门信息
        EduUserDept dept = (EduUserDept) redisService.hget(CachePrefixConstant.USER_DEPT_DATA, deptId.toString());
        if (dept == null) {
            dept = this.remoteUserDeptService.getByDeptId(deptId).getData();
            redisService.hset(CachePrefixConstant.USER_DEPT_DATA, deptId.toString(), dept);
        }
        return dept;
    }

    public Dept getSchoolByCorpId(String corpId) {
        Long deptId = redisService.hHasKey(CachePrefixConstant.SYS_SCHOOL_CORPID_ID, corpId)
            ? Long.valueOf(redisService.hget(CachePrefixConstant.SYS_SCHOOL_CORPID_ID, corpId).toString())
            : null;
        Dept school;
        if (deptId == null) {
            Dept dept = remoteDeptService.getSchoolByCorp(corpId).getData();
            school = dept;
            if (school != null) {
                redisService.hset(CachePrefixConstant.SYS_SCHOOL_CORPID_ID, corpId, dept.getDeptId());
            }
        } else {
            school = getDept(deptId);
        }
        return school;
    }

    /**
     * 根据微信公众号id获取部门
     */
    public Dept getSchoolByAppId(String appId) {
        Long deptId = redisService.hHasKey(CachePrefixConstant.SYS_SCHOOL_APPID_ID, appId)
            ? Long.valueOf(redisService.hget(CachePrefixConstant.SYS_SCHOOL_APPID_ID, appId).toString())
            : null;
        Dept school;
        if (deptId == null) {
            Dept dept = remoteDeptService.getSchoolByAppId(appId).getData();
            school = dept;
            if (school != null) {
                redisService.hset(CachePrefixConstant.SYS_SCHOOL_APPID_ID, appId, dept.getDeptId());
            }
        } else {
            school = getDept(deptId);
        }
        return school;
    }

    /**
     * 查询系统app信息
     *
     * @param code     应用代码
     * @param corpId   微信corpId
     * @param schoolId 学校id
     */
    public EduApp getAppByCodeAndSchool(String code, String corpId, Long schoolId) {
        if (schoolId == null && StrUtil.isNotBlank(corpId)) {
            Dept school = remoteDeptService.getSchoolByCorp(corpId).getData();
            schoolId = school.getDeptId();
        }
        EduApp app = redisService.hasKey(CachePrefixConstant.SYS_APP + schoolId)
            ? (EduApp) redisService.hget(CachePrefixConstant.SYS_APP + schoolId, code)
            : null;
        if (app == null) {
            app = remoteAppService.getAppBySchoolOrCorpIdAndCode(schoolId, null, code).getData();
            redisService.hset(CachePrefixConstant.SYS_APP + schoolId, code, app);
        }
        return app;
    }

    /**
     * 查询易达app
     */
    public EduYidaApp getYidaApp(Long schoolId) {
        Long yidaAppId = NumberUtil.object2Long(redisService.hget(CachePrefixConstant.SYS_SCHOOL_YIDA_APP,
            schoolId.toString()));
        EduYidaApp yidaApp = null;
        if (yidaAppId != null) {
            yidaApp = (EduYidaApp) redisService.hget(CachePrefixConstant.SYS_YIDA_APP, yidaAppId.toString());
        }
        if (yidaApp == null) {
            yidaApp = remoteYidaAppService.getAppBySchoolNoPermission(schoolId).getData();
            if (yidaApp != null) {
                redisService.hset(CachePrefixConstant.SYS_SCHOOL_YIDA_APP, schoolId.toString(), yidaApp.getId());
                redisService.hset(CachePrefixConstant.SYS_YIDA_APP, yidaApp.getId().toString(), yidaApp);
            }
        }
        return yidaApp;
    }

    /**
     * 查询易达订阅号
     *
     * @param type 0-家长，1-老师
     */
    public EduYidaAppAccount getYidaAppAccount(Long schoolId, Integer type) {
        EduYidaAppAccount account = (EduYidaAppAccount) redisService
            .hget(CachePrefixConstant.SYS_YIDA_APP_ACCOUNT + schoolId.toString(),
                type.toString());
        if (account == null) {
            account = remoteYidaAppAccountService.getAccountByTypeNoPermission(schoolId, type).getData();
            if (account != null) {
                redisService.hset(CachePrefixConstant.SYS_YIDA_APP_ACCOUNT + schoolId,
                    type.toString(), account);
            }
        }
        return account;
    }

    /**
     * 判断当前学校下是否有当前家校部门
     *
     * @param deptName 部门名称
     * @param deptType 部门类型 {@link UserDeptTypeEnum}
     * @param schoolId 学校id
     * @param str      某次导入的唯一标识
     * @param parentId 父级部门id
     * @return com.yida.data.common.core.entity.system.Dept
     * @author ZYJ
     * @date 2021/8/23 19:49
     */
    public EduUserDept getUserDeptBySchoolIdAndNameAndType(String deptName, Integer deptType, Long schoolId,
        String str, Long parentId) {
        // 查询部门信息
        return (EduUserDept) redisService.hget(RedisUtil.getDeptKey(str),
            RedisUtil.getDeptRedisKey(deptName, deptType, schoolId, parentId));
    }

    /**
     * 根据学校查询微信支付配置
     */
    public EduPayWxConfig getPayWxConfigBySchool(Long schoolId) {
        EduPayWxConfig config = redisService.hasKey(CachePrefixConstant.PAY_WX_CONFIG)
            ? (EduPayWxConfig) redisService.hget(CachePrefixConstant.PAY_WX_CONFIG, schoolId.toString())
            : null;
        if (config == null) {
            config = remotePayWxConfigService.getPayWxConfigBySchool(schoolId).getData();
            redisService.hset(CachePrefixConstant.PAY_WX_CONFIG, schoolId.toString(), config);
        }
        return config;
    }

    /**
     * 查询当天是否是工作日
     */
    public Boolean isWorkDay(LocalDate target) {
        List<Object> objects = redisService.lGet(CachePrefixConstant.HOLIDAY, 0L, -1L);
        if (CollUtil.isEmpty(objects)) {
            List<EduHoliday> data = remoteHolidayService.listAllHoliday().getData();
            if (CollUtil.isNotEmpty(data)) {
                redisService.llSet(CachePrefixConstant.HOLIDAY, data);
                for (EduHoliday holiday : data) {
                    // 节假日
                    if (target.equals(holiday)) {
                        return false;
                    }
                }
            }
        } else {
            for (Object o : objects) {
                // 节假日
                EduHoliday holiday = (EduHoliday) o;
                if (target.equals(holiday)) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 查询当天的上一个工作日
     */
    public LocalDate findLastWorkDay(LocalDate target) {
        LocalDate yesterday = target.minusDays(1L);
        return isWorkDay(yesterday) ? yesterday : findLastWorkDay(yesterday);
    }

    /**
     * 获取系统微信公众号
     */
    public EduDeptWxPublic getWxPublic(Long deptId) {
        EduDeptWxPublic sysWxPublic = (EduDeptWxPublic) redisService
            .hget(CachePrefixConstant.SYS_DEPT_WX_PUBLIC, deptId.toString());
        if (sysWxPublic == null) {
            sysWxPublic = remoteCommonService.getDeptWxPublic(deptId).getData();
            if (sysWxPublic != null) {
                redisService.hset(CachePrefixConstant.SYS_DEPT_WX_PUBLIC, deptId.toString(), sysWxPublic);
            }
        }
        return sysWxPublic;
    }

    /**
     * 查询区域信息
     *
     * @param id
     * @return
     */
    public EduArea getArea(Long id) {
        EduArea area = (EduArea) redisService.get(CachePrefixConstant.AREA_DATA + id);
        if (area == null) {
            area = remoteCommonService.getArea(id).getData();
            redisService.set(CachePrefixConstant.AREA_DATA + id, area, 3600L);
        }
        return area;
    }

    /**
     * 根据部门id获取部门支付方式
     *
     * @param deptId 部门id
     * @return com.yida.data.common.core.entity.system.EduDeptPayType
     * @author ZYJ
     * @date 2022/6/22 14:05
     */
    public EduDeptPayType getDeptPayWay(Long deptId) {
        EduDeptPayType payType = redisService.hasKey(CachePrefixConstant.PAY_WAY_CONFIG)
            ? (EduDeptPayType) redisService.hget(CachePrefixConstant.PAY_WAY_CONFIG, deptId.toString())
            : null;
        if (Objects.isNull(payType)) {
            payType = remotePayTypeService.getPayTypeByDeptId(deptId).getData();
            if (Objects.nonNull(payType)) {
                redisService.hset(CachePrefixConstant.PAY_WAY_CONFIG, deptId.toString(), payType);
            }
        }
        return payType;
    }

    /**
     * 根据部门查询银联云闪付支付配置
     *
     * @param deptId 部门id
     * @return com.yida.data.common.core.entity.system.UnionPayConfig
     * @author ZYJ
     * @date 2022/6/23 16:45
     */
    public UnionPayConfig getUnionPayConfigByDept(Long deptId) {
        UnionPayConfig config = redisService.hasKey(CachePrefixConstant.UNION_PAY_CONFIG)
            ? (UnionPayConfig) redisService.hget(CachePrefixConstant.UNION_PAY_CONFIG, deptId.toString())
            : null;
        if (config == null) {
            config = remoteUnionPayConfigService.getUnionPayConfigByDept(deptId).getData();
            redisService.hset(CachePrefixConstant.UNION_PAY_CONFIG, deptId.toString(), config);
        }
        return config;
    }

    /**
     * 向下查询指定家校部门类型的家校部门id(可查询非直接子家校部门) 未毕业家校部门
     *
     * @param deptId 部门id
     * @param type   家校部门类型 {@link UserDeptTypeEnum}
     * @return java.util.List<com.yida.data.common.core.entity.user.EduUserDept>
     * @author ZYJ
     * @date 2022/7/11 16:10
     */
    public List<EduUserDept> findChildIdByParentAndType(Long deptId, Integer type) {
//        List<Object> listCache = redisService.lGet(CachePrefixConstant.USER_DEPT_TYPE_DATA + StringConstant.DASH +
//                deptId + StringConstant.DASH + type, 0L, -1L);
//        List<EduUserDept> list = listCache.stream().map(EduUserDept.class::cast).collect(Collectors.toList());
//
//        if (CollUtil.isEmpty(list)) {
//            list = remoteUserDeptService.findChildIdByParentAndTypeNoPermission(deptId, type).getData();
//            if (CollUtil.isNotEmpty(list)) {
//                redisService.lSet(CachePrefixConstant.USER_DEPT_TYPE_DATA + StringConstant.DASH +
//                        deptId + StringConstant.DASH + type, list);
//            }
//        }
//        return list;
        return remoteUserDeptService.findChildIdByParentAndTypeNoPermission(deptId, type).getData();
    }


    /**
     * 工具学校名称查找机构信息
     *
     * @param schoolName
     * @return
     */
    public Dept getSchoolByName(String schoolName) {
        return remoteDeptService.getSchoolByName(schoolName).getData();
    }
}
