package com.system.serivce.impl;

import com.system.constants.Constants;
import com.system.constants.RsaKeyConstant;
import com.system.dao.InitConnectParamMapper;
import com.system.scheduler.LicScheduler;
import com.system.serivce.ILicFileService;
import com.system.transfer.configure.LicInfoFileImportInVo;
import com.system.transfer.response.RestResponse;
import com.system.utils.FileUtil;
import com.system.utils.JsonUtil;
import com.system.utils.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @author Inori
 */
@Service
public class LicFileServiceImpl implements ILicFileService {

    @Autowired
    private RsaKeyConstant rsaKeyConstant;

    @Autowired
    private InitConnectParamMapper initConnectParamMapper;

    @Autowired
    private LicScheduler licScheduler;


    @Override
    public RestResponse licInfoFileImport(LicInfoFileImportInVo inVo) {
        if (!Objects.requireNonNull(inVo.getFile().getOriginalFilename()).equals(Constants.FILE_FORMAT)) {
            return RestResponse.fail("Lic文件格式错误");
        }

        try {
            String data = FileUtil.read(inVo.getFile().getInputStream());
            String result = RsaUtil.decryptByPublicKey(data, rsaKeyConstant.getPublicKey());
            Map<String, String> map = JsonUtil.toMap(result, String.class, String.class);
            if (CollectionUtils.isEmpty(map) || !map.containsKey(Constants.EFFECTIVE_TIME)) {
                return RestResponse.fail("Lic文件内容错误");
            }


            if (new Date().after(new SimpleDateFormat(Constants.TIME_FORMAT).parse(map.get(Constants.EFFECTIVE_TIME)))) {
                return RestResponse.fail("Lic文件导入时间已过期");
            }

            initConnectParamMapper.initConnectParamUpdate(data);
            licScheduler.setLicScheduler(Integer.parseInt(map.get(Constants.VERIFICATION_INTERVAL)));
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail("Lic文件保存失败");
        }

        return RestResponse.success();
    }


}
