package com.app.service.organ;

import com.app.dto.organ.OrganBranchSchoolResponseDto;
import com.app.entity.organ.Organ;
import com.app.entity.organ.OrganSchool;
import com.app.mapper.organ.OrganMapper;
import com.app.mapper.organ.OrganSchoolMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class OrganService {

    @Autowired
    private OrganMapper mapper;

    @Autowired
    public OrganSchoolMapper organSchoolMapper;

    @Transactional
    public void saveOrUpdate(OrganBranchSchoolResponseDto organBranchSchoolResponseDto) {
        Organ organ = new Organ();
        BeanUtils.copyProperties(organBranchSchoolResponseDto, organ);
        if (StringUtils.isEmpty(organBranchSchoolResponseDto.getId())) {
            mapper.insert(organ);
        } else {
            Organ _organ = mapper.selectById(organBranchSchoolResponseDto.getId());
            BeanUtils.copyProperties(organ, _organ);
            mapper.updateById(_organ);
        }

        for (OrganSchool branchSchool: organBranchSchoolResponseDto.getList()) {
            if (StringUtils.isEmpty(branchSchool.getId())) {
                organSchoolMapper.insert(branchSchool);
            } else {
                OrganSchool _organSchool = organSchoolMapper.selectById(branchSchool.getId());
                BeanUtils.copyProperties(branchSchool, _organSchool);
                organSchoolMapper.updateById(_organSchool);
            }
        }
    }

    @Transactional
    public OrganBranchSchoolResponseDto findOrgan(String id) {
        OrganBranchSchoolResponseDto organBranchSchoolResponseDto = new OrganBranchSchoolResponseDto();

        List<OrganSchool> branchSchools = organSchoolMapper.selectList(new QueryWrapper<OrganSchool>().lambda()
                .eq(OrganSchool::getOrganId, id)
                .eq(OrganSchool::getIsDel, false)
        );
        organBranchSchoolResponseDto.setList(branchSchools);

        Organ branchSchool = mapper.selectById(id);
        BeanUtils.copyProperties(branchSchool, organBranchSchoolResponseDto);

        return organBranchSchoolResponseDto;
    }

    public List<Organ> findAllOrgan() {
        return mapper.selectList(new QueryWrapper<Organ>().lambda()
                .eq(Organ::getIsDel, Boolean.FALSE)
        );
    }

}
