package com.ytpm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.agent.model.YtAppAdSource;
import com.ytpm.agent.param.AdSourceListParam;
import com.ytpm.agent.param.AdSourceParam;
import com.ytpm.agent.view.AgentAdSourceView;
import com.ytpm.dao.AdSourceMapper;
import com.ytpm.feign.AdvertiseFeign;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.service.AdSourceService;
import com.ytpm.utils.GetTakuInfoUtil;
import org.springframework.stereotype.Service;

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

@Service
public class AdSourceServiceImpl implements AdSourceService {

    @Resource
    private AdSourceMapper adSourceMapper;

    @Resource
    private AdvertiseFeign advertiseFeign;

    @Resource
    private GetTakuInfoUtil getTakuInfoUtil;

    @Override
    public ResultTable<AgentAdSourceView> adSourceList(AdSourceListParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        List<AgentAdSourceView> agentAdSourceViews = adSourceMapper.adSourceList(param);
        return ResultTable.resultTableOk(new PageInfo<>(agentAdSourceViews));
    }

    @Override
    public Result<?> addOne(AdSourceParam param) {
        //调用api接口进行广告源新增
        YtAppAdSource ytAppAdSource = new YtAppAdSource();
        ytAppAdSource.setName(param.getName());
        ytAppAdSource.setType(param.getType());
        ytAppAdSource.setMixFormat(param.getMix_format());
        ytAppAdSource.setPlacementId(param.getPlacementId());
        ytAppAdSource.setEnabled(1);
        adSourceMapper.insertOne(ytAppAdSource);
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }

    @Override
    public Result<?> updateOne(AdSourceParam param) {
        //调用api接口进行广告源修改
        YtAppAdSource ytAppAdSource = new YtAppAdSource();
        ytAppAdSource.setAdSourceId(param.getAdSourceId());
        ytAppAdSource.setName(param.getName());
        ytAppAdSource.setType(param.getType());
        ytAppAdSource.setMixFormat(param.getMix_format());
        ytAppAdSource.setPlacementId(param.getPlacementId());
        ytAppAdSource.setEnabled(1);
        adSourceMapper.update(ytAppAdSource);
        return Result.resultOk(RepMessage.MODIFY_SUCCESS);
    }

    @Override
    public Result<?> deleteOne(Integer adSourceId,String userId) {
        String takuPublicKey = getTakuInfoUtil.getTakuPublicKey(userId);
        advertiseFeign.delAdSource(adSourceId,takuPublicKey);
        YtAppAdSource ytAppAdSource = new YtAppAdSource();
        ytAppAdSource.setEnabled(0);
        ytAppAdSource.setAdSourceId(adSourceId);
        adSourceMapper.update(ytAppAdSource);
        return Result.resultOk(RepMessage.DELETE_SUCCESS);
    }
}
