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.TPublicServiceResource;
import com.ruoyi.system.domain.system.enums.AttachEnums;
import com.ruoyi.system.mapper.publicservice.TOtherappAttachmentMapper;
import com.ruoyi.system.mapper.publicservice.TPublicServiceResourceMapper;
import com.ruoyi.system.service.publicservice.TOtherappAttachmentService;
import com.ruoyi.system.service.publicservice.TPublicServiceDemandService;
import com.ruoyi.system.service.publicservice.TPublicServiceResourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 资源
 * @author wujm<wujm@eazytec.com>
 */
@Service
public class TPublicServiceResourceServiceImpl implements TPublicServiceResourceService {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	private TPublicServiceResourceMapper tPublicServiceResourceMapper;

	@Autowired
	private PublicServiceRedisCache redisCache;

	@Autowired
	private TOtherappAttachmentService itOtherappAttachmentService;

	@Autowired
	private TOtherappAttachmentMapper tOtherappAttachmentMapper;

	@Autowired
	private TPublicServiceDemandService itPublicServiceDemandService;

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

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

    /**
     * 分页查询
     * @param tPublicServiceResource
     * @return
     */
	@Override
	public List<TPublicServiceResource> listTPublicServiceResource(TPublicServiceResource tPublicServiceResource) {
		return this.list(tPublicServiceResource);
	}

    /**
     * 新增
     * @param tPublicServiceResource
     * @return
     */
	@Override
	public int saveTPublicServiceResource(TPublicServiceResource tPublicServiceResource) {
		return tPublicServiceResourceMapper.save(tPublicServiceResource);
	}

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

    /**
     * 修改
     * @param tPublicServiceResource
     * @return
     */
	@Override
	public int updateTPublicServiceResource(TPublicServiceResource tPublicServiceResource) {
		return tPublicServiceResourceMapper.update(tPublicServiceResource);
	}

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


	/**
	 * 新增
	 * @param tPublicServiceResource
	 * @return
	 */
	@Override
	@Transactional
	public int saveResource(TPublicServiceResource tPublicServiceResource) {
		tPublicServiceResource.setResCode(this.getMaxNum(tPublicServiceResource));

		int result = tPublicServiceResourceMapper.save(tPublicServiceResource);

		if(!CollectionUtils.isEmpty(tPublicServiceResource.getAttachmentList())){
			for(TOtherappAttachment attachment : tPublicServiceResource.getAttachmentList()){
				attachment.setBusinessId(tPublicServiceResource.getResId().toString());
				attachment.setAttachType(AttachEnums.AttachType.RESOURCE.name());
				tOtherappAttachmentMapper.insertSelective(attachment);
			}
		}

		return result;
	}

	/**
	 * 根据id查询
	 * @param id
	 * @return
	 */
	@Override
	public TPublicServiceResource getResourceById(Long id) {
		TPublicServiceResource resource = this.getObjectById(id);

		if(null == resource){
			return null;
		}

		resource.setAttachmentList(itOtherappAttachmentService.listByBusinessIdAndType(Lists.newArrayList(id), AttachEnums.AttachType.RESOURCE.name()));

		return resource;
	}

	@Override
	public List<TPublicServiceResource> listResource(TPublicServiceResource tPublicServiceResource) {

		List<TPublicServiceResource> resources = this.list(tPublicServiceResource);

		List<Long> resIds = resources.stream().map(TPublicServiceResource::getResId).collect(Collectors.toList());

		List<TOtherappAttachment> attachments = itOtherappAttachmentService.listByBusinessIdAndType(resIds, AttachEnums.AttachType.RESOURCE.name());
		if(!CollectionUtils.isEmpty(attachments)){
			Map<String, List<TOtherappAttachment>> map = attachments.stream().collect(Collectors.groupingBy(TOtherappAttachment::getBusinessId));
			for(TPublicServiceResource resource : resources){
				resource.setAttachmentList(map.get(resource.getResId().toString()));
			}
		}


		return resources;
	}

	@Override
	public String getMaxNum(TPublicServiceResource resource){

		String bsConstant = "";
		String prefix = "";

		//类型 1 资源 2 需求
		if("1".equals(resource.getTypeName())){
			bsConstant = BsConstants.CACHE_KEY_RESOURCE_NO;
			prefix = "FZY";
		}else if("2".equals(resource.getTypeName())){
			bsConstant = BsConstants.CACHE_KEY_DEMAND_NO;
			prefix = "FXQZ";
		}

		String numKey = BsUtils.getBsCacheKey(String.format("%s%s",bsConstant));
		String num = "";
		if (!redisCache.keys().exists(numKey)) {
			resource = tPublicServiceResourceMapper.getMaxNo(resource);

			if(null == resource || StringUtils.isNull(resource.getResCode())){
				num = "00001";
			}else{
				num = resource.getResCode().substring(resource.getResCode().length()-5,resource.getResCode().length());
			}
			redisCache.strings().setnx(numKey,Integer.parseInt(num));
		}
		redisCache.keys().expire(numKey,1,TimeUnit.DAYS);
		Long no = redisCache.strings().incrBy(numKey, 1L);
		return prefix+BsUtils.formatMindNo(no,5);
	}

	@Override
	@Transactional
	public int updateResource(TPublicServiceResource tPublicServiceResource, String realName) {
		TPublicServiceResource resource = tPublicServiceResourceMapper.getObjectById(tPublicServiceResource.getResId());

		if(null == resource){
			throw new ServiceException("资源/需求记录不存在");
		}
		tPublicServiceResource.setUpdateTime(new Date());
		return tPublicServiceResourceMapper.update(tPublicServiceResource);
	}
}
