package com.bonus.tcp.smartIdentify.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bonus.common.core.constant.HttpStatus;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.entity.tcp.DeviceUseVo;
import com.bonus.common.entity.tcp.PeopleVioVo;
import com.bonus.system.api.RemoteFileService;
import com.bonus.system.api.RemoteSourceService;
import com.bonus.system.api.domain.SysFileSource;
import com.bonus.tcp.smartIdentify.mapper.SmartIdentifyMapper;
import com.bonus.tcp.smartIdentify.service.SmartIdentifyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * @className:SmartIdentifyServiceImpl
 * @author:cwchen
 * @date:2024-08-27-15:15
 * @version:1.0
 * @description:智能识别
 */
@Service(value = "SmartIdentifyService")
@Slf4j
public class SmartIdentifyServiceImpl implements SmartIdentifyService {

    @Resource(name = "SmartIdentifyMapper")
    private SmartIdentifyMapper mapper;

    @Resource
    private RemoteFileService remoteFileService;

    @Resource
    private RemoteSourceService remoteSourceService;

    @Override
    public List<DeviceUseVo> getDevices(String puid) {
        List<DeviceUseVo> list = null;
        try {
            list = mapper.getDevices(puid);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addEventData(DeviceUseVo deviceUseVo, List<MultipartFile> files) {
        // 文件ID
        String delFileId = null;
        try {
            if (StringUtils.isNotBlank(deviceUseVo.getIdCard())) {
                List<PeopleVioVo> userIds = mapper.getUserByIdCard(Sm4Utils.encode(deviceUseVo.getIdCard()));
                if (CollectionUtils.isNotEmpty(userIds)) {
                    deviceUseVo.setUserId(userIds.get(0).getId());
                    deviceUseVo.setPeopleType(userIds.get(0).getPeopleType());
                    deviceUseVo.setWarnContent(userIds.get(0).getName() + deviceUseVo.getWarnContent());
                }
            }
            // 添加告警信息
            mapper.addWarnInfo(deviceUseVo);
            // 上传智能识别图片
            if (CollectionUtils.isNotEmpty(files)) {
                delFileId = uploadFile(files.get(0), deviceUseVo.getId());
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            // 添加失败-删除文件
            if (delFileId != null) {
                remoteFileService.delFile(delFileId, SecurityConstants.INNER);
            }
        }
    }

    public String uploadFile(MultipartFile file, Long warnId) {
        if (file == null) {
            return null;
        }
        R result = remoteFileService.singleUploadFile(file, SecurityConstants.INNER);
        if (result != null && result.getCode() == HttpStatus.ERROR) {
            log.error("违章照片上传失败");
            return null;
        } else if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
            String jsonString = JSON.toJSONString(result.getData());
            JSONObject item = JSON.parseObject(jsonString);
            if (item != null) {
                SysFileSource fileVo = setResourceFileData(item, warnId);
                R<Boolean> r = null;
                try {
                    r = remoteSourceService.addFileSource(fileVo, SecurityConstants.INNER);
                    if (!r.getData()) {
                        // 资源文件保存失败，删除文件
                        remoteFileService.delFile(item.getString("fileId"), SecurityConstants.INNER);
                        return null;
                    }
                } catch (Exception e) {
                    log.error(e.toString(), e);
                }
            }
            return item.getString("fileId");
        }
        return null;
    }

    public SysFileSource setResourceFileData(JSONObject item, Long warnId) {
        SysFileSource fileVo = new SysFileSource();
        fileVo.setFileType(1);
        fileVo.setFilePath(item.getString("fileId"));
        fileVo.setFileSuffix(item.getString("suffix"));
        fileVo.setFileName(item.getString("fileName"));
        fileVo.setSourceId(warnId + "");
        fileVo.setSourceType("8");
        return fileVo;
    }

}
