package com.reyun.saas.mob.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.reyun.saas.common.model.Constant;
import com.reyun.saas.common.restResult.PageParam;
import com.reyun.saas.common.restResult.RestResult;
import com.reyun.saas.common.restResult.ResultGenerator;
import com.reyun.saas.mob.user.dao.*;
import com.reyun.saas.mob.user.domain.*;
import com.reyun.saas.mob.user.dto.WarningConfigDTO;
import com.reyun.saas.mob.user.service.AuthService;
import com.reyun.saas.mob.user.service.WarningConfigService;
import com.reyun.saas.mob.user.vo.WarningConfigParam;
import com.reyun.saas.mob.user.vo.WarningConfigVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

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

/**
 * @desc
 */
@Transactional
@Service
public class WarningConfigServiceImpl implements WarningConfigService {
    @Resource
    private WarningConfigMapper warningConfigMapper;
    @Resource
    private WarningAddresseeMapper warningAddresseeMapper;
    @Resource
    private WarningColumnMapper warningColumnMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AppMapper appMapper;
    @Resource
    private ChannelMapper channelMapper;
    @Resource
    private AuthService authServiceImpl;
    @Resource
    private WarningDataInfoMapper warningDataInfoMapper;

    @Override
    public RestResult findColumnCode(String os) {
        Example example = new Example(WarningColumn.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("os",Arrays.asList("-1",os));
        example.and(criteria);
        List<WarningColumn> warningColumns = warningColumnMapper.selectByExample(example);
        return ResultGenerator.genSuccessResult(warningColumns);
    }

    @Override
    public RestResult create(WarningConfigVO warningConfigVO, String type, Long loginUserId) {
        User loginUser = userMapper.selectByPrimaryKey(loginUserId);
        WarningConfig warningConfig = warningConfigVO.getWarningConfig();
        List<WarningAddressee> addressees = warningConfigVO.getAddressees();

        warningConfig.setUserId(loginUser.getId());
        warningConfig.setRootParent(loginUser.getRealRootParent());
        warningConfig.setCreateEmail(loginUser.getUsername());
        warningConfig.setCreateTime(DateUtil.now());
        warningConfig.setDelFlag(false);

        if(type.equals("all")){//创建配置且创建模板
            if(!authServiceImpl.checkUserAppAuth(loginUser,warningConfig.getAppkey())){
                return ResultGenerator.genFailResult("没有操作权限");
            }
            //保存配置
            warningConfig.setIsusing(true);
            warningConfig.setTemplate(false);
            warningConfigMapper.insertSelective(warningConfig);
            for (WarningAddressee addressee : addressees) {
                addressee.setConfigId(warningConfig.getId());
                addressee.setIsusing(true);
            }
            warningAddresseeMapper.insertList(addressees);
            //保存模板
            WarningConfig warningConfigTemplate = new WarningConfig();
            BeanUtils.copyProperties(warningConfig,warningConfigTemplate);
            warningConfigTemplate.setId(null);
            warningConfigTemplate.setName(warningConfig.getTemplateName());
            warningConfigTemplate.setIsusing(false);
            warningConfigTemplate.setTemplate(true);
            warningConfigTemplate.setAppkey(null);
            warningConfigTemplate.setCid(null);
            warningConfigTemplate.setChannelId(null);
            warningConfigMapper.insertSelective(warningConfigTemplate);
            for (WarningAddressee addressee : addressees) {
                addressee.setConfigId(warningConfigTemplate.getId());
                addressee.setIsusing(true);
            }
            warningAddresseeMapper.insertList(addressees);
            return ResultGenerator.genSuccessResult();
        }else{
            if(type.equals("cfg")){//创建配置
                if(!authServiceImpl.checkUserAppAuth(loginUser,warningConfig.getAppkey())){
                    return ResultGenerator.genFailResult("没有操作权限");
                }
                warningConfig.setIsusing(true);
                warningConfig.setTemplate(false);
            }else if(type.equals("tmp")){//创建模板
                warningConfig.setIsusing(false);
                warningConfig.setTemplate(true);
            }else{
                return ResultGenerator.genFailResult("未知的类型");
            }
            warningConfigMapper.insertSelective(warningConfig);
            for (WarningAddressee addressee : addressees) {
                addressee.setConfigId(warningConfig.getId());
                addressee.setIsusing(true);
            }
            warningAddresseeMapper.insertList(addressees);
            return ResultGenerator.genSuccessResult();
        }
    }

    @Override
    public RestResult echo(Long id, Long loginUserId) {
        WarningConfig warningConfig = warningConfigMapper.selectByPrimaryKey(id);
        if(!authServiceImpl.checkloginUserAuth(loginUserId,warningConfig.getUserId())){
            return ResultGenerator.genFailResult("没有操作权限");
        }
        Example example = new Example(WarningAddressee.class);
        example.and().andEqualTo("configId",warningConfig.getId());
        List<WarningAddressee> warningAddressees = warningAddresseeMapper.selectByExample(example);
        WarningConfigVO build = WarningConfigVO.builder().addressees(warningAddressees).warningConfig(warningConfig).build();
        return ResultGenerator.genSuccessResult(build);
    }

    @Override
    public RestResult update(WarningConfigVO warningConfigVO, String type, Long loginUserId) {
        WarningConfig warningConfig = warningConfigVO.getWarningConfig();
        WarningConfig warningConfigDB = warningConfigMapper.selectByPrimaryKey(warningConfig.getId());
        if(!authServiceImpl.checkloginUserAuth(loginUserId,warningConfigDB.getUserId())){
            return ResultGenerator.genFailResult("没有操作权限");
        }
        if((warningConfigDB.getTemplate()&&type.equals("cfg")) || (!warningConfigDB.getTemplate()&&type.equals("tmp"))){
            return ResultGenerator.genSuccessResult("未知的类型");
        }
        List<WarningAddressee> addressees = warningConfigVO.getAddressees();
        WarningConfig warningConfigUpdate = new WarningConfig();
        warningConfigUpdate.setId(warningConfig.getId());
        warningConfigUpdate.setAppkey(warningConfig.getAppkey());
        warningConfigUpdate.setChannelId(warningConfig.getChannelId());
        warningConfigUpdate.setCid(warningConfig.getCid());
        warningConfigUpdate.setName(warningConfig.getName());
        warningConfigUpdate.setEval(warningConfig.getEval());
        warningConfigUpdate.setDataCycleRule(warningConfig.getDataCycleRule());
        if(type.equals("cfg")){
        }else if(type.equals("tmp")){
            warningConfigUpdate.setRemark(warningConfig.getRemark());
        }else{
            return ResultGenerator.genFailResult("未知的类型");
        }
        warningConfigMapper.updateByPrimaryKeySelective(warningConfigUpdate);
        Example example = new Example(WarningAddressee.class);
        example.and().andEqualTo("configId",warningConfig.getId());
        warningAddresseeMapper.deleteByExample(example);
        for (WarningAddressee addressee : addressees) {
            addressee.setConfigId(warningConfig.getId());
        }
        warningAddresseeMapper.insertList(addressees);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public RestResult listTemplate(PageParam pageParam, WarningConfigParam warningConfigParam, Long loginUserId) {
        List<Long> ids = authServiceImpl.getChildUserIdsAndOwn(loginUserId);
        PageHelper.startPage(pageParam.getPage(), pageParam.getSize());
        List<WarningConfigDTO> list = warningConfigMapper.selectTemplateByUserIds(StrUtil.join(",",ids),warningConfigParam.getEmail(),warningConfigParam.getSearchText(),warningConfigParam.getOs());
        PageInfo<WarningConfigDTO> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public RestResult listConfig(PageParam pageParam, WarningConfigParam warningConfigParam, Long loginUserId) {
        List<String> appkeys = new ArrayList<>();
        List<Long> channelIds = new ArrayList<>();
        searchTextAppAndChannel(warningConfigParam,appkeys,channelIds,loginUserId);
        List<Long> ids = authServiceImpl.getChildUserIdsAndOwn(loginUserId);
        PageHelper.startPage(pageParam.getPage(), pageParam.getSize());
        List<WarningConfigDTO> list = warningConfigMapper.selectConfigByUserIds(StrUtil.join(",",ids),StrUtil.join(",",appkeys),StrUtil.join(",",channelIds),warningConfigParam.getIsusing(),warningConfigParam.getAppkey(),warningConfigParam.getChannelId(),warningConfigParam.getOs());
        PageInfo<WarningConfigDTO> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    public void searchTextAppAndChannel(WarningConfigParam warningConfigParam,List<String> appkeys,List<Long> channelIds,Long loginUserId){
        /*String appkey = warningConfigParam.getAppkey();
        Long channelId = warningConfigParam.getChannelId();
        if(StrUtil.isNotEmpty(warningConfigParam.getAppkey())){
            appkeys.add("'"+appkey+"'");
        }
        if(warningConfigParam.getChannelId()!=null&&!warningConfigParam.getChannelId().equals(0L)){
            channelIds.add(channelId);
        }*/
        if(StrUtil.isNotEmpty(warningConfigParam.getSearchText())){
            List<Long> ids = authServiceImpl.getChildUserIdsAndOwn(loginUserId);
            //模糊查询渠道名和app名
            Example exampleApp = new Example(App.class);
            Example.Criteria criteriaApp = exampleApp.createCriteria().andIn("createUser",ids).andEqualTo("delFlag", false).andEqualTo("disableFlag", false).andLike("appName", "%" + warningConfigParam.getSearchText() + "%");
            exampleApp.and(criteriaApp);
            List<App> apps = appMapper.selectByExample(exampleApp);
            if(CollectionUtils.isEmpty(apps)){
                appkeys.add("'-1'");
            }else{
                for (App app : apps) {
                    appkeys.add("'"+app.getAppkey()+"'");
                }
            }
            User user = userMapper.selectByPrimaryKey(loginUserId);
            List<App> appsAuth = authServiceImpl.getAppByUser(user);
            List<String> appkeysAuth = new ArrayList<>();
            for (App app : appsAuth) {
                appkeysAuth.add(app.getAppkey());
            }
            Example exampleChannel = new Example(Channel.class);
            Example.Criteria criteriaChannel = exampleChannel.createCriteria().andIn("appkey",appkeysAuth).andEqualTo("delFlag",false).andEqualTo("active",true).andLike("channelAlias","%"+warningConfigParam.getSearchText()+"%");
            exampleChannel.and(criteriaChannel);
            List<Channel> channels = channelMapper.selectByExample(exampleChannel);
            if(CollectionUtils.isEmpty(channels)){
                channelIds.add(-1L);
            }else{
                for (Channel channel : channels) {
                    channelIds.add(channel.getId());
                }
            }
        }
    }
    @Override
    public RestResult delete(String ids, Long loginUserId) {
        User user = userMapper.selectByPrimaryKey(loginUserId);
        WarningConfig build = WarningConfig.builder().modifyEmail(user.getUsername()).modifyTime(DateUtil.now()).delFlag(true).build();
        Example example = new Example(WarningConfig.class);
        Example.Criteria criteria = example.createCriteria();
        if(!ids.equals("all")){
            criteria.andIn("id",Arrays.asList(ids.split(",")));
        }
        List<Long> userIds = authServiceImpl.getChildUserIdsAndOwn(loginUserId);
        criteria.andIn("userId",userIds);
        example.and(criteria);
        warningConfigMapper.updateByExampleSelective(build,example);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public RestResult enable(String ids, Boolean isusing, Long loginUserId) {
        User user = userMapper.selectByPrimaryKey(loginUserId);
        WarningConfig build = WarningConfig.builder().modifyEmail(user.getUsername()).modifyTime(DateUtil.now()).isusing(isusing).build();
        Example example = new Example(WarningConfig.class);
        Example.Criteria criteria = example.createCriteria();
        if(!ids.equals("all")){
            criteria.andIn("id",Arrays.asList(ids.split(",")));
        }
        List<Long> userIds = authServiceImpl.getChildUserIdsAndOwn(loginUserId);
        criteria.andIn("userId",userIds);
        criteria.andEqualTo("template",false);
        example.and(criteria);
        warningConfigMapper.updateByExampleSelective(build,example);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public RestResult selectTemplate(Long loginUserId, String appkey, String cid, String os) {
        List<Long> ids = authServiceImpl.getChildUserIdsAndOwn(loginUserId);
        Map<String,String> map= warningConfigMapper.selectConfigTemplateByUserIdsAandAppkeyAndCid(StrUtil.join(",",ids),appkey,cid,os);
        return ResultGenerator.genSuccessResult(map);
    }

    @Override
    public RestResult listAnalysis(PageParam pageParam, WarningConfigParam warningConfigParam, Long loginUserId) {
        if (warningConfigParam.getOs().equals("1")) {
            warningConfigParam.setOs(Constant.OS_IOS);
        }else{
            warningConfigParam.setOs(Constant.OS_ANDROID);
        }
        List<String> appkeys = new ArrayList<>();
        List<Long> channelIds = new ArrayList<>();
        searchTextAppAndChannel(warningConfigParam,appkeys,channelIds,loginUserId);
        List<Long> ids = authServiceImpl.getChildUserIdsAndOwn(loginUserId);
        PageHelper.startPage(pageParam.getPage(), pageParam.getSize());
        List<WarningConfigDTO> list = warningConfigMapper.selectConfigAnalysisByUserIds(StrUtil.join(",",ids),StrUtil.join(",",appkeys),StrUtil.join(",",channelIds),warningConfigParam.getStartDate(),warningConfigParam.getEndDate(),warningConfigParam.getAppkey(),warningConfigParam.getChannelId(),warningConfigParam.getOs());
        PageInfo<WarningConfigDTO> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public RestResult listAnalysisNextLayer(PageParam pageParam, WarningConfigParam warningConfigParam, Long loginUserId) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getSize());
        List<WarningDataInfo> warningDataInfos = warningDataInfoMapper.selectByConfigId(warningConfigParam);
        PageInfo<WarningDataInfo> pageInfo = new PageInfo<>(warningDataInfos);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

}
