package com.yunzhi.marketing.channel.sysChannel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhi.marketing.channel.sysChannel.entity.TaChannelProxy;
import com.yunzhi.marketing.channel.sysChannel.mapper.TaChannelProxyMapper;
import com.yunzhi.marketing.channel.sysChannel.service.ITaChannelProxyService;
import com.yunzhi.marketing.common.MD5Utils;
import com.yunzhi.marketing.entity.TaChannelAppRelation;
import com.yunzhi.marketing.mapper.TaChannelAppRelationMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TaChannelProxyServiceImpl extends ServiceImpl<TaChannelProxyMapper, TaChannelProxy>  implements ITaChannelProxyService {
    @Autowired
    private TaChannelProxyMapper taChannelProxyMapper;

    @Autowired
    private TaChannelAppRelationMapper taChannelAppRelationMapper;

    @Override
    public IPage<TaChannelProxy> getChannelList(IPage page) {
        IPage<TaChannelProxy> taChannelProxyIPage = taChannelProxyMapper.getChannelList(page);
        if (CollectionUtils.isNotEmpty(taChannelProxyIPage.getRecords())){
            taChannelProxyIPage.getRecords().forEach(e->{
                QueryWrapper<TaChannelAppRelation> taChannelAppRelationQueryWrapper = new QueryWrapper<>();
                taChannelAppRelationQueryWrapper.eq("channel_id", e.getChannelId());
                taChannelAppRelationQueryWrapper.groupBy("channel_id");
                e.setAppCurrentNum(taChannelAppRelationMapper.selectCount(taChannelAppRelationQueryWrapper));
            });
            taChannelProxyIPage.setRecords(taChannelProxyIPage.getRecords());
        }
        return taChannelProxyIPage;
    }

    @Override
    public void resetPassword(Integer id, String newPass) throws Exception {
        TaChannelProxy taChannelProxy = this.getById(id);
        if (null == taChannelProxy) {
            throw new Exception("未找到有效的渠道信息");
        }

        String encryptPass = MD5Utils.md5(MD5Utils.md5(newPass));
        TaChannelProxy proxy = new TaChannelProxy();
        proxy.setPassword(encryptPass);
        proxy.setChannelId(id);

        if (!this.updateById(proxy)) {
            throw new Exception("重置渠道密码失败");
        }
    }
}
