package com.ruoyi.system.service.publicservice.impl;

import com.google.common.collect.Lists;
import com.ruoyi.common.constant.BsConstants;
import com.ruoyi.common.core.redis.PublicServiceRedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BsUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.Query;
import com.ruoyi.system.domain.publicservice.TOtherappAttachment;
import com.ruoyi.system.domain.publicservice.TPublicServiceDiscuss;
import com.ruoyi.system.domain.system.enums.AttachEnums;
import com.ruoyi.system.mapper.publicservice.TOtherappAttachmentMapper;
import com.ruoyi.system.mapper.publicservice.TPublicServiceDiscussMapper;
import com.ruoyi.system.service.publicservice.TOtherappAttachmentService;
import com.ruoyi.system.service.publicservice.TPublicServiceDiscussService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 公共服务 我发现表
 *
 * @author wangjie
 */
@Service
public class TPublicServiceDiscussServiceImpl implements TPublicServiceDiscussService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private TPublicServiceDiscussMapper tPublicServiceDiscussMapper;

    @Autowired
    private PublicServiceRedisCache redisCache;

    @Autowired
    private TOtherappAttachmentService itOtherappAttachmentService;

    @Autowired
    private TOtherappAttachmentMapper tOtherappAttachmentMapper;

    // 事务模板
    @Autowired
    private TransactionTemplate transactionTemplate;

    /** 基础功能不要直接写实现 */
    /**
     * 列表
     *
     * @return
     */
    private List<TPublicServiceDiscuss> list(TPublicServiceDiscuss tPublicServiceDiscuss) {
        return tPublicServiceDiscussMapper.list(tPublicServiceDiscuss);
    }

    /**
     * 查询
     *
     * @param id
     */
    private TPublicServiceDiscuss getObjectById(Long id) {
        Query query = new Query();
        query.put("discussId", id);
        return tPublicServiceDiscussMapper.getObjectById(query);
    }

    /**
     * 分页查询
     *
     * @param tPublicServiceDiscuss
     * @return
     */
    @Override
    public List<TPublicServiceDiscuss> listTPublicServiceDiscuss(TPublicServiceDiscuss tPublicServiceDiscuss) {
        return this.list(tPublicServiceDiscuss);
    }

    /**
     * 新增
     *
     * @param tPublicServiceDiscuss
     * @return
     */
    @Override
    public int saveTPublicServiceDiscuss(TPublicServiceDiscuss tPublicServiceDiscuss) {
        return tPublicServiceDiscussMapper.save(tPublicServiceDiscuss);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public TPublicServiceDiscuss getTPublicServiceDiscussById(Long id) {
        return this.getObjectById(id);
    }

    /**
     * 修改
     *
     * @param tPublicServiceDiscuss
     * @return
     */
    @Override
    public int updateTPublicServiceDiscuss(TPublicServiceDiscuss tPublicServiceDiscuss) {
        return tPublicServiceDiscussMapper.update(tPublicServiceDiscuss);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public int batchRemove(Long[] ids) {
        int count = 0;
        for (Long id : ids) {
            count += tPublicServiceDiscussMapper.remove(id);
        }
        return count;
    }

    @Override
    public String getMaxNum() {
        String numKey = BsUtils.getBsCacheKey(String.format("%s%s", BsConstants.CACHE_KEY_IFIND_NO));
        String num = "";
        if (!redisCache.keys().exists(numKey)) {
            TPublicServiceDiscuss discuss = new TPublicServiceDiscuss();
            discuss = tPublicServiceDiscussMapper.getMaxNo(discuss);
            if (null == discuss || StringUtils.isNull(discuss.getDiscussCode())) {
                num = "00001";
            } else {
                num = discuss.getDiscussCode().substring(discuss.getDiscussCode().length() - 5, discuss.getDiscussCode().length());
            }
            redisCache.strings().setnx(numKey, Integer.parseInt(num));
        }
        redisCache.keys().expire(numKey, 1, TimeUnit.DAYS);
        Long no = redisCache.strings().incrBy(numKey, 1L);
        return "WS" + BsUtils.formatMindNo(no, 5);
    }

    @Override
    public int saveDiscuss(TPublicServiceDiscuss tPublicServiceDiscuss, String userId) {
        return transactionTemplate.execute(status -> {
            //tPublicServiceDiscuss.setLabelId(bsUserinfo.getLabelId());
            tPublicServiceDiscuss.setDiscussCode(getMaxNum());
            int result = tPublicServiceDiscussMapper.save(tPublicServiceDiscuss);

            if (!CollectionUtils.isEmpty(tPublicServiceDiscuss.getAttachmentList())) {
                for (TOtherappAttachment attachment : tPublicServiceDiscuss.getAttachmentList()) {
                    attachment.setBusinessId(tPublicServiceDiscuss.getDiscussId().toString());
                    attachment.setAttachType(AttachEnums.AttachType.DISCUSS.name());
                    result = tOtherappAttachmentMapper.insertSelective(attachment);
                }
            }
            return result;
        });
    }

    @Override
    public TPublicServiceDiscuss getDiscussById(Long id) {
        TPublicServiceDiscuss discuss = this.getObjectById(id);
        if (null == discuss) {
            return null;
        }
        discuss.setAttachmentList(itOtherappAttachmentService.listByBusinessIdAndType(Lists.newArrayList(discuss.getDiscussId()), AttachEnums.AttachType.DISCUSS.name()));
        return discuss;
    }

    @Override
    public int updateDiscuss(TPublicServiceDiscuss tPublicServiceDiscuss, String realName) {
        TPublicServiceDiscuss discuss = tPublicServiceDiscussMapper.getObjectById(tPublicServiceDiscuss.getDiscussId());
        if (null == discuss) {
            throw new ServiceException("万事好商量记录不存在");
        }
        return tPublicServiceDiscussMapper.update(tPublicServiceDiscuss);
    }

}
