package com.fdkankan.platform.agent.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.constant.*;
import com.fdkankan.common.util.AesUtil;
import com.fdkankan.common.util.FileUtil;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.common.util.RSAEncrypt;
import com.fdkankan.platform.agent.entity.VaildCameras;
import com.fdkankan.platform.agent.mapper.IVaildCamerasMapper;
import com.fdkankan.platform.agent.service.IVaildCamerasService;
import com.fdkankan.common.constant.CameraConstant;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.ServerCode;
import com.fdkankan.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

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

    private static Logger log = LoggerFactory.getLogger("programLog");

    @Value("${main.url}")
    private String mainUrl;

    @Override
    public HashMap<String,Object> getVaildCameras(String file, String companyName) throws Exception{
        if(StringUtils.isEmpty(file) || StringUtils.isEmpty(companyName)){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        List<VaildCameras> vaildCamerasEntityList = getListByCompanyName(companyName);
        if(vaildCamerasEntityList == null || vaildCamerasEntityList.size() <= 0){
            throw new BusinessException(CameraConstant.FAILURE_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(ErrorCode.FILE_NOT_EXIST);
        }

        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);
        HashMap<String,Object> map = new HashMap<>();
        map.put("aecData", aesData);
        map.put("keyUrl", mainUrl + "agent/" + companyName + "/secretData/" + resultName);
        return map;
    }

    @Override
    public String addVaildCameras(String macId, String wifiName, String companyName) {
        if(StringUtils.isEmpty(macId) || StringUtils.isEmpty(companyName)){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        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);
        }
        VaildCameras vaildCamerasEntity = this.getByCompanyNameAndDevicemac(companyName, macId);
        if(vaildCamerasEntity != null){
            throw new BusinessException(CameraConstant.FAILURE_6001);
        }
        vaildCamerasEntity = new VaildCameras();
        vaildCamerasEntity.setDevicemac(macId);
        vaildCamerasEntity.setWifiName(wifiName);
        vaildCamerasEntity.setCompanyName(companyName);
        this.save(vaildCamerasEntity);
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String deleteVaildCameras(String macId, String companyName) {
        if(StringUtils.isEmpty(macId) || StringUtils.isEmpty(companyName)){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        VaildCameras vaildCamerasEntity = this.getByCompanyNameAndDevicemac(companyName, macId);
        if(vaildCamerasEntity != null){
            this.removeById(vaildCamerasEntity);
        }
        return ServerCode.SUCCESS.message();
    }



    public List<VaildCameras> getListByCompanyName(String companyName){
        QueryWrapper<VaildCameras> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VaildCameras::getTbStatus,TbStatus.VALID.code());
        queryWrapper.lambda().eq(VaildCameras::getCompanyName,companyName);
        return this.list(queryWrapper);
    }
    public VaildCameras getByCompanyNameAndDevicemac(String companyName,String devicemac){
        QueryWrapper<VaildCameras> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VaildCameras::getTbStatus,TbStatus.VALID.code());
        queryWrapper.lambda().eq(VaildCameras::getCompanyName,companyName);
        queryWrapper.lambda().eq(VaildCameras::getDevicemac,devicemac);
        List<VaildCameras> list = this.list(queryWrapper);
        if(list == null || list.size() <= 0){
            return null;
        }
        return list.get(0);
    }
}
