package com.ytpm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.advertise.param.AddPlacementParam;
import com.ytpm.advertise.view.AddPlacementResponse;
import com.ytpm.agent.model.YtAppPlacement;
import com.ytpm.agent.param.PlacementListParam;
import com.ytpm.agent.param.PlacementParam;
import com.ytpm.agent.view.AgentPlacementView;
import com.ytpm.dao.PlacementMapper;
import com.ytpm.feign.AdvertiseFeign;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.service.PlacementService;
import com.ytpm.utils.GetTakuInfoUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class PlacementServiceImpl implements PlacementService {

    @Resource
    private PlacementMapper placementMapper;
    @Resource
    private AdvertiseFeign advertiseFeign;

    @Resource
    private GetTakuInfoUtil getTakuInfoUtil;

    /**
     * 查询广告位列表
     */
    @Override
    public ResultTable<AgentPlacementView> placementList(PlacementListParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        return ResultTable.resultTableOk(new PageInfo<AgentPlacementView>(placementMapper.selectList(param)));
    }

    /**
     * 保存广告位
     * PS: 如需改变顺序请加上事务处理
     */
    @Override
    public Result<?> savePlacement(PlacementParam param,String userId) {
        AddPlacementParam placementParam = new AddPlacementParam(param);
        //设置数量为1
        placementParam.setCount(1);
        //获取takuPublicKey
        String takuPublicKey = getTakuInfoUtil.getTakuPublicKey(userId);
        placementParam.setTakuPublicKey(takuPublicKey);
        ResultTable<AddPlacementResponse> resultTable = advertiseFeign.savePlacement(placementParam);
        AddPlacementResponse response = resultTable.getData().get(0);
        YtAppPlacement placement = new YtAppPlacement();
        BeanUtil.copyProperties(param, placement);
        if(StrUtil.isNotBlank(param.getPlacementId())){
            placementMapper.updateOne(placement);
        }else{
            placement.setPlacementId(response.getPlacement_id());
            placement.setPlacementName(response.getPlacement_name());
            placementMapper.addOne(placement);
        }
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }

    /**
     * 删除广告位
     */
    @Override
    public Result<?> delPlacement(String placementId,String userId) {
        //获取takuPublicKey
        String takuPublicKey = getTakuInfoUtil.getTakuPublicKey(userId);
        advertiseFeign.delPlacement(placementId,takuPublicKey);
        placementMapper.deleteOne(placementId);
        return Result.resultOk(RepMessage.DELETE_SUCCESS);
    }


}
