package com.yida.data.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.EduApp;
import com.yida.data.common.core.utils.Asserts;
import com.yida.data.system.mapper.DeptMapper;
import com.yida.data.system.mapper.EduAppMapper;
import com.yida.data.system.service.EduAppService;

import org.springframework.stereotype.Service;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class EduAppServiceImpl extends ServiceImpl<EduAppMapper, EduApp> implements EduAppService {
    private final DeptMapper deptMapper;

    @Override
    public IPage<EduApp> listQywxAppPage(Page page, Long schoolId) {
        return baseMapper.listAppPage(page, schoolId);
    }

    @Override
    public void saveApp(EduApp app) {
        Dept school = deptMapper.selectById(app.getDeptId());
        Asserts.isTrue(school != null && school.getDeptType() == 0, "学校不存在或未设置corpId");
        app.setWxCorpId(school.getCorpId());
        saveOrUpdate(app);
    }

    @Override
    public EduApp getAppBySchoolOrCorpIdAndCode(Long schoolId, String corpId, String code) {
        EduApp eduApp = new EduApp();
        if (schoolId != null) {
            eduApp.setDeptId(schoolId);
        }
        if (StrUtil.isNotEmpty(corpId)) {
            eduApp.setWxCorpId(corpId);
        }
        eduApp.setCode(code);
        return baseMapper.selectOne(Wrappers.lambdaQuery(eduApp));
    }
}
