package com.fdkankan.ucenter.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fdkankan.common.constant.SceneConstant;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.AesUtil;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.ucenter.common.FileUtil;
import com.fdkankan.ucenter.common.RSAEncrypt;
import com.fdkankan.ucenter.common.Result;
import com.fdkankan.ucenter.common.constants.ConstantFilePath;
import com.fdkankan.ucenter.common.constants.NacosProperty;
import com.fdkankan.ucenter.constant.CameraConstant;
import com.fdkankan.ucenter.constant.LoginConstant;
import com.fdkankan.ucenter.entity.VaildCameras;
import com.fdkankan.ucenter.mapper.IVaildCamerasMapper;
import com.fdkankan.ucenter.service.IVaildCamerasService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 代理商可用相机表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-11-02
 */
@Service
public class VaildCamerasServiceImpl extends ServiceImpl<IVaildCamerasMapper, VaildCameras> implements IVaildCamerasService {


    @Override
    public Result getVaildCameras(String file, String companyName) throws Exception {
        LambdaQueryWrapper<VaildCameras> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VaildCameras::getCompanyName,companyName);
        List<VaildCameras> vaildCamerasEntityList = this.list(wrapper);
        if(vaildCamerasEntityList == null || vaildCamerasEntityList.size() <= 0){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6011, CameraConstant.FAILURE_MSG_6011);
        }

        //生成需要加密的文件
        UUID uuid = UUID.randomUUID();
        String key = uuid.toString().replace("-","").substring(0,16);

        JSONArray array = new JSONArray();
        JSONObject object = null;
        for(VaildCameras vaildCamerasEntity: vaildCamerasEntityList){
            object = new JSONObject();
            object.put("Devicemac", vaildCamerasEntity.getDevicemac());
            array.add(object);
        }
        String aesData = AesUtil.encryptAES(array.toString(), key, key);

        String dataPath = ConstantFilePath.AGENT_PATH + companyName + File.separator + System.currentTimeMillis() + "_" + Math.random()*100 + "_key.txt";
        FileUtils.writeFile(dataPath, key);

        String secretPath = ConstantFilePath.AGENT_PATH + companyName + "/secret/";
        String fileName = System.currentTimeMillis() + "_public.pem";
        File targetFile = new File(secretPath + fileName);
        if(!targetFile.getParentFile().exists()){
            targetFile.getParentFile().mkdirs();
        }
        FileUtils.writeFile(secretPath + fileName, file);

        if(!new File(secretPath + fileName).exists()){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3018, LoginConstant.FAILURE_MSG_3018);
        }

        byte[] data = RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(secretPath + fileName)),
                FileUtil.toByteArray3(dataPath));

        //加密后的文件地址
        String resultPath = ConstantFilePath.AGENT_PATH + companyName + "/secretData/";
        String resultName = System.currentTimeMillis() + "_data.txt";
        FileUtils.writeFile(resultPath, resultName, data);

        Map map = new HashMap();
        map.put("aecData", aesData);
        map.put("keyUrl", NacosProperty.getMainUrl() + "agent/" + companyName + "/secretData/" + resultName);
        return Result.success(map);
    }

    @Override
    public Result addVaildCameras(String macId, String companyName, String wifiName) {
        String regex = "^[a-z0-9A-Z#]+$";
        if(!macId.matches(regex) || macId.length() != 25 || macId.indexOf("#") != 12){
            throw new BusinessException(SceneConstant.FAILURE_CODE_5012, SceneConstant.FAILURE_MSG_5012);
        }

        LambdaQueryWrapper<VaildCameras> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VaildCameras::getCompanyName,companyName);
        wrapper.eq(VaildCameras::getDevicemac,macId);
        List<VaildCameras> vaildCamerasEntityList = this.list(wrapper);

        if(vaildCamerasEntityList.size()>0 ){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6001, CameraConstant.FAILURE_MSG_6001);
        }

        VaildCameras vaildCameras = new VaildCameras();
        vaildCameras.setDevicemac(macId);
        vaildCameras.setWifiName(wifiName);
        vaildCameras.setCompanyName(companyName);
        this.save(vaildCameras);

        return Result.success();
    }

    @Override
    public Result deleteVaildCameras(String macId, String companyName) {
        LambdaQueryWrapper<VaildCameras> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VaildCameras::getCompanyName,companyName);
        wrapper.eq(VaildCameras::getDevicemac,macId);
        this.remove(wrapper);
        return Result.success();
    }
}
