package com.system.serivce.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.transfer.response.RestResponse;
import com.system.constants.RsaKeyConstant;
import com.system.dao.LicInfoMapper;
import com.system.serivce.ILicInfoService;
import com.system.transfer.lic.*;
import com.system.utils.DownloadUtil;
import com.system.utils.JsonUtil;
import com.system.utils.RsaUtil;
import com.system.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Inori
 */
@Service
public class LicInfoServiceImpl implements ILicInfoService {

    @Autowired
    private LicInfoMapper licInfoMapper;

    @Autowired
    private RsaKeyConstant rsaKeyConstant;


    @Override
    public LicInfoListOutVo licInfoList(LicInfoListInVo inVo) {
        Page<LicInfoListOutVoRecords> page = new Page<>(inVo.getPageNo(), inVo.getPageSize());
        List<LicInfoListOutVoRecords> recordsList = licInfoMapper.licInfoList(page, inVo);

        LicInfoListOutVo outVo = new LicInfoListOutVo();
        outVo.setTotal((int) page.getTotal());
        outVo.setRecords(recordsList);
        return outVo;
    }

    @Override
    public void licInfoCreate(LicInfoCreateInVo inVo) {

        licInfoMapper.licInfoCreate(inVo);
    }

    @Override
    public void licInfoUpdate(LicInfoUpdateInVo inVo) {

        licInfoMapper.licInfoUpdate(inVo);
    }

    @Override
    public void licInfoDelete(LicInfoDeleteInVo inVo) {
        licInfoMapper.licInfoDelete(inVo);
    }

    @Override
    public RestResponse licInfoFileCreate(LicInfoFileCreateInVo inVo, HttpServletResponse response) {
        LicInfoListOutVoRecords records = licInfoMapper.getLicInfoByMacAddress(inVo.getMacAddress());
        if (StringUtil.isNull(records)) {
            return RestResponse.fail("MAC地址不存在");
        }

        try {
            String data = RsaUtil.encryptByPrivateKeyToLong(JsonUtil.toString(records), rsaKeyConstant.getPrivateKey());
            DownloadUtil.download(response, data, records.getMacAddress());
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail("Lic文件生成失败");
        }
        return RestResponse.success();
    }

    @Override
    public String licInfoCreate(String macAddress) throws Exception {
        LicInfoListOutVoRecords records = licInfoMapper.getLicInfoByMacAddress(macAddress);
        String data = RsaUtil.encryptByPrivateKeyToLong(JsonUtil.toString(records), rsaKeyConstant.getPrivateKey());
        return data;

    }

}
