package com.org.web.person.service;


import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.org.system.enums.YesOrNoState;
import com.org.utils.SecurityUtil;
import com.org.web.person.domain.BcPersonFamily;
import com.org.web.person.mapper.BcPersonFamilyMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

@Service
@Slf4j
public class BcPersonFamilyService extends ServiceImpl<BcPersonFamilyMapper, BcPersonFamily> {

    /**
     * 新增或编辑
     */
    @Transactional(rollbackFor = Exception.class)
    public void executeSaveOrUpdate(Long personId, List<BcPersonFamily> newList) {
        Long userId = SecurityUtil.getUserId();

        List<BcPersonFamily> resultList = newList.stream()
                .filter(person -> Validator.isNotEmpty(person.getFamilyName()) || Validator.isNotEmpty(person.getRelation()) ||
                        Validator.isNotEmpty(person.getPhone()) || Validator.isNotEmpty(person.getWorkInfo()) )// 这里是过滤条件
                .collect(Collectors.toList());
        for (BcPersonFamily bcPersonFamily : resultList) {
            if (ObjectUtil.isEmpty(bcPersonFamily.getId())) {
                bcPersonFamily.setCreateBy(userId);
                bcPersonFamily.setCreateTime(new Date());
                bcPersonFamily.setIsDelete(YesOrNoState.NO.getState());
            } else {
                bcPersonFamily.setUpdateBy(userId);
                bcPersonFamily.setUpdateTime(new Date());
            }

            bcPersonFamily.setPersonId(personId);
        }
        this.saveOrUpdateBatch(resultList);

        List<Long> idList = resultList.stream().map(i -> i.getId()).collect(toList());
        // 删除编辑中没有的数据
        baseMapper.deleteWithout(personId, idList, userId);
    }

    /**
     * 列表
     */
    public List<BcPersonFamily> listByPersonId(Long personId) {
        log.info("BcPersonFamilyService - listByPersonId personId:{}", personId);

        return baseMapper.listByPersonId(personId);
    }

    /**
     * 删除
     */
    public boolean delByPersonId(Long personId) {
        log.info("BcPersonFamilyService - del personId:{}", personId);

        baseMapper.deleteByPersonId(personId, SecurityUtil.getUserId());

        return true;
    }
}
