package com.skr.mdm.api.system.service.impl;

import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.skr.mdm.api.system.service.SystemParamService;
import com.skr.mdm.bean.qo.system.SystemParamQO;
import com.skr.mdm.bean.vo.system.SystemParamVO;
import com.skr.mdm.dao.AuCompanyDao;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.entity.AuCompanyDO;
import com.skr.mdm.enums.LogAdminTypeEnum;
import com.skr.mdm.handle.DownloadCounterHandler;
import com.skr.mdm.handle.LogAdminHandler;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.RedisGetKeyUtil;
import com.skr.mdm.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author nfq
 * @date 2023-03-13 14:16
 */
@Service
public class SystemParamServiceImpl implements SystemParamService {

    @Autowired
    private AuCompanyDao companyDao;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private LogAdminHandler logAdminHandler;
    @Autowired
    private DownloadCounterHandler downloadCounterHandler;

    @Override
    public ResponseResult getSystemParam(LoginAdminDTO loginAdminDTO) {
        AuCompanyDO companyDO = companyDao.selectById(loginAdminDTO.getCompanyId());
        SystemParamVO systemParamVO = SystemParamVO.builder()
                .maxDownloadNum(companyDO.getMaxDownloadNum())
                .nowDownloadNum(redisUtils.scanKeys(RedisGetKeyUtil.DOWNLOAD_TOKEN_KEY + loginAdminDTO.getCompanyId()).size())
                .build();
        return ResponseResult.success(systemParamVO);
    }

    @Override
    public ResponseResult updateParam(SystemParamQO systemParamQO, LoginAdminDTO loginAdminDTO) {
        new LambdaUpdateChainWrapper<>(companyDao)
                .eq(AuCompanyDO::getId, loginAdminDTO.getCompanyId())
                .set(systemParamQO.getMaxDownloadNum() != null, AuCompanyDO::getMaxDownloadNum, systemParamQO.getMaxDownloadNum())
                .update();
        downloadCounterHandler.update(loginAdminDTO.getCompanyId(), systemParamQO.getMaxDownloadNum());
        logAdminHandler.log(loginAdminDTO, loginAdminDTO.getAdminName(), LogAdminTypeEnum.OTHER_TYPE.getLogType(), "系统参数修改", "系统设置");
        return ResponseResult.success();
    }
}
