package com.liquidnet.client.admin.zhengzai.kylin.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.common.enums.BannersTargetType;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.goblin.entity.GoblinSelfMarketing;
import com.liquidnet.service.goblin.mapper.GoblinSelfMarketingMapper;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dao.BannerDetailsListDao;
import com.liquidnet.service.kylin.dto.param.BannersParam;
import com.liquidnet.service.kylin.dto.param.BannersSearchParam;
import com.liquidnet.service.kylin.dto.vo.KylinBannersVo;
import com.liquidnet.service.kylin.entity.KylinBanners;
import com.liquidnet.service.kylin.entity.KylinBannersRelations;
import com.liquidnet.service.kylin.entity.KylinPerformances;
import com.liquidnet.service.kylin.mapper.KylinBannersMapper;
import com.liquidnet.service.kylin.mapper.KylinBannersRelationsMapper;
import com.liquidnet.service.kylin.mapper.KylinPerformancesMapper;
import com.liquidnet.service.kylin.service.admin.IKylinBannersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 轮播图 服务实现类
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-05-02
 */
@Service
public class KylinBannersServiceImpl extends ServiceImpl<KylinBannersMapper, KylinBanners> implements IKylinBannersService {

    @Value("${liquidnet.aliyun.oss.imgUrl}")
    private String imgUrl;

    @Autowired
    private KylinBannersMapper bannersMapper;

    @Autowired
    private KylinBannersRelationsMapper kylinBannersRelationsMapper;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisDataSourceUtil redisDataSourceUtil;

    @Autowired
    private GoblinSelfMarketingMapper goblinSelfMarketingMapper;

    @Autowired
    private KylinPerformancesMapper kylinPerformancesMapper;

