package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.BindAccountLogin;
import cn.com.ctop.common.module.mapper.BindAccountLoginMapper;
import cn.com.ctop.common.module.service.IBindAccountLoginService;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.common.module.vo.PangolinAccountVO;
import cn.com.ctop.common.module.vo.PangolinProjectVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 账号绑定-登陆
 * @Author: jeecg-boot
 * @Date: 2019-07-31
 * @Version: V1.0
 */
@Slf4j
@Service
public class BindAccountLoginServiceImpl extends ServiceImpl<BindAccountLoginMapper, BindAccountLogin> implements IBindAccountLoginService {
    @Autowired
    private BindAccountLoginMapper bindAccountLoginMapper;
    @Override
    public boolean checkLogin(BindAccountLogin bindAccountLogin, String response) {
        if (response.contains("<html>")) {
            bindAccountLogin.setCookie("");
            this.updateById(bindAccountLogin);
            return false;
        }
        return true;
    }

    @Override
    public BindAccountLogin selectByAccountId(String accountId) {
        QueryWrapper<BindAccountLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId).orderByDesc("id").last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public BindAccountLogin getByParams(String accountName, String password, String advertiserId) {
        QueryWrapper<BindAccountLogin> queryWrapper = new QueryWrapper<>();
        if(null!=accountName&&!"".equals(accountName)){
            queryWrapper.eq("account_name",accountName);
        }
        if(null!=password&&!"".equals(password)){
            queryWrapper.eq("password",password);
        }
        if(null!=advertiserId&&!"".equals(advertiserId)){
            queryWrapper.eq("advertiser_id",advertiserId);
        }
        queryWrapper.orderByDesc("create_time").last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public List<PangolinProjectVO> getProjectByParams(String userId, String loginType) {
        List<PangolinProjectVO> projectVos =  bindAccountLoginMapper.getProjectByParams(userId,loginType,null);
        List<PangolinProjectVO> setProjectVos = new ArrayList<>();
        if(null!=projectVos&&!projectVos.isEmpty()){
            projectVos.forEach(pangolinProjectVO -> {
                List<PangolinAccountVO>accountVos = bindAccountLoginMapper.getAccountByParams(userId,loginType,pangolinProjectVO.getProjectId());
                if(null!=accountVos&&!accountVos.isEmpty()){
                    pangolinProjectVO.setAccountVOList(accountVos);
                    setProjectVos.add(pangolinProjectVO);
                }
            });
        }
        return setProjectVos;
    }

    @Override
    public Map<String, Object> getListByUserId(String userId) {
        Map<String,Object>result = new HashMap<>();
        QueryWrapper<BindAccountLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_type", CtopAdConstant.PLATFORM_TYPE_PANGOLIN_PY);
        List<BindAccountLogin> loginList = new ArrayList<>();
        if(userId == null||"".equals(userId.trim())){
            loginList.add(new BindAccountLogin(0L,"全部"));
        }else{
            queryWrapper.eq("user_id",userId);
        }
        loginList.addAll(this.list(queryWrapper));
        result.put("data",loginList);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @Override
    public List<BindAccountLogin> getListByParams(String loginType, Integer status) {
        QueryWrapper<BindAccountLogin> queryWrapper = new QueryWrapper<>();
        if(null!=loginType&&!"".equals(loginType)){
            queryWrapper.eq("login_type",loginType);
        }
        if(status!=null){
            queryWrapper.eq("status",status);
        }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }

    @Override
    public CookieStore setCookie(BindAccountLogin bindAccountLogin,String domain) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<String> cookieList = mapper.readValue(bindAccountLogin.getCookie(), new TypeReference<List<String>>() {});
        if(cookieList == null||cookieList.isEmpty()){
            return null;
        }
        CookieStore cookieStore = new BasicCookieStore();
        for (String cookieStr : cookieList) {
            String[] cookieArray = cookieStr.split(";");
            Map<String, String> cookieMap = new HashMap<>();
            for (String cookie : cookieArray) {
                String[] kv = cookie.split("=");
                if (kv.length > 1) {
                    cookieMap.put(kv[0].trim(), kv[1].trim());
                }
            }
            BasicClientCookie clientCookie = new BasicClientCookie(cookieArray[0].split("=")[0],
                    cookieArray[0].split("=")[1]);
            clientCookie.setDomain(domain);
            clientCookie.setPath(cookieMap.get("path"));
            cookieStore.addCookie(clientCookie);
        }
        return cookieStore;
    }
}
