package cn.com.ctop.toutiao.service.impl;

import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.toutiao.entity.BytedanceUrlInfo;
import cn.com.ctop.toutiao.mapper.BytedanceUrlInfoMapper;
import cn.com.ctop.toutiao.service.IBytedanceUrlInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 今日头条链接信息
 * @Author: jeecg-boot
 * @Date: 2019-08-06
 * @Version: V1.0
 */
@Service
public class BytedanceUrlInfoServiceImpl extends ServiceImpl<BytedanceUrlInfoMapper, BytedanceUrlInfo> implements IBytedanceUrlInfoService {

    @Override
    public Map<String, Object> insertLink(BytedanceUrlInfo template) {
        Map<String, Object> resultMap = new HashMap<>();
        Long id = template.getId();
        String name = template.getName();
        if (null == name || "".equals(name.trim())) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.TEMPLATE_NAME_IS_NULL.getCode());
            return resultMap;
        }
        String urlType = template.getType();
        if (null != urlType && "落地页".equals(urlType)) {
            template.setPackageName(null);
        }
        QueryWrapper<BytedanceUrlInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", template.getName());
        if (null != id && id != 0) {
            queryWrapper.ne("id", id);
        }
        BytedanceUrlInfo templateExist = getOne(queryWrapper);
        if (null != templateExist) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.TEMPLATE_NAME_HAS_EXIST.getCode());
            return resultMap;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        template.setAdvertiserId(user.getId());
        Date now = new Date();
        template.setCreateTime(now);
        template.setUpdateTime(now);
        this.saveOrUpdate(template);
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
        return resultMap;
    }
}
