package com.boman.web.core.service.ip;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.domain.IpTimes;
import com.boman.domain.SysUser;
import com.boman.domain.dto.AjaxResult;
import com.boman.web.core.mapper.IpTimesMapper;
import com.boman.web.core.utils.AuthUtils;
import org.springframework.stereotype.Service;

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

/**
 * @author shiqian
 * @date 2022年01月24日 11:15
 **/
@Service
public class IpTimesServiceImpl implements IpTimesService {

    @Resource
    private IpTimesMapper mapper;

    @Override
    public List<JSONObject> list(String ip, String times) {
        return mapper.list(ip, times);
    }

    @Override
    public JSONObject getById(Long id) {
        return mapper.getById(id);
    }

    @Override
    public JSONObject countByUsername(String username, String pwd) {
        return mapper.countByUsername(username, pwd);
    }

    @Override
    public JSONObject getByIp(String ip) {
        return mapper.getByIp(ip);
    }

    @Override
    public AjaxResult saveOrUpdate(JSONObject jsonObject) {
        String userName = AuthUtils.getLoginUser().getSysUser().getUserName();
        Long id = jsonObject.getLong("id");
//        ipTimes.setUpdateBy(userName);
        if (null == id) {
            //判断ip地址是否存在
            String ip = jsonObject.getString("ip");
            JSONObject byIp = mapper.getByIp(ip);
            if (byIp != null){
                return AjaxResult.error("当前ip已存在");
            }
            jsonObject.put("createBy", userName);
            mapper.save(jsonObject);
            return AjaxResult.success();
        }
        //判断ip地址是否重复
        String ip = jsonObject.getString("ip");
        JSONObject byIp = mapper.getByIp(ip);
        if (byIp != null && !byIp.getString("ip").equals(ip)){
            return AjaxResult.error("当前ip已存在");
        }
        jsonObject.put("updateBy", userName);
        mapper.update(jsonObject);
        return AjaxResult.success();
    }

    @Override
    public int delete(Long[] idArr) {
        int i = 0;
        for (Long aLong : idArr) {
            i += mapper.delete(aLong);
        }
        return i;
    }

    @Override
    public List<JSONObject> getAllColumns(String tableName) {
        if (ObjectUtils.isEmpty(tableName)) throw new IllegalArgumentException("tableName is empty");
        List<JSONObject> allColumns = mapper.getAllColumns(tableName);
        List<JSONObject> result = new ArrayList<>();
        for (JSONObject column : allColumns) {
            JSONObject jsonObject = new JSONObject(2);
            jsonObject.put("label", column.getString("Comment"));
            jsonObject.put("value", column.getString("Field"));
            result.add(jsonObject);
        }

        return result;
    }

    @Override
    public JSONObject selectByAppId(String appId) {
        return mapper.getByAppId(appId);
    }
}
