package com.house365.ws.interfaces.impl;

import com.house365.beans.entity.CloudRuleEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.dao.mapper.CloudRuleMapper;
import com.house365.ws.interfaces.server.ICloudRuleInterface;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Created by 365 on 2020/8/12.
 */
@Service("cloudRule")
public class CloudRuleImpl implements ICloudRuleInterface {

    @Autowired
    private CloudRuleMapper ruleMapper;

    @Override
    public HResult save(List<CloudRuleEntity> ruleList, UserEntity userEntity, String city) {
        HResult result = new HResult();
        Date date = new Date();
        for (CloudRuleEntity c : ruleList) {
            Map<String, Object> map = new HashMap<>(10);
            map.put("projectId", c.getProjectId());
            map.put("notUserId", userEntity.getId());
            List<CloudRuleEntity> list = ruleMapper.queryByConditions(map);
            if (CollectionUtils.isNotEmpty(list)) {
                String projectName = list.get(0).getProjectName();
                String tips = "[" + projectName + "]" + "已被其他人订阅，请重新选择";
                result.setStatus(500);
                result.setErrorMessage(tips);
                return result;
            }
        }
        //判断过滤，项目id没有绑定时在做新增操作，新增前删除该用户以前的规则，做覆盖处理
        ruleMapper.deleteByUserId(userEntity.getId());
        for (CloudRuleEntity entity : ruleList) {
            entity.setUserId(userEntity.getId());
            entity.setProjectName(entity.getProjectName());
            entity.setChannelName(entity.getChannelName());
            entity.setIsDelete(0);
            entity.setCityCode(city);
            entity.setCreateId(userEntity.getId());
            entity.setCreateName(userEntity.getRealName());
            entity.setCreateTime(date);
            ruleMapper.save(entity);
        }
        return result;
    }

    @Override
    public void deleteByUserId(int userId) {
        ruleMapper.deleteByUserId(userId);
    }

    @Override
    public CloudRuleEntity getById(int id) {
        return ruleMapper.getById(id);
    }

    @Override
    public List<CloudRuleEntity> queryByConditions(Map<String, Object> map) {
        List<CloudRuleEntity> list = ruleMapper.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        return Collections.emptyList();
    }
}
