package com.bonus.bracelet.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bonus.bracelet.mapper.BaseProjectMapper;
import com.bonus.bracelet.mapper.ResourceFileMapper;
import com.bonus.bracelet.service.IBaseProjectService;
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.constant.UserConstants;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.UploadCheckUtils;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.utils.global.SystemGlobal;
import com.bonus.common.core.utils.uuid.IdUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.entity.bracelet.vo.BaseProject;
import com.bonus.common.entity.bracelet.vo.PersonVo;
import com.bonus.common.entity.file.ResourceFileVo;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.RemoteFileService;
import com.bonus.system.api.domain.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.Arrays;
import java.util.List;
import java.util.Map;


import static com.bonus.common.core.web.domain.AjaxResult.error;
import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * 岗位信息 服务层处理
 * 
 * @author bonus
 */
@Service
@Slf4j
public class BaseProjectServiceImpl implements IBaseProjectService
{
    @Autowired
    private BaseProjectMapper projectMapper;

    @Resource
    private RemoteFileService remoteFileService;

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

    /**
     * 查询项目数据集合
     *
     * @param project 项目信息
     * @return 项目数据集合
     */
    @Override
    public List<BaseProject> selectProjectList(BaseProject project)
    {
//        return projectMapper.selectProjectList(project);
        List<BaseProject> list = new ArrayList<>();
        try {
            list = projectMapper.selectProjectList(project);
            for (BaseProject vo : list) {
                vo.setContactInformation(Sm4Utils.decode(vo.getContactInformation()));
                vo.setAppnum(projectMapper.getAppCount(vo.getProjectId()));
                vo.setPronum(projectMapper.getProCount(vo.getProjectId()));
            }
        } catch (Exception e) {
            log.error("查询人员列表", e);
        }
        return list;
    }

    /**
     *通过项目名称查询项目信息
     * @param projectId
     * @return
     */

    @Override
    public AjaxResult selectProjectById(Integer projectId) {
        try {
            BaseProject vo = projectMapper.selectProjectById(projectId);
            vo.setContactInformation(Sm4Utils.decode(vo.getContactInformation()));
            if(ObjectUtil.isNotEmpty(vo)){
                List<ResourceFileVo>   list = projectMapper.selectProjectFile(projectId);
                getImageFile(list);
                vo.setFileList(list);
            }

            return AjaxResult.success(vo);
        } catch (Exception e) {
            log.error("项目详情", e);
            return AjaxResult.error();
        }
    }

