package com.securitycontrol.background.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.securitycontrol.background.mapper.HumanManageMapper;
import com.securitycontrol.background.service.HumanService;
import com.securitycontrol.common.core.constant.Constant;
import com.securitycontrol.common.core.constant.HttpStatus;
import com.securitycontrol.common.core.constant.SecurityConstants;
import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.utils.StringUtils;
import com.securitycontrol.common.core.utils.aes.AesCbcUtils;
import com.securitycontrol.common.core.utils.aes.DateTimeHelper;
import com.securitycontrol.common.core.utils.aes.ListHelper;
import com.securitycontrol.common.core.utils.aes.StringHelper;
import com.securitycontrol.common.core.utils.uuid.IdUtils;
import com.securitycontrol.common.core.web.domain.AjaxResult;
import com.securitycontrol.common.security.utils.ValidatorsUtils;
import com.securitycontrol.entity.background.dto.ParamDto;
import com.securitycontrol.entity.background.vo.HumanManageVo;
import com.securitycontrol.entity.background.vo.UserAccessVo;
import com.securitycontrol.entity.system.SystemGlobal;
import com.securitycontrol.entity.system.vo.ResourceFileVo;
import com.securitycontrol.system.api.RemoteFileService;
import com.securitycontrol.system.api.domain.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
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.*;

/**人员管理-业务逻辑层
 * @author 10488
 */
@Service(value = "HumanService")
@Slf4j
public class HumanServiceImpl implements HumanService {

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

    @Resource
    private RemoteFileService remoteFileService;

    @Resource(name = "ValidatorsUtils")
    private ValidatorsUtils validatorsUtils;

