package com.gic.haoban.manage.service.service.hm.impl;

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.Page;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.common.utils.PageUtil;
import com.gic.haoban.manage.api.enums.WelcomeRelationStatusEnum;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanWelcomeTemplateRelationMapper;
import com.gic.haoban.manage.service.entity.hm.TabHaobanWelcomeTemplateRelation;
import com.gic.haoban.manage.service.pojo.bo.hm.HmWelcomeRelationBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.WelcomeDetailBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.WelcomeReferBO;
import com.gic.haoban.manage.service.pojo.qo.WelcomeRelationQO;
import com.gic.haoban.manage.service.service.WelcomeService;
import com.gic.haoban.manage.service.service.hm.WelcomeRelationService;
import com.gic.redis.data.util.RedisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2022/7/4 5:50 PM
 * @Description
 * @Version
 **/
@Component
public class WelcomeRelationServiceImpl implements WelcomeRelationService {

    private static final Logger log = LoggerFactory.getLogger(WelcomeRelationServiceImpl.class);

    @Autowired
    private TabHaobanWelcomeTemplateRelationMapper welcomeTemplateRelationMapper;

    @Autowired
    private WelcomeService welcomeService;
    private static final String WELCOME_RELATION_KEY = "HM:welcome:relation:";
    private static final Long WELCOME_RELATION_CACHE_TIME = 5 * 60L;


    /**
     * 条件查询 欢迎语引用列表
     *
     * @param welcomeRelationQo
     * @return
     */
    @Override
    public List<HmWelcomeRelationBO> queryWelcomeRelationList(WelcomeRelationQO welcomeRelationQo) {
        List<TabHaobanWelcomeTemplateRelation> tabHaobanWelcomeTemplateRelations = welcomeTemplateRelationMapper.queryWelcomeTemplate(welcomeRelationQo);
        if (CollectionUtils.isEmpty(tabHaobanWelcomeTemplateRelations)) {
            return Collections.emptyList();
        }
        return tabHaobanWelcomeTemplateRelations.stream()
                .map(item -> {
                    HmWelcomeRelationBO welcomeRelationBo = new HmWelcomeRelationBO();
                    BeanUtils.copyProperties(item, welcomeRelationBo);
                    return welcomeRelationBo;
                }).collect(Collectors.toList());
    }

    /**
     * 分页查询 欢迎语关联列表
     *
     * @param welcomeRelationQo
     * @return
     */
    @Override
    public Page<HmWelcomeRelationBO> queryWelcomeRelationPage(WelcomeRelationQO welcomeRelationQo) {
        PageHelper.startPage(welcomeRelationQo.getPageNum(), welcomeRelationQo.getPageSize());
        com.github.pagehelper.Page<TabHaobanWelcomeTemplateRelation> tabHaobanWelcomeTemplateRelations =
                (com.github.pagehelper.Page<TabHaobanWelcomeTemplateRelation>) welcomeTemplateRelationMapper.queryWelcomeTemplate(welcomeRelationQo);
        return PageUtil.changePageHelperToCurrentPage(tabHaobanWelcomeTemplateRelations, HmWelcomeRelationBO.class);
    }

    /**
     * 保存欢迎语引用关联关系
     *
     * @param hmWelcomeRelationBO
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean saveHmWelcomeRelation(HmWelcomeRelationBO hmWelcomeRelationBO) {
        log.info("[saveHmWelcomeRelation] params:{}", JSON.toJSONString(hmWelcomeRelationBO));
        if (StringUtils.isAnyBlank(hmWelcomeRelationBO.getWelcomeId(), hmWelcomeRelationBO.getReferId(),
                hmWelcomeRelationBO.getEnterpriseId(), hmWelcomeRelationBO.getWxEnterpriseId(), hmWelcomeRelationBO.getReferName())) {
            return Boolean.FALSE;
        }
        if (hmWelcomeRelationBO.getType() == null) {
            return Boolean.FALSE;
        }
        TabHaobanWelcomeTemplateRelation welcomeTemplateRelation = new TabHaobanWelcomeTemplateRelation();
        welcomeTemplateRelation.setRelationId(UniqueIdUtils.uniqueLong());
        welcomeTemplateRelation.setEnterpriseId(hmWelcomeRelationBO.getEnterpriseId());
        welcomeTemplateRelation.setWxEnterpriseId(hmWelcomeRelationBO.getWxEnterpriseId());
        welcomeTemplateRelation.setWelcomeId(hmWelcomeRelationBO.getWelcomeId());
        welcomeTemplateRelation.setReferId(hmWelcomeRelationBO.getReferId());
        welcomeTemplateRelation.setReferCode(hmWelcomeRelationBO.getReferCode());
        welcomeTemplateRelation.setReferName(hmWelcomeRelationBO.getReferName());
        welcomeTemplateRelation.setType(hmWelcomeRelationBO.getType());
        welcomeTemplateRelation.setStatus(WelcomeRelationStatusEnum.ENABLE.getCode());
        welcomeTemplateRelation.setCreateTime(new Date());
        welcomeTemplateRelation.setUpdateTime(new Date());
        welcomeTemplateRelationMapper.insertSelective(welcomeTemplateRelation);
        return Boolean.TRUE;
    }

    /**
     * 删除关联关系
     *
     * @param hmWelcomeRelationBO
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean updateWelcomeRelation(HmWelcomeRelationBO hmWelcomeRelationBO) {
        log.info("[updateWelcomeRelationStatus] params:{}", JSON.toJSONString(hmWelcomeRelationBO));
        // 取消该referId已有的引用
        List<TabHaobanWelcomeTemplateRelation> tabHaobanWelcomeTemplateRelations =
                welcomeTemplateRelationMapper.queryWelTemplateRelation(null, hmWelcomeRelationBO.getReferId(), WelcomeRelationStatusEnum.ENABLE.getCode());
        if (CollectionUtils.isNotEmpty(tabHaobanWelcomeTemplateRelations)) {
            TabHaobanWelcomeTemplateRelation welcomeTemplateRelation = tabHaobanWelcomeTemplateRelations.get(0);
            if (StringUtils.equals(welcomeTemplateRelation.getWelcomeId(), hmWelcomeRelationBO.getWelcomeId())) {
                return Boolean.TRUE;
            }
            welcomeTemplateRelation.setUpdateTime(new Date());
            welcomeTemplateRelation.setStatus(hmWelcomeRelationBO.getStatus());
            if (welcomeTemplateRelation.getStatus() == null){
                welcomeTemplateRelation.setStatus(WelcomeRelationStatusEnum.DISABLE.getCode());
            }
            welcomeTemplateRelationMapper.updateByPrimaryKeySelective(welcomeTemplateRelation);

            // 定义
            this.removeWelcomeRelationCache(welcomeTemplateRelation.getReferId());
        }
        if (StringUtils.isNotBlank(hmWelcomeRelationBO.getWelcomeId())) {
            return this.saveHmWelcomeRelation(hmWelcomeRelationBO);
        }
        return Boolean.TRUE;
    }

    private void removeWelcomeRelationCache(String referId) {
        String welcomeRelationCacheKey = WELCOME_RELATION_KEY + referId;
        RedisUtil.delCache(welcomeRelationCacheKey);
    }
}