    /**
     * 修改条件下校验项目名称是否唯一
     * @param project 项目信息
     * @return 结果
     */
    @Override
    public boolean checkProjectDeptNameUnique(BaseProject project)
    {
        String projectDepartName =  project.getProjectDepartName();
        BaseProject projectTemp = projectMapper.checkProjectDeptNameUnique(projectDepartName,project.getProjectId());
        if (StringUtils.isNotNull(projectTemp))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增条件下校验项目名称是否唯一
     * @param project 项目信息
     * @return 结果
     */
    @Override
    public boolean checkProjectDeptNameUniqueAdd(BaseProject project)
    {
        String projectDepartName =  project.getProjectDepartName();
        Integer projectId = project.getProjectId();
        BaseProject projectTemp = projectMapper.checkProjectDeptNameUniqueAdd(projectDepartName);
        if (StringUtils.isNotNull(projectTemp))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     *
     * @param file
     * @param params
     * @return
     */
    @Override
    public AjaxResult insertProject( MultipartFile[] file, String params)
    {
        BaseProject project = JSON.parseObject(params, BaseProject.class);
        project.setCreateBy(SecurityUtils.getUsername());
        project.setContactInformation(Sm4Utils.encode(project.getContactInformation()));
        int pro = projectMapper.insertProject(project);
        String delFileId = null;
        try{
            if(pro > SystemGlobal.SUCCESS_MIN_NUM && file!=null){
                R result = remoteFileService.mostUploadFile(file, SecurityConstants.INNER);
                if (result != null && result.getCode() == HttpStatus.ERROR) {
                    log.error("人员照片上传失败");
                    return AjaxResult.error();
                } else if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
                    String jsonString = JSON.toJSONString(result.getData());
                    JSONArray json = JSON.parseArray(jsonString);
                    for (int i = 0; i < json.size(); i++) {
                        JSONObject item = json.getJSONObject(i);
                        if (item != null) {
                            ResourceFileVo fileVo = setResourceFileData(item, project);
                            resourceFileMapper.addFile(fileVo);
                            delFileId =  item.getString("fileId");
                        }
                    }
                }
        }
        }catch (Exception e) {
            log.error("新增项目", e);
            // 添加失败-删除文件
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(delFileId)) {
                remoteFileService.delFile(delFileId, SecurityConstants.INNER);
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 修改保存项目信息
     * @param file
     * @param params
     * @return
     */
    @Override
    public AjaxResult updateProject( MultipartFile[] file, String params,String[] delFileIdList)
    {
        BaseProject project = JSON.parseObject(params, BaseProject.class);
        project.setUpdateBy(SecurityUtils.getUsername());
        project.setContactInformation(Sm4Utils.encode(project.getContactInformation()));
        int pro = projectMapper.updateProject(project);
//        List<String> fileList =   project.getDelFileIdList();
//        for (int i = 0; i < fileList.size(); i++) {
//          String filePath =   fileList.get(i);
//            projectMapper.deleteFileId(filePath);
//            remoteFileService.delFile(filePath,SecurityConstants.INNER);
//        }

        if (delFileIdList != null) {
            for (int i = 0; i < delFileIdList.length; i++) {
                String high = String.valueOf(delFileIdList[i]);
                Integer certicificateId = projectMapper.getHighId(high);
//                    if(certicificateId==null){
//                        return AjaxResult.error("被删除的高出作业证图片资源无法找到");
//                    }
                if (certicificateId != null) {
                    projectMapper.delHighFile(high, certicificateId);
                    remoteFileService.delFile(high, SecurityConstants.INNER);
                }
            }
        }

        String delFileId = null;
        try{
            if(file!=null) {
                if (pro > SystemGlobal.SUCCESS_MIN_NUM) {
                    R result = remoteFileService.mostUploadFile(file, SecurityConstants.INNER);
                    if (result != null && result.getCode() == HttpStatus.ERROR) {
                        log.error("人员照片上传失败");
                        return AjaxResult.error();
                    } else if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
                        String jsonString = JSON.toJSONString(result.getData());
                        JSONArray json = JSON.parseArray(jsonString);
                        for (int i = 0; i < json.size(); i++) {
                            JSONObject item = json.getJSONObject(i);
                            if (item != null) {
                                ResourceFileVo fileVo = setResourceFileData(item, project);
                                resourceFileMapper.addFile(fileVo);
                                delFileId = item.getString("fileId");
                            }
                        }
                    }
                }
            }
        }catch (Exception e) {
            log.error("修改项目", e);
            // 添加失败-删除文件
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(delFileId)) {
                remoteFileService.delFile(delFileId, SecurityConstants.INNER);
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除项目信息
     *
     * @param projectIds 需要删除的项目ID
     * @return 结果
     */
    @Override
    public int deleteProjectByIds(int[] projectIds)
    {
        int num = 0;
        for (int i = 0; i < projectIds.length; i++) {
          int a =  projectMapper.deleteProjectByIds(projectIds[i]);
          projectMapper.deleteFile(projectIds[i]);
          List<String> list = projectMapper.selectFilePathById(projectIds[i]);
          for(int j = 0;j<list.size();j++){
              remoteFileService.delFile(list.get(j),SecurityConstants.INNER);
          }
          num = num + a;
        }
        return num;
    }

    /**
     * 资源文件赋值
     *
     * @param item
     * @return ResourceFileVo
     * @author cwchen
     * @date 2024/7/16 13:49
     */
    public ResourceFileVo setResourceFileData(JSONObject item, BaseProject 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.getProjectId() + "");
        fileVo.setSourceType("5");
        return fileVo;
    }

    /**
     * 图片查询
     * @param list
     * @return
     */
    public void  getImageFile(List<ResourceFileVo> list) {
        if(StringUtils.isNotEmpty(list)){
            list.forEach(file->{
                R<SysFile> result = remoteFileService.getImgBase64(file.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");
                    file.setBast64Image(base64);
                }
            });
        }

    }
}
