package com.qianhe.zqbf.service.impl;

import com.qianhe.common.exception.BusinessException;
import com.qianhe.zqbf.domain.ZqbfXmzBfzj;
import com.qianhe.zqbf.domain.ZqczXmzDdzj;
import com.qianhe.zqbf.mapper.ZqczXmzDdzjMapper;
import com.qianhe.zqbf.service.ZqczXmzDdzjService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class ZqczXmzDdzjServiceImpl implements ZqczXmzDdzjService {
    @Autowired
    private ZqczXmzDdzjMapper ddzjMapper;
    /**
     * 条件查询
     */
    @Override
    public List<ZqczXmzDdzj> list(ZqczXmzDdzj zqczXmzDdzj) {
        List<ZqczXmzDdzj> dataList = ddzjMapper.list(zqczXmzDdzj);
        return dataList;
    }

    @Transactional
    @Override
    public int batchAdd(List<ZqbfXmzBfzj> xmzBfzjList) {
        if (Optional.ofNullable(xmzBfzjList).orElse(Collections.emptyList()).isEmpty()) {
            return 0;
        }
        Long xqid = xmzBfzjList.get(0).getXqid();
        ddzjMapper.delete(xqid);

        List<ZqczXmzDdzj> dataList = new ArrayList<>();
        int count = 0;
        for (ZqbfXmzBfzj zqbfXmzBfzj : xmzBfzjList) {
            if ("1".equals(zqbfXmzBfzj.getFzr())) count += 1;
            dataList.add(new ZqczXmzDdzj(zqbfXmzBfzj));
        }
        if (count != 1) {
            throw new BusinessException("必须指定一个负责人");
        }
        ddzjMapper.batchAdd(dataList);
        return 1;
    }
}
