package org.jeecg.modules.basedata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import org.jeecg.modules.basedata.entity.FdHospital;
import org.jeecg.modules.basedata.entity.FdHospitalContacts;
import org.jeecg.modules.basedata.mapper.FdHospitalContactsMapper;
import org.jeecg.modules.basedata.mapper.FdHospitalMapper;
import org.jeecg.modules.basedata.service.IFdHospitalContactsService;
import org.jeecg.modules.basedata.service.IFdHospitalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Description: 医院档案表
 * @author： jeecg-boot
 * @date：   2019-05-05
 * @version： V1.0
 */
@Service
@Transactional
public class FdHospitalServiceImpl extends ServiceImpl<FdHospitalMapper, FdHospital> implements IFdHospitalService {

    @Resource
    public FdHospitalMapper fdHospitalMapper;
    @Resource
    public IFdHospitalContactsService iFdHospitalContactsService;


    @Override
    public IPage<FdHospital> findByPage(Page<FdHospital> page, QueryWrapper<FdHospital> queryWrapper) {
        return fdHospitalMapper.findByPage(page,queryWrapper);
    }

    @Override
    @Transactional
    public void saveHospitalAndContacts(FdHospital hospital) {
        List<FdHospitalContacts> hospitalContacts = hospital.getHospitalContacts();
        if(hospitalContacts==null || hospitalContacts.isEmpty()){
            throw new RuntimeException("医院联系人不能为空");
        }
        if(hospital.getId()==""||hospital.getId()==null){
            //新增
            save(hospital);
        }else{
            //修改
            LambdaQueryWrapper<FdHospitalContacts> queryContacts = new LambdaQueryWrapper<>();
            queryContacts.eq(FdHospitalContacts::getPkHospitalId, hospital.getId());
            iFdHospitalContactsService.remove(queryContacts);
            fdHospitalMapper.updateById(hospital);
        }

        String id = hospital.getId();
        int count = 0;
        for(FdHospitalContacts hospitalContact : hospitalContacts){
            String isDefault = hospitalContact.getIsDefault();
            if("1".equals(isDefault)){
                count++;
            }
            hospitalContact.setPkHospitalId(id);
        }
        if(count==0){
            throw new RuntimeException("您必须为医院指定一个默认的联系人");
        }
        if(count>2){
            throw new RuntimeException("只能有一个默认的医院联系人");
        }
        iFdHospitalContactsService.saveBatch(hospitalContacts);
    }
}
