package yangtz.cs.liu.campus.service.impl.schoolInfo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.utils.StringUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.constant.InfoAcquisitionConstant;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolInfo.SchoolInfoAcquisition;
import yangtz.cs.liu.campus.domain.schoolInfo.SchoolInfoDetail;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.domain.student.SchoolStudentClassRelation;
import yangtz.cs.liu.campus.mapper.schoolInfo.SchoolInfoAcquisitionMapper;
import yangtz.cs.liu.campus.mapper.schoolInfo.SchoolInfoDetailMapper;
import yangtz.cs.liu.campus.service.schoolInfo.ISchoolInfoDetailService;
import yangtz.cs.liu.campus.vo.student.SchoolStudentVO;

import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;

@Service
public class SchoolInfoDetailServiceImpl extends ServiceImpl<SchoolInfoDetailMapper, SchoolInfoDetail> implements ISchoolInfoDetailService {
    @Autowired
    private SchoolInfoDetailMapper detailMapper;

    @Autowired
    private SchoolInfoAcquisitionMapper acquisitionMapper;
    //教务-信息采集-数据、数据查看-列表
    @Override
    public List<SchoolInfoDetail> queryList(SchoolInfoDetail detail) {
        LambdaQueryWrapper<SchoolInfoDetail> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolInfoDetail::getInfoId,detail.getInfoId())
                .like(isNotNull(detail.getIdCard()),SchoolInfoDetail::getIdCard,detail.getIdCard())
                .like(isNotNull(detail.getStudentName()),SchoolInfoDetail::getStudentName,detail.getStudentName())
                .like(isNotNull(detail.getSchoolNo()),SchoolInfoDetail::getSchoolNo,detail.getSchoolNo())
                .orderByDesc(SchoolInfoDetail::getCreateTime)
                ;
        return detailMapper.selectList(lqw);
    }

    //教务-信息采集-数据、数据查看-新增
    @Override
    public int add(SchoolInfoDetail detail) {
        checkStudentUnique(detail, detail.getInfoId());
        detail.insert();
        return detailMapper.insert(detail);
    }

    @Override
    public int edit(SchoolInfoDetail detail) {
        checkStudentUnique(detail, detail.getInfoId());
        detail.update();
        return detailMapper.updateById(detail);
    }

    //撤回
    @Override
    public int withdraw(Long id) {
        LambdaUpdateWrapper<SchoolInfoDetail> luw = new LambdaUpdateWrapper<>();
        luw.eq(SchoolInfoDetail::getInfoId,id)
                .set(SchoolInfoDetail::getSex,null)
                .set(SchoolInfoDetail::getBirthday,null)
                .set(SchoolInfoDetail::getNation,null)
                .set(SchoolInfoDetail::getProvincialNumber,null)
                .set(SchoolInfoDetail::getNationalNumber,null)
                .set(SchoolInfoDetail::getStuTelephone,null)
                .set(SchoolInfoDetail::getHomeAddress,null)
                .set(SchoolInfoDetail::getPostalAddress,null)
                .set(SchoolInfoDetail::getBirthAddress,null)
                .set(SchoolInfoDetail::getPostalCode,null)
                .set(SchoolInfoDetail::getNativePlace,null)
                .set(SchoolInfoDetail::getRegisteredAddress,null)
                .set(SchoolInfoDetail::getRegisteredType,null)
                .set(SchoolInfoDetail::getJuniorSchool,null)
                .set(SchoolInfoDetail::getRegion,null)
                .set(SchoolInfoDetail::getForeignLanguages,null)
                .set(SchoolInfoDetail::getAppearance,null)
                .set(SchoolInfoDetail::getBloodType,null)
                .set(SchoolInfoDetail::getHealth,null)
                .set(SchoolInfoDetail::getOtherRegions,null)
                .set(SchoolInfoDetail::getFloatingPopulation,null)
                .set(SchoolInfoDetail::getOnlyChild,null)
                .set(SchoolInfoDetail::getNature,null)
                .set(SchoolInfoDetail::getSupport,null)
                .set(SchoolInfoDetail::getParentName1,null)
                .set(SchoolInfoDetail::getRelationship1,null)
                .set(SchoolInfoDetail::getWorkAddress1,null)
                .set(SchoolInfoDetail::getContactAddress1,null)
                .set(SchoolInfoDetail::getTelephone1,null)
                .set(SchoolInfoDetail::getPostalCode1,null)
                .set(SchoolInfoDetail::getParentName2,null)
                .set(SchoolInfoDetail::getRelationship2,null)
                .set(SchoolInfoDetail::getWorkAddress2,null)
                .set(SchoolInfoDetail::getContactAddress2,null)
                .set(SchoolInfoDetail::getTelephone2,null)
                .set(SchoolInfoDetail::getPostalCode2,null)
                ;
        detailMapper.update(null,luw);

        LambdaUpdateWrapper<SchoolInfoAcquisition> acLuw = new LambdaUpdateWrapper<>();
        acLuw.eq(SchoolInfoAcquisition::getId,id).set(SchoolInfoAcquisition::getInfoType, InfoAcquisitionConstant.NOPUB);
        return acquisitionMapper.update(null,acLuw);
    }

    @Override
    public void checkImport(List<SchoolInfoDetail> list) {
        //检验是否为空
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }
        // 准备记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolInfoDetail detail : list) {
            if (StringUtils.isEmpty(detail.getStudentName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、姓名为空,请您重新输入! ");
            }  else if (StringUtils.isEmpty(detail.getIdCard())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、身份证号为空,请您重新输入! ");
            }  else if (StringUtils.isEmpty(detail.getSchoolNo())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、注册序号为空,请您重新输入! ");
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<SchoolInfoDetail> list,Long infoId) {
        // 准备记录日志数据
        int successNum = 0;
        StringBuilder successMsg = new StringBuilder();
        // 遍历并逐个导入
        for (SchoolInfoDetail detail : list) {
                checkStudentUnique(detail,infoId);
                //姓名身份证号注册序号的前后空格消除
                detail.setStudentName(StringUtil.clearSpace(detail.getStudentName()));
                detail.setIdCard(StringUtil.clearSpace(detail.getIdCard()));
                detail.setSchoolNo(StringUtil.clearSpace(detail.getSchoolNo()));
                detail.setInfoId(infoId);
                detail.insert();
                detailMapper.insert(detail);
                successNum++;

        }
        successMsg.insert(0, "恭喜您，数据已导入成功！共有 " + successNum + " 条");
        return successMsg.toString();
    }

    //判断是否有信息重复
    private void checkStudentUnique(SchoolInfoDetail detail,Long infoId) {

        LambdaQueryWrapper<SchoolInfoDetail> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolInfoDetail::getInfoId, infoId)
                .eq(SchoolInfoDetail::getIdCard, detail.getIdCard())
                .or()
                .eq(SchoolInfoDetail::getSchoolNo, detail.getSchoolNo())
                .or()
                .eq(isNotBlank(detail.getProvincialNumber()),SchoolInfoDetail::getProvincialNumber,detail.getProvincialNumber())
                .or()
                .eq(isNotBlank(detail.getNationalNumber()),SchoolInfoDetail::getNationalNumber,detail.getNationalNumber())
        ;
        List<SchoolInfoDetail> getDetails = detailMapper.selectList(lqw);
        if (StringUtils.isNotNull(getDetails) && getDetails.size() > 0) {
            //如果有，则只有一个
            SchoolInfoDetail getDetail = getDetails.get(0);
            if (StringUtils.isNotNull(detail.getId()) && detail.getId().equals(getDetail.getId())) {
                return;
            }
            if (detail.getIdCard().equals(getDetail.getIdCard())) {
                throw new ServiceException("学生姓名为"+detail.getStudentName()+"的身份证号已存在本次信息采集中，请检查");
            }
            if (detail.getSchoolNo().equals(getDetail.getSchoolNo())) {
                throw new ServiceException("学生姓名为"+detail.getStudentName()+"的注册序号已存在本次信息采集中，请检查");
            }
            if(StringUtils.isNotBlank(getDetail.getProvincialNumber())){
                if (detail.getProvincialNumber().equals(getDetail.getProvincialNumber())) {
                    throw new ServiceException("学生姓名为"+detail.getStudentName()+"的省学籍辅号已存在本次信息采集中，请检查");
                }
            }
            if(StringUtils.isNotBlank(detail.getNationalNumber())){
                if (detail.getNationalNumber().equals(getDetail.getNationalNumber())) {
                    throw new ServiceException("学生姓名为"+detail.getStudentName() +"的全国学籍号已存在本次信息采集中，请检查");
                }
            }
        }
    }
}