    public boolean create(BannersParam bannersParam) {
        try {
            // 时间
            String bannersId = IDGenerator.nextSnowId();
            LocalDateTime createdAt = LocalDateTime.now();
            String createdAtString = DateUtil.Formatter.yyyyMMddHHmmss.format(createdAt);
            if (StringUtils.isEmpty(bannersParam.getOnlineStartTime())) {
                bannersParam.setOnlineStartTime(null);
            }
            if (StringUtils.isEmpty(bannersParam.getOnlineEndTime())) {
                bannersParam.setOnlineEndTime(null);
            }
            // 入数据库
            KylinBanners kylinBanners = bannersParam.getFields(bannersId, createdAtString);
            String performanceName = getPerformanceNameById(bannersParam.getPerformanceId());
            if (StringUtil.isBlank(performanceName)) {
                kylinBanners.setPerformanceId("");
                kylinBanners.setPerformanceName("");
            }else {
                kylinBanners.setPerformanceName(performanceName);
            }
            bannersMapper.insert(kylinBanners);

            List<String> positionList = bannersParam.getPositionList();
            KylinBannersRelations kylinBannersRelations = new KylinBannersRelations();
            String bannersRelationsId = IDGenerator.nextSnowId();
            kylinBannersRelations.setBannersRelationsId(bannersRelationsId);
            kylinBannersRelations.setBannersId(bannersId);
            kylinBannersRelations.setCreatedAt(createdAtString);
            for (String fieldId : positionList) {
                kylinBannersRelations.setFieldId(fieldId);
                kylinBannersRelations.setFieldIdType(1);
                kylinBannersRelationsMapper.insert(kylinBannersRelations);
            }
            List<String> provincesList = bannersParam.getProvincesList();
            if (!CollectionUtils.isEmpty(provincesList)) {
                List<String> provincesNameList = bannersParam.getProvincesNameList();
                for (int i = 0; i < provincesList.size(); i++) {
                    kylinBannersRelations.setFieldId(provincesList.get(i));
                    kylinBannersRelations.setFieldIdType(2);
                    kylinBannersRelations.setFieldName(provincesNameList.get(i));
                    kylinBannersRelationsMapper.insert(kylinBannersRelations);
                }
            }

            // 处理缓存数据
            setBannerListRedis();

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private String getPerformanceNameById(String performanceId) {
        if (StringUtil.isBlank(performanceId)) {
            return "";
        }
        List<KylinPerformances> kylinPerformances = kylinPerformancesMapper.selectList(new LambdaUpdateWrapper<KylinPerformances>()
                .eq(KylinPerformances::getPerformancesId, performanceId));

        if (kylinPerformances.isEmpty()) {
            return "";
        }
        return kylinPerformances.get(0).getTitle();
    }

    private void setBannerListRedis() {
        List<KylinBanners> bannerList = bannersMapper.selectList(
                Wrappers.lambdaQuery(KylinBanners.class).eq(KylinBanners::getIsOnline, 1)
                        .eq(KylinBanners::getIsDeleted, 1)
                        .orderByDesc(KylinBanners::getBannersSort)
        );
        for (KylinBanners banner : bannerList) {
            List<KylinBannersRelations> pList = kylinBannersRelationsMapper.selectList(
                    Wrappers.lambdaQuery(KylinBannersRelations.class).eq(KylinBannersRelations::getBannersId, banner.getBannersId())
                            .eq(KylinBannersRelations::getFieldIdType, 1)
            );
            List<String> pListStr = pList.stream().map(KylinBannersRelations -> KylinBannersRelations.getFieldId()).collect(Collectors.toList());
            List<KylinBannersRelations> proList = kylinBannersRelationsMapper.selectList(
                    Wrappers.lambdaQuery(KylinBannersRelations.class).eq(KylinBannersRelations::getBannersId, banner.getBannersId())
                            .eq(KylinBannersRelations::getFieldIdType, 2)
            );
            List<String> proListStr = proList.stream().map(KylinBannersRelations -> KylinBannersRelations.getFieldName()).collect(Collectors.toList());
            banner.setPositionList(pListStr);
            banner.setProvincesList(proListStr);
        }
        redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.ADMIN_BANNER_LIST, bannerList);
    }

    public boolean update(BannersParam bannersParam) {
        try {
            // 时间
            String bannersId = bannersParam.getBannersId();
            LocalDateTime updatedAt = LocalDateTime.now();
            String updatedAtString = DateUtil.Formatter.yyyyMMddHHmmss.format(updatedAt);

            KylinBanners params = bannersParam.getFields(null, null);
            params.setUpdatedAt(updatedAtString);
            String performanceName = getPerformanceNameById(bannersParam.getPerformanceId());
            if (StringUtil.isBlank(performanceName)) {
                params.setPerformanceId("");
                params.setPerformanceName("");
            }else {
                params.setPerformanceName(performanceName);
            }

            /*if (StringUtils.isEmpty(bannersParam.getOnlineStartTime())) {
                params.setOnlineStartTime(null);
            }
            if (StringUtils.isEmpty(bannersParam.getOnlineEndTime())) {
                params.setOnlineEndTime(null);
            }*/
            // 入数据库
            bannersMapper.update(params, new UpdateWrapper<KylinBanners>().eq("banners_id", bannersId));

            List<String> positionList = bannersParam.getPositionList();
            KylinBannersRelations kylinBannersRelations = new KylinBannersRelations();
            String bannersRelationsId = IDGenerator.nextSnowId();
            kylinBannersRelations.setBannersRelationsId(bannersRelationsId);
            kylinBannersRelations.setBannersId(bannersId);
            kylinBannersRelations.setCreatedAt(updatedAtString);
            // 入数据库 先删除之前的
            kylinBannersRelationsMapper.delete(
                    new UpdateWrapper<KylinBannersRelations>().eq("banners_id", bannersId).eq("field_id_type", 1)
            );
            for (String fieldId : positionList) {
                kylinBannersRelations.setFieldId(fieldId);
                kylinBannersRelations.setFieldIdType(1);
                kylinBannersRelationsMapper.insert(kylinBannersRelations);
            }
            List<String> provincesList = bannersParam.getProvincesList();
            // 入数据库 先删除之前的
            kylinBannersRelationsMapper.delete(
                    new UpdateWrapper<KylinBannersRelations>().eq("banners_id", bannersId).eq("field_id_type", 2)
            );
            if (!CollectionUtils.isEmpty(provincesList)) {
                List<String> provincesNameList = bannersParam.getProvincesNameList();
                if (!provincesList.isEmpty()) {
                    for (int i = 0; i < provincesList.size(); i++) {
                        kylinBannersRelations.setFieldId(provincesList.get(i));
                        kylinBannersRelations.setFieldIdType(2);
                        kylinBannersRelations.setFieldName(provincesNameList.get(i));
                        kylinBannersRelationsMapper.insert(kylinBannersRelations);
                    }
                }
            }

            // 处理缓存数据
            setBannerListRedis();

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public KylinBannersVo detail(String bannersId) {
        KylinBanners data = bannersMapper.selectOne(
                new UpdateWrapper<KylinBanners>().eq("banners_id", bannersId).eq("is_deleted", 1)
        );
        KylinBannersVo kylinBannersVo = new KylinBannersVo();
        if (null != data) {
            List<String> positionList = kylinBannersRelationsMapper.getBannersRelationsField("field_id", bannersId, 1);
            List<String> provincesList = kylinBannersRelationsMapper.getBannersRelationsField("field_id", bannersId, 2);
            GoblinSelfMarketing marketData = goblinSelfMarketingMapper.selectOne(Wrappers.lambdaQuery(GoblinSelfMarketing.class).eq(GoblinSelfMarketing::getSelfMarketId,data.getMarketId()));
            data.setPositionList(positionList);
            data.setProvincesList(provincesList);
            BeanUtils.copyProperties(data, kylinBannersVo);
            if(marketData!=null){
                kylinBannersVo.setMarketName(marketData.getName());
            }else{
                kylinBannersVo.setMarketName("");
            }
        } else {
            return null;
        }

        return kylinBannersVo;
    }

    public PageInfo<BannerDetailsListDao> bannerList(BannersSearchParam bannersSearchParam) {
        PageInfo<BannerDetailsListDao> pageInfoTmp = null;
        try {
            PageHelper.startPage(bannersSearchParam.getPageNum(), bannersSearchParam.getPageSize());
            List<BannerDetailsListDao> voList = bannersMapper.searchBannersList(BeanUtil.convertBeanToMap(bannersSearchParam));
            for (BannerDetailsListDao item : voList) {
                item.setIsOnlineName(item.getIsOnline());
                item.setPromotionTypeName(item.getPromotionType());

                String typeName = BannersTargetType.getTypeName(item.getTargetType());
                item.setTargetTypeName(typeName);

                item.setCoverImg(imgUrl + item.getCoverImg());
            }
            pageInfoTmp = new PageInfo(voList);
        } catch (Exception e) {
            return new PageInfo();
        }
        return pageInfoTmp;
    }

    public Boolean delete(List<String> bannersId) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();
            String updatedAtString = DateUtil.Formatter.yyyyMMddHHmmss.format(updatedAt);

            KylinBanners kylinBanners = new KylinBanners();
            kylinBanners.setUpdatedAt(updatedAtString);
            kylinBanners.setIsDeleted(0);
            bannersMapper.update(
                    kylinBanners
                    , new UpdateWrapper<KylinBanners>().in("banners_id", bannersId)
            );

            // 处理缓存数据
            setBannerListRedis();

            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
