package com.bonus.bracelet.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bonus.bracelet.mapper.DeviceMapper;
import com.bonus.bracelet.mapper.ResourceFileMapper;
import com.bonus.bracelet.mapper.SidebandMapper;
import com.bonus.bracelet.service.IDeviceService;
import com.bonus.bracelet.service.ISidebandService;
import com.bonus.common.core.constant.BusinessConstants;
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.UploadCheckUtils;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.utils.uuid.IdUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.entity.bracelet.BraceletParamsDto;
import com.bonus.common.entity.bracelet.vo.*;
import com.bonus.common.entity.file.ResourceFileVo;
import com.bonus.system.api.RemoteFileService;
import com.bonus.system.api.domain.SysFile;
import lombok.extern.slf4j.Slf4j;
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.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * DeviceServiceImpl
 */
@Service(value = "IDeviceService")
@Slf4j
public class DeviceServiceImpl implements IDeviceService {

    @Resource(name = "DeviceMapper")
    private DeviceMapper deviceMapper;

    @Resource
    private RemoteFileService remoteFileService;

    @Resource(name = "ResourceFileMapper")
    private ResourceFileMapper resourceFileMapper;

    @Override
    public List<DeviceVo> getDeviceLists(DeviceVo data) {
        List<DeviceVo> list = new ArrayList<>();
        try {
            list = deviceMapper.getDeviceLists(data);

        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return list;
    }

    /**
     * 根据边带id获得详细信息
     * @param deviceId
     * @return
     */
    @Override
    public AjaxResult selectDeviceById(Integer deviceId) {
        try {
            DeviceVo vo = deviceMapper.selectDeviceById(deviceId);
            return AjaxResult.success(vo);
        } catch (Exception e) {
            log.error("设备详情", e);
            return AjaxResult.error();
        }
    }


    /**
     * 新增设备信息
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addDevice(DeviceVo vo) {
        try {
            DeviceVo result = deviceMapper.isNameExist(vo);
            if (result != null) {
                return AjaxResult.error("设备名称已存在");
            }
            DeviceVo resultTwo = deviceMapper.isCodeExist(vo);
            if (resultTwo != null) {
                return AjaxResult.error("设备编码已存在");
            }
            int num =  deviceMapper.addDevice(vo);
            int numly = deviceMapper.getDeviceLy(vo.getDeviceId());
            if(numly==0){
                deviceMapper.addDeviceLy(vo.getDeviceId());
            }
            if(num==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("设备信息新增失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     *  新增设备属性信息
     * @param file
     * @param params
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addAttribute(MultipartFile file, String params) {
        // 文件ID
        String delFileId = null;
        try {
            AttributeVo vo = JSON.parseObject(params, AttributeVo.class);
            AttributeVo resultOne = deviceMapper.isDataCodeExist(vo);
            if (resultOne != null) {
                return AjaxResult.error("该设备的级联编号已存在，请重新输入");
            }

            if(file!=null){
                // 校验文件、上传文件
                String isVerify = UploadCheckUtils.uploadImgVerify(file);
                if (StringUtils.isNotBlank(isVerify)) {
                    return AjaxResult.error(isVerify);
                }
                int num =  deviceMapper.addAttribute(vo);
                if(num!=1){
                    return AjaxResult.error("设备属性数据新增失败");
                }
                delFileId = uploadFile(file,vo);
            }else{
                int num =  deviceMapper.addAttribute(vo);
                if(num!=1){
                    return AjaxResult.error("设备属性数据新增失败");
                }
            }
            return AjaxResult.success("新增成功");
        } catch (Exception e) {
            log.error("新增设备属性", e);
            // 添加失败-删除文件
            if (StringUtils.isNotEmpty(delFileId)) {
                remoteFileService.delFile(delFileId, SecurityConstants.INNER);
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 修改设备属性信息
     * @param file
     * @param params
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editAttribute(MultipartFile file, String params) {
        // 文件ID
        String delFileId = null;
        try {
            AttributeVo vo = JSON.parseObject(params, AttributeVo.class);
            AttributeVo resultOne = deviceMapper.isEditDataCodeExist(vo);
            if (resultOne != null) {
                return AjaxResult.error("该设备的级联编号已存在，请重新输入");
            }
            if(vo.getDelFileId() != null && vo.getDelFileId()!=""){
                deviceMapper.deleteFileId(vo.getDelFileId());
                remoteFileService.delFile(vo.getDelFileId(),SecurityConstants.INNER);
            }
            if(file!=null){
                // 校验文件、上传文件
                String isVerify = UploadCheckUtils.uploadImgVerify(file);
                if (StringUtils.isNotBlank(isVerify)) {
                    return AjaxResult.error(isVerify);
                }
                int num =  deviceMapper.editAttribute(vo);
                if(num!=1){
                    return AjaxResult.error("设备属性数据修改失败");
                }
                delFileId = uploadFile(file,vo);
            }else{
                int num =  deviceMapper.editAttribute(vo);
                deviceMapper.editFilePath(vo);
                if(num!=1){
                    return AjaxResult.error("设备属性数据修改失败");
                }
            }
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            log.error("修改设备属性", e);
            // 添加失败-删除文件
            if (StringUtils.isNotEmpty(delFileId)) {
                remoteFileService.delFile(delFileId, SecurityConstants.INNER);
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editDevice(DeviceVo vo) {
        try {
            DeviceVo result = deviceMapper.isExist(vo);
            if (result != null) {
                return AjaxResult.error("设备名称已存在");
            }

            DeviceVo resultTwo = deviceMapper.isExistCode(vo);
            if (resultTwo != null) {
                return AjaxResult.error("设备编码已存在");
            }

           int num =  deviceMapper.updateDevice(vo);
            if(num==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("设备信息修改失败");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteDeviceById(int deviceId) {
        try {
            int result = deviceMapper.deleteDeviceById(deviceId);
            int numly = deviceMapper.getDeviceLy(deviceId);
            if(numly==1){
                deviceMapper.deleteDeviceLy(deviceId);
            }
            if(result==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("设备信息删除失败");
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 设备属性列表
     * @param data
     * @return
     */
    @Override
    public List<AttributeVo> getDeviceAttributeLists(AttributeVo data) {
        List<AttributeVo> list = new ArrayList<>();
        try {
            list = deviceMapper.getDeviceAttributeLists(data);
            for (AttributeVo vo : list) {
                vo = handleData(vo);
            }

        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return list;
    }

    /**
     * 根据id获取设备属性
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getAttributeInfo(AttributeVo dto) {
        try {
            AttributeVo vo = deviceMapper.getAttributeInfo(dto);
            AttributeVo handleData = handleData(vo);
            return AjaxResult.success(handleData);
        } catch (Exception e) {
            log.error("设备属性详情", e);
            return AjaxResult.error();
        }
    }


    public AttributeVo handleData(AttributeVo vo) {
        R<SysFile> result = remoteFileService.getImgBase64(vo.getFilePath(), SecurityConstants.INNER);
        if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
            String jsonString = JSON.toJSONString(result.getData());
            JSONObject item = JSON.parseObject(jsonString);
            String base64 = item.getString("url");
            vo.setBase64Url(base64);
        }
        return vo;
    }

    public ResourceFileVo setResourceFileData(JSONObject item, AttributeVo vo) {
        ResourceFileVo fileVo = new ResourceFileVo();
        String resourceId = IdUtils.simpleUUID();
        fileVo.setFileType(1);
        fileVo.setFilePath(item.getString("fileId"));
        fileVo.setFileSuffix(item.getString("suffix"));
        fileVo.setFileName(item.getString("fileName"));
        fileVo.setSourceId(vo.getId() + "");
        fileVo.setSourceType("7");
        return fileVo;
    }

    public String uploadFile(MultipartFile file, AttributeVo vo) {
        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) {
                vo.setFilePath(item.getString("fileId"));
                deviceMapper.setFilePath(vo);
                ResourceFileVo fileVo = setResourceFileData(item, vo);
                resourceFileMapper.addFile(fileVo);
            }
            return item.getString("fileId");
        }
        return null;
    }

    /**
     * 删除设备属性
     *
     * @param id
     * @return 结果
     */
    @Override
    public AjaxResult delDeviceAttribute(Long id)
    {
        try {
            int num = 0;
            num =  deviceMapper.deleteFile(id);
            int num2 = deviceMapper.getFile(id);
            if(num2!=0){
                deviceMapper.deleFileSource(id);
                String filePath = deviceMapper.selectFilePathById(id);
                remoteFileService.delFile(filePath,SecurityConstants.INNER);
            }
            if(num==1){
                return AjaxResult.success();
            }
            return AjaxResult.error("设备属性删除失败");
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }
}
