package com.qmth.teachcloud.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.teachcloud.common.bean.params.BasicCampusParams;
import com.qmth.teachcloud.common.bean.result.BasicCampusResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicCampus;
import com.qmth.teachcloud.common.entity.BasicClazz;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.mapper.BasicCampusMapper;
import com.qmth.teachcloud.common.service.BasicCampusService;
import com.qmth.teachcloud.common.service.BasicClazzService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 基础校区表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2021-08-02
 */
@Service
public class BasicCampusServiceImpl extends ServiceImpl<BasicCampusMapper, BasicCampus> implements BasicCampusService {
    @Resource
    private BasicCampusMapper basicCampusMapper;
    @Resource
    private BasicClazzService basicClazzService;

    @Override
    public List<BasicCampusResult> basicCampusList(Long schoolId) {
        return basicCampusMapper.findBasicCampusResult(schoolId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long saveBasicCampus(BasicCampusParams basicCampusParams) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Long schoolId = sysUser.getSchoolId();
        Long orgId = sysUser.getOrgId();

        Long campusId = basicCampusParams.getId();
        String campusName = basicCampusParams.getCampusName();
        String campusCode = basicCampusParams.getCampusCode();
        Long printHouseId = basicCampusParams.getPrintHouseId();
        if (!SystemConstant.strNotNull(campusCode)){
            throw ExceptionResultEnum.ERROR.exception("缺少校区编号");
        }
        BasicCampus checkName = this.getOne(new QueryWrapper<BasicCampus>().lambda().eq(BasicCampus::getEnable,true).eq(BasicCampus::getSchoolId,schoolId).eq(BasicCampus::getCampusName,campusName));
        if (Objects.nonNull(checkName) && !checkName.getId().equals(campusId)){
            throw ExceptionResultEnum.ERROR.exception("校区名称【" + campusName + "】重复");
        }
        BasicCampus checkCode = this.getOne(new QueryWrapper<BasicCampus>().lambda().eq(BasicCampus::getEnable,true).eq(BasicCampus::getSchoolId,schoolId).eq(BasicCampus::getCampusCode,campusCode));
        if (Objects.nonNull(checkCode) && !checkCode.getId().equals(campusId)){
            throw ExceptionResultEnum.ERROR.exception("校区编号【" + campusCode + "】重复");
        }

        if (SystemConstant.longNotNull(campusId)){
            // 编辑
            campusId = basicCampusParams.getId();
            BasicCampus old = this.getById(campusId);
            if (Objects.isNull(old) || old.getEnable().equals(false)){
                throw ExceptionResultEnum.ERROR.exception("所选校区主键不存在或被禁用");
            }
            UpdateWrapper<BasicCampus> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .set(BasicCampus::getCampusName,campusName)
                    .set(BasicCampus::getSchoolId,schoolId)
                    .set(BasicCampus::getPrintHouseId, printHouseId)
                    .set(BasicCampus::getUpdateId,sysUser.getId())
                    .eq(BasicCampus::getId,campusId);
            this.update(updateWrapper);
        }else {
            // 新增
            campusId = SystemConstant.getDbUuid();
            BasicCampus basicCampus = new BasicCampus();
            basicCampus.setId(campusId);
            basicCampus.setCampusCode(campusCode);
            basicCampus.setCampusName(campusName);
            basicCampus.setPrintHouseId(printHouseId);
            basicCampus.setOrgId(orgId);
            basicCampus.setEnable(true);
            basicCampus.setCreateId(sysUser.getId());
            basicCampus.setSchoolId(schoolId);
            this.save(basicCampus);
        }
        return campusId;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean removeBasicCampusById(Long id) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        if (basicClazzService.list(new QueryWrapper<BasicClazz>().lambda().eq(BasicClazz::getCampusId,id)).size() > 0){
            throw ExceptionResultEnum.ERROR.exception("基础班级中绑定了要删除的校区，无法删除");
        }
        return this.removeById(id);
    }

    @Override
    public Long getPrintHouseIdBySchoolIdAndCampusName(Long schoolId, String campusName) {
        QueryWrapper<BasicCampus> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicCampus::getSchoolId, schoolId).eq(BasicCampus::getCampusName, campusName);
        BasicCampus basicCampus = this.getOne(queryWrapper);
        if(Objects.isNull(basicCampus)){
            throw ExceptionResultEnum.ERROR.exception("校区不存在");
        }
        if(Objects.isNull(basicCampus.getPrintHouseId())){
            throw ExceptionResultEnum.ERROR.exception("校区没有绑定印刷室");
        }
        return basicCampus.getPrintHouseId();
    }

    @Override
    public String findCampusNamesByClazzIdList(List<Long> clazzIdList, String separator) {
        String campusNames = "";
//        Long schoolId = SystemConstant.convertIdToLong(ServletUtil.getRequestHeaderSchoolId().toString());
        List<Long> campusId = basicClazzService.list(new QueryWrapper<BasicClazz>().lambda()
                .in(BasicClazz::getId,clazzIdList))
                .stream()
                .map(BasicClazz::getCampusId)
                .distinct()
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(campusId)){
            List<BasicCampus> basicCampusList = this.list(new QueryWrapper<BasicCampus>().lambda()
//                    .eq(BasicCampus::getSchoolId,schoolId)
                    .in(BasicCampus::getId,campusId));
            campusNames = basicCampusList.stream().map(BasicCampus::getCampusName).distinct().collect(Collectors.joining(separator));
        }
        return campusNames;
    }
}
