package org.springblade.manager.feign;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.manager.dto.SaveUserInfoByProjectDTO;
import org.springblade.manager.entity.ContractInfo;
import org.springblade.manager.mapper.SaveUserInfoByProjectMapper;
import org.springblade.manager.service.IContractInfoService;
import org.springblade.manager.service.impl.SaveUserInfoByProjectServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@AllArgsConstructor
public class ContractClientImpl implements ContractClient {

    private final IContractInfoService contractInfoService;
    private final SaveUserInfoByProjectMapper saveUserInfoByProjectMapper;
    private final SaveUserInfoByProjectServiceImpl saveUserInfoByProject;

    @Override
    public ContractInfo getContractById(Long id) {
        return this.contractInfoService.getById(id);
    }

    @Override
    public List<ContractInfo> queryContractListByIds(List<Long> ids) {
        return this.contractInfoService.selectContractByProjectIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveUserInfoByProjectTow(List<SaveUserInfoByProjectDTO> list) {
        if (list.size() > 0) {
            //判重
            list.forEach((lists) -> {
                Long row = saveUserInfoByProjectMapper.selectCount(
                        Wrappers.<SaveUserInfoByProjectDTO>query().lambda().
                                eq(SaveUserInfoByProjectDTO::getProjectId, lists.getProjectId()).
                                eq(SaveUserInfoByProjectDTO::getContractId, lists.getContractId()).
                                eq(SaveUserInfoByProjectDTO::getPostId, lists.getPostId()).
                                eq(SaveUserInfoByProjectDTO::getUserId, lists.getUserId()));

                if (row > 0L) {
                    throw new ServiceException(StringUtil.format("当前用户已存在该合同段下,请重新选择"));
                }
            });
            boolean result = saveUserInfoByProject.saveBatch(list);
            if (result) {
                return R.success("保存成功");
            }
        }
        return R.fail("保存失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveUserInfoByProjectThree(List<SaveUserInfoByProjectDTO> list) {
        if (list.size() > 0) {
            boolean result = saveUserInfoByProject.saveBatch(list);
            if (result) {
                return R.success("保存成功");
            }
        }
        return R.fail("保存失败");
    }



}
