package com.qmth.paper.library.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.paper.library.common.bean.params.BasicSemesterParams;
import com.qmth.paper.library.common.bean.result.BasicSemesterResult;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.BasicSemester;
import com.qmth.paper.library.common.entity.SysUser;
import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import com.qmth.paper.library.common.mapper.BasicSemesterMapper;
import com.qmth.paper.library.common.service.BasicSemesterService;
import com.qmth.paper.library.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 学期字典表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2021-10-28
 */
@Service
public class BasicSemesterServiceImpl extends ServiceImpl<BasicSemesterMapper, BasicSemester> implements BasicSemesterService {

    @Resource
    BasicSemesterService basicSemesterService;

    @Override
    public IPage<BasicSemesterResult> basicSemesterPage(Long schoolId, int pageNumber, int pageSize) {
        return this.baseMapper.findBasicSemesterPage(new Page<>(pageNumber, pageSize), schoolId, null);
    }

    @Transactional
    @Override
    public Long saveBasicSemester(BasicSemesterParams basicSemesterParams) throws IllegalAccessException {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        return basicSemesterService.saveBasicSemesterCommon(basicSemesterParams, sysUser.getSchoolId(), false);
    }

    /**
     * 保存公用
     *
     * @param basicSemesterParams
     * @param schoolId
     * @return
     * @throws IllegalAccessException
     */
    @Override
    @Transactional
    public Long saveBasicSemesterCommon(BasicSemesterParams basicSemesterParams, Long schoolId, boolean openApi) throws IllegalAccessException {
        SystemConstant.verifyDBFields(basicSemesterParams, basicSemesterParams.getClass());
        Long id = basicSemesterParams.getId();
        String semesterName = basicSemesterParams.getSemesterName();

        // 校验学期唯一性
        BasicSemester checkName = this.getOne(new QueryWrapper<BasicSemester>().lambda()
                .eq(BasicSemester::getEnable, true)
                .eq(BasicSemester::getSchoolId, schoolId)
                .eq(BasicSemester::getName, semesterName));
        if (Objects.nonNull(checkName) && !checkName.getId().equals(id)) {
            if (openApi) {
                // 如果是开放接口（分布式印刷推学期给教研分析），就算没有教研分析学期id，只要名称一致就视为编辑
                id = checkName.getId();
            } else {
                throw ExceptionResultEnum.ERROR.exception("学期名称【" + semesterName + "】重复");
            }
        }
        if (SystemConstant.longNotNull(id)) {
            // 编辑
            BasicSemester old = this.getById(id);
            if (Objects.isNull(old) || old.getEnable().equals(false)) {
                throw ExceptionResultEnum.ERROR.exception("所选学期不存在或被禁用");
            }
            this.update(new UpdateWrapper<BasicSemester>().lambda()
                    .eq(BasicSemester::getId, id)
                    .set(BasicSemester::getName, semesterName));
        } else {
            // 新增
            id = SystemConstant.getDbUuid();
            BasicSemester basicSemester = new BasicSemester();
            basicSemester.setId(id);
            basicSemester.setEnable(true);
            basicSemester.setName(semesterName);
            basicSemester.setSchoolId(schoolId);
            basicSemester.setCode(null);
            this.save(basicSemester);
        }
        return id;
    }

    @Transactional
    @Override
    public boolean deleteBasicSemesterById(String ids) {
        String[] idsArrary = ids.split(",");
        for (String id : idsArrary) {
            if (StringUtils.isBlank(id)) {
                throw ExceptionResultEnum.ERROR.exception("ID不允许为空");
            }
            if (this.baseMapper.countBasicExamBySemesterId(Long.valueOf(id)) > 0) {
                throw ExceptionResultEnum.ERROR.exception("当前学期已创建考试，不允许删除");
            }
            this.removeById(id);
        }
        return true;
    }

    @Override
    public List<BasicSemester> querySemester() {
        Long schoolId = SystemConstant.convertIdToLong(ServletUtil.getRequestHeaderSchoolId().toString());
        QueryWrapper<BasicSemester> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicSemester::getSchoolId, schoolId).eq(BasicSemester::getEnable, true);
        return this.list(queryWrapper);
    }

}
