package com.sptg.ad.biz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.ad.api.dto.AdTypeDto;
import com.sptg.ad.api.entity.AdType;
import com.sptg.ad.biz.mapper.AdTypeMapper;
import com.sptg.ad.biz.service.AdTypeServiceInterface;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.util.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * title: AdTypeServicelmpl
 * package: com.sptg.ad.biz.security.impl
 * description: 广告-服务层实现类
 *
 *
 *
 */
@Service
public class AdTypeServicelmpl extends ServiceImpl<AdTypeMapper, AdType> implements AdTypeServiceInterface{


    private final RedisTemplate<String,String> redisTemplate;

    @Autowired
    public AdTypeServicelmpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * Adtype缓存名称
     */
    private final static String AD_TYPE_CACHE_NAME = "sptg:ad:type";

    @Override
    public Page<AdType> showAdTypeList(AdTypeDto adTypeDto) {
        //排序字段 时间降序
        adTypeDto.getPage().setOrderByField("t_create_date");
        adTypeDto.getPage().setAsc(false);
        //构建查询条件
        Wrapper<AdType> wrapper = new EntityWrapper<>();
        //根据名字查询
        if(StringUtils.isNotBlank(adTypeDto.getName())){
            wrapper.like("s_name",adTypeDto.getName());
        }
        //排除删除的数据
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        //rootOrgId=1 总部，常运智慧科技公司账号--显示所有
        //  排序字段
        if (adTypeDto.getSortField() != null && adTypeDto.getSortOrder() != null){
            wrapper.orderBy(adTypeDto.getSortField(),adTypeDto.getSortOrder().equals("asc"));
        }else {
            //  排序字段 时间降序
            wrapper.orderBy("t_create_date",false);
        }
        isNotRootOrg(adTypeDto, wrapper);
        return this.selectPage(adTypeDto.getPage(), wrapper);
    }

    @Override
    public ResultBean<Boolean> addAdType(AdType adType) {
        if(this.insertOrUpdate(adType)){
            HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
            String hashKey = adType.getId().toString();
            //  保存到缓存中
            String json = JsonUtils.objectToJson(adType);
            hashOperations.put(AD_TYPE_CACHE_NAME,hashKey,json);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,true);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public ResultBean<Boolean> deleteAdType(String ids) {
        String[] id = ids.split(",");
        if(id!=null && ids.length()>0){
            List<String> list = Arrays.asList(id);
            Wrapper<AdType> wrapper = new EntityWrapper<>();
            wrapper.in("l_id", list);
            //需要修改状态的广告类型
            AdType type = new AdType();
            type.setStatus(OperationConstant.MINUS_ONE);
            //更新缓存
            for(String adTypeId :list){
                this.redisTemplate.opsForHash().delete(AD_TYPE_CACHE_NAME,adTypeId);
            }
            return new ResultBean<>(ResultEnum.SUCCESS, this.update(type,wrapper));
        }
        return new ResultBean<>(ResultEnum.ERROR);
    }

    @Override
    public ResultBean<AdType> getAdTypeList(Long rootOrgId) {
            //构建查询条件
        Wrapper<AdType> wrapper = new EntityWrapper<>();
        //排除删除的数据
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        //rootOrgId=1 总部，常运智慧科技账号
        if(rootOrgId!=1){
            List<Long> rootOrgIds = new ArrayList<>();
            rootOrgIds.add(rootOrgId);
            rootOrgIds.add((long) 1);
            //根机构和下级分类是共享的
            wrapper.in("l_root_org_id",rootOrgIds);
        }
        wrapper.orderBy("l_id", false);
        return new ResultBean<>(ResultEnum.SUCCESS,this.selectList(wrapper));
    }

    @Override
    public ResultBean<Boolean> checkAdTypeName(AdType adType) {
        Wrapper<AdType> wrapper = new EntityWrapper<>();
        //排除自身
        if(adType.getId()!=null){
            wrapper.notIn("l_id",adType.getId());
        }
        wrapper.eq("s_name",adType.getName());
        //排除删除的数据
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        isNotRootOrg(adType, wrapper);
        //统计
        int count = this.selectCount(wrapper);
        if(count>0){
            return new ResultBean<>(ResultEnum.SUCCESS,true);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,false);
    }

    @Override
    public AdType getAdTypeById(Long id) {
        //  查询缓存
        HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
        String hashKey = id.toString();
        String json = hashOperations.get(AD_TYPE_CACHE_NAME,hashKey);
        if (StringUtils.isEmpty(json)) {
            //  构建查询数据库
            Wrapper<AdType> wrapper = new EntityWrapper<>();
            //  根据Id查询
            wrapper.eq("l_id", id);
            AdType adType = this.selectOne(wrapper);
            if (null != adType) {
                //  保存到缓存中
                json = JsonUtils.objectToJson(adType);
                hashOperations.put(AD_TYPE_CACHE_NAME,hashKey,json);
            }
            return adType;
        }
        return JsonUtils.jsonToPojo(json,AdType.class);
    }

    @Override
    public Integer getAdTypeCount(AdTypeDto adTypeDto) {
        Wrapper<AdType> wrapper = new EntityWrapper<>();
        //查询某月数据
        if(adTypeDto.getSelectMonth()!=null){
            Calendar calendar=Calendar.getInstance();
            calendar.setTime(adTypeDto.getSelectMonth());
            int  year=calendar.get(Calendar.YEAR);
            int month= calendar.get(Calendar.MONTH)+1;
            wrapper.eq("DATE_FORMAT(t_create_date,'%Y%c')",year+""+month);
        }
        isNotRootOrg(adTypeDto, wrapper);
        //排除删除的数据
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        int count = this.selectCount(wrapper);
        return count;
    }

    private void isNotRootOrg(AdType adType, Wrapper<AdType> wrapper) {
        if(adType.getRootOrgId()!=1){
            List<Long> rootOrgIds = new ArrayList<>();
            rootOrgIds.add(adType.getRootOrgId());
            rootOrgIds.add((long) 1);
            //根机构和下级分类是共享的
            wrapper.in("l_root_org_id",rootOrgIds);
        }
    }
}