    @Override
    public List<HumanManageVo> getHumanLists(ParamDto dto) {
        List<HumanManageVo> list = new ArrayList<>();
        try {
            list = mapper.getHumanLists(dto);
        } catch (Exception e) {
            log.error("获取人员列表",e);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addOrUpdatePersonnel(MultipartFile file, String params) {
        String delFileId = null;
        try {
            HumanManageVo vo = JSON.parseObject(params, HumanManageVo.class);
            String validResult = validatorsUtils.valid(vo, HumanManageVo.Query.class);
            if (StringUtils.isNotBlank(validResult)) {
                return AjaxResult.error(validResult);
            }
            String userId = IdUtils.getUUId();
            List<Map<String, String>> list = mapper.userIsExist(vo);
            if (CollectionUtils.isNotEmpty(list)) {
                Boolean result = userIsExist(list,vo.getIdNumber());
                if (result) {
                    return AjaxResult.error("人员不能重复");
                }
            }
            if (StringUtils.isBlank(vo.getUserId())) {
                if (file == null) {
                    return AjaxResult.error("人员照片未上传");
                }
                vo.setType(1);
                vo.setUserId(userId);
                vo.setCreateTime(DateTimeHelper.getNowTime());
            } else {
                vo.setType(2);
                if (StringUtils.isNotEmpty(vo.getDelFiles())) {
                    String[] delFiles = vo.getDelFiles().split(",");
                    for (String fileId : delFiles) {
                        mapper.delFile(fileId);
                        remoteFileService.delFile(fileId,SecurityConstants.INNER);
                    }
                }
            }
            // 上传文件
            if (file != null) {
                Result result = remoteFileService.singleUploadFile(file, SecurityConstants.INNER);
                if(result != null && result.getCode() == HttpStatus.ERROR) {
                    log.error("人员照片上传失败");
                }else if(result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null){
                    String jsonString = JSON.toJSONString(result.getData());
                    JSONObject item = JSON.parseObject(jsonString);
                    delFileId = item.getString("fileId");
                    if (item != null) {
                        ResourceFileVo fileVo = new ResourceFileVo();
                        String resourceId = IdUtils.getUUId();
                        fileVo.setResourceId(resourceId);
                        fileVo.setFileType(1);
                        fileVo.setFileId(item.getString("fileId"));
                        fileVo.setFileSuffix(item.getString("suffix"));
                        fileVo.setFileName(item.getString("fileName"));
                        fileVo.setSourceId(vo.getType() == 1 ? userId : vo.getUserId());
                        fileVo.setUpdateTime(DateTimeHelper.getNowTime());
                        fileVo.setSourceType("人员照片");
                        mapper.addFiles(fileVo);
                    }
                }
            }
            vo.setIdNumber(AesCbcUtils.encrypt(vo.getIdNumber()));
            // 保存人员数据
            mapper.addOrUpdatePersonnel(vo);
        } catch (Exception e) {
            log.error("新增/修改人员",e);
            // 删除文件
            if (StringUtils.isNotEmpty(delFileId)) {
                remoteFileService.delFile(delFileId,SecurityConstants.INNER);
            }
            //手动回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 班组是否存在
     * @param list
     * @param idNumber
     * @return Boolean
     * @description
     * @author cwchen
     * @date 2024/3/21 10:36
     */
    public Boolean userIsExist(List<Map<String, String>> list, String idNumber) {
        for (Map<String, String> map : list) {
            String value = map.get("value");
            String decryptValue = AesCbcUtils.decrypt(value);
            if (decryptValue == null) {
                if (Objects.equals(idNumber, value)) {
                    return true;
                }
            } else {
                if (Objects.equals(idNumber, decryptValue)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public AjaxResult getPersonnelById(ParamDto dto) {
        HumanManageVo vo = new HumanManageVo();
        try {
            vo = mapper.getPersonnelById(dto);
            String decryptIdNumber = AesCbcUtils.decrypt(vo.getIdNumber());
            if(decryptIdNumber != null){
                vo.setIdNumber(decryptIdNumber);
            }
            List<ResourceFileVo> resourceFileVos = mapper.getFiles(vo.getUserId());
            if (CollectionUtils.isNotEmpty(resourceFileVos)) {
                List<HumanManageVo.FileData> list = new ArrayList<>();
                for (ResourceFileVo fileVo : resourceFileVos) {
                    String base64 = null;
                    Result<SysFile> result = remoteFileService.getImgBase64(fileVo.getFileId(), SecurityConstants.INNER);
                    if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
                        String jsonString = JSON.toJSONString(result.getData());
                        JSONObject item = JSON.parseObject(jsonString);
                        base64 = item.getString("url");
                    }
                    HumanManageVo.FileData fileData = new HumanManageVo.FileData();
                    fileData.setFileId(fileVo.getFileId());
                    fileData.setBase64Url(base64);
                    list.add(fileData);
                }
                vo.setFileData(list);
            }
        } catch (Exception e) {
            log.error("人员详情",e);
        }
        return AjaxResult.success(vo);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delPersonnelById(ParamDto dto) {
        try {
            if (StringUtils.isEmpty(dto.getId())) {
                return AjaxResult.error("参数不完整");
            }
            mapper.delPersonnelById(dto);
            // 查询人员照片
            List<ResourceFileVo> files = mapper.getFiles(dto.getId());
            if (CollectionUtils.isNotEmpty(files)) {
                files.forEach(item -> {
                    mapper.delFile(item.getFileId());
                    remoteFileService.delFile(item.getFileId(), SecurityConstants.INNER);
                });
            }

        } catch (Exception e) {
            log.error("删除人员", e);
            //手动回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult viewPersonnelFile(ParamDto dto) {
        List<HumanManageVo.FileData> list = new ArrayList<>();
        try {
            List<ResourceFileVo> resourceFileVos = mapper.getFiles(dto.getId());
            if (CollectionUtils.isNotEmpty(resourceFileVos)) {
                for (ResourceFileVo fileVo : resourceFileVos) {
                    String base64 = null;
                    Result<SysFile> result = remoteFileService.getImgBase64(fileVo.getFileId(), SecurityConstants.INNER);
                    if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
                        String jsonString = JSON.toJSONString(result.getData());
                        JSONObject item = JSON.parseObject(jsonString);
                        base64 = item.getString("url");
                    }
                    HumanManageVo.FileData fileData = new HumanManageVo.FileData();
                    fileData.setFileId(fileVo.getFileId());
                    fileData.setBase64Url(base64);
                    list.add(fileData);
                }
            }
        } catch (Exception e) {
            log.error("人员照片预览",e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public List<UserAccessVo> getPersonnelAccessLists(ParamDto dto) {
        List<UserAccessVo> list = new ArrayList<>();
        try {
            dto.setTypeCode(Constant.PERSON_CAR_TYPE);
            dto.setModeName(Constant.PERSON);
            list = mapper.getPersonnelAccessLists(dto);
            UserAccessVo userDetail = mapper.getUserDeatail(dto);
            String decryptIdNumber = AesCbcUtils.decrypt(userDetail.getIdNumber());
            if(decryptIdNumber != null){
                userDetail.setIdNumber(decryptIdNumber);
            }
            for (UserAccessVo vo : list) {
                String value = vo.getValue();
                vo.setIdNumber(userDetail.getIdNumber());
                vo.setUserPhone(userDetail.getUserPhone());
                vo.setUserName(userDetail.getUserName());
                String data = mapper.getUserAccessLists(value);
                if(StringUtils.isNotEmpty(data)){
                    String[] dataArr = data.split(",");
                    setUserAccessData(vo,dataArr);
                }
            }
        } catch (Exception e) {
            log.error("获取人员出入记录",e);
        }
        return list;
    }

    public UserAccessVo setUserAccessData(UserAccessVo vo,String[] valArr){
        for (String str : valArr) {
            String[] splitStr = str.split("@");
            if(Objects.equals(splitStr[0],Constant.ACCESS_TIME)){
                vo.setAccessTime(splitStr[1]);
            }else if(Objects.equals(splitStr[0],Constant.ACCESS_TYPE)){
                vo.setAccessType(splitStr[1]);
            }
        }
        return vo;
    }
    /**
     * 人员绑定安全膜
     * @param dto
     * @return
     */
    @Override
    public AjaxResult bindDev(ParamDto dto) {
        try{
            if (StringHelper.isEmpty(dto.getUserId())) {
                AjaxResult.error("未选择人员");
            }
            if (StringHelper.isEmpty(dto.getDevId())) {
                AjaxResult.error("未选择安全帽");
            }
            if(StringHelper.isEmpty(dto.getId())){
                int bidNum=mapper.getBindHis(dto);
                dto.setId(IdUtils.getUUId());
                if(bidNum>SystemGlobal.MIN_NUM){
                    return  AjaxResult.error("该人员已绑定安全帽");
                }
                int num= mapper.bindDev(dto);
                if(num== SystemGlobal.SUCCESS_NUM){
                    return  AjaxResult.success("绑定成功");
                }
            }else{
                int num= mapper.updateDev(dto);
                if(num== SystemGlobal.SUCCESS_NUM){
                    return  AjaxResult.success("修改成功");
                }

            }




            return  AjaxResult.error("绑定失败,数据未入库");
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error("系统升级中,请稍后重试");
        }
    }

    /**
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult delBind(ParamDto dto) {
        try{
            if (StringHelper.isEmpty(dto.getUserId())) {
                return  AjaxResult.error("人员不能为空");
            }
            int num= mapper.delBind(dto);
            if(num>SystemGlobal.MIN_NUM){
                return  AjaxResult.success("解除绑定成功");
            }
            return  AjaxResult.error("解除绑定失败");
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error("系统升级中,请稍后重试");
        }
    }

    @Override
    public AjaxResult getBindDetail(ParamDto dto) {
        try{
          List<ParamDto> list=mapper.getBindDetail(dto);
          if(ListHelper.isNotEmpty(list)){
              return   AjaxResult.success("请求成功",list.get(0));
          }
            return   AjaxResult.success("未绑定球机","");
        } catch (Exception e) {
            log.error(e.toString(),e);
        }
         return  AjaxResult.success("error","");
    }
}
