package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmImgMaintainDao;
import com.ssm.manage.entity.ImgMaintain;
import com.ssm.manage.entity.UploadFiles;
import com.ssm.manage.query.ImgMaintainRequest;
import com.ssm.manage.response.UserResponse;
import com.ssm.manage.service.SsmImgMaintainService;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class SsmImgMaintainServiceImpl extends BaseServiceImpl<ImgMaintain> implements SsmImgMaintainService {
    @Autowired
    private RedisClient<UserResponse> redisClient;

    @Autowired
    private SsmImgMaintainDao dao;

    @Override
    public SsmImgMaintainDao getDao() {
        return dao;
    }

    @Override
    public PageInfo<ImgMaintain> page(ImgMaintainRequest imgMaintainRequest) {
        return dao.page(imgMaintainRequest);
    }

    @Override
    public int saveInfo(List<ImgMaintain> uploadFilesInfo, String userNum) {
        int i = 0;
        UserResponse userResponse = new UserResponse();
        if (redisClient.hasKey(getKey(userNum))){
            userResponse = redisClient.get(getKey(userNum));
        }
        for (ImgMaintain imgMaintain : uploadFilesInfo) {
            imgMaintain.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            imgMaintain.setFunderName(userResponse.getUserName());
            imgMaintain.setFunderId(userResponse.getId());
            imgMaintain.setFunderDate(new Date());
            i = dao.saveNotNull(imgMaintain);
        }

        return i;
    }


    @Override
    public int delete(List<ImgMaintain> list) {
        int i = 0;
        for (ImgMaintain imgMaintain : list) {
            i = dao.delete(imgMaintain);
        }
        return i;
    }

    public String getKey(String userNum){
        String key = "";
        if (StringUtils.isNotBlank(userNum)){
            key = Constant.userKey + userNum;
        }
        return key;
    }
}
