package com.jeeplus.finance.projectDict.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.finance.fileDict.domain.ProgramFileDict;
import com.jeeplus.finance.fileDict.mapper.ProgramFileDictMapper;
import com.jeeplus.finance.projectDict.domain.ProgramProjectDict;
import com.jeeplus.finance.projectDict.domain.vo.FileDictVo;
import com.jeeplus.finance.projectDict.mapper.ProjectDictMapper;
import com.jeeplus.finance.projectDict.service.dto.ProjectDictDto;
import com.jeeplus.finance.projectReport.domain.CwProjectReport;
import com.jeeplus.finance.projectReport.domain.CwProjectReviewNew;
import com.jeeplus.finance.projectReport.mapper.CwProjectReviewNewMapper;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.sys.service.dto.WorkAttachmentInfoDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class ProjectDictService {

    @Resource
    private ProjectDictMapper projectDictMapper;

    @Resource
    private ProgramFileDictMapper programFileDictMapper;

    @Resource
    private CwProjectReviewNewMapper reviewNewMapper;

    @Value("${config.accessory.aliyun.aliyunUrl}")
    private String aliyunUrl;

    @Value("${config.accessory.aliyun.aliyunDownloadUrl}")
    private String aliyunDownloadUrl;

    @Value("${config.accessory.aliyun.endpoint}")
    private String endpoint;

    @Value("${config.accessory.aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${config.accessory.aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${config.accessory.aliyun.bucketName}")
    private String bucketName;

    /**
     * 查询
     * @param projectDictDto
     * @param id
     * @return
     */
    public List<FileDictVo> getFileDictList(ProjectDictDto projectDictDto, String projectId, String id,String type) {
        //获取当前登陆人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        List<FileDictVo> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(projectDictDto.getAttachmentProjectType())) {
            //查询父级
            List<FileDictVo> parentList = projectDictMapper.getParentList(projectDictDto.getSortList());
            for (FileDictVo fileDictVo : parentList) {
                fileDictVo.setId(fileDictVo.getFileId());
            }
            list.addAll(parentList);
            //查询子级
            List<FileDictVo> dictVos = projectDictMapper.list(projectDictDto.getAttachmentProjectType(),projectDictDto.getAttachmentProjectSort(),projectDictDto.getProjectLevel());
            list.addAll(dictVos);
        }
        List<WorkAttachmentInfoDTO> fileList = Lists.newArrayList();
        String stage="";
        //判断当前的报告复核处于哪一个节点
        CwProjectReviewNew reviewNew = reviewNewMapper.selectOne(new QueryWrapper<CwProjectReviewNew>().eq("report_id", id));
        //获取当前节点名称
        if (null != reviewNew) {
            String currentTaskName = SpringUtil.getBean(IFlowableApi.class).getCurrentTaskName(reviewNew.getProcInsId());
            if (StringUtils.isNotBlank(currentTaskName)) {
                stage= "1";
            } else {
                stage= "1";
            }
        }
        stage= "1";
        if (StringUtils.isNotBlank(type)) {
            if (type.equals("归档")) {
                stage= "2";
            }
        }




        for (FileDictVo dictVo : list) {
            if(StringUtils.isNotBlank(dictVo.getRequiredStage()) && dictVo.getRequiredStage().equals(stage)){
                dictVo.setMustFlag(1);
            }else{
                dictVo.setMustFlag(0);
            }
            if(StringUtils.isNotBlank(dictVo.getType())){
                //此处为子集菜单，需根据项目id和附件类型id查询对应附件信息
                dictVo.setLevelFlag(2);
                // 查询附件信息
                List<WorkAttachmentInfoDTO> files = projectDictMapper.getFileListByAttachmentAndModuleType(dictVo.getId(), projectId);
                if (CollectionUtils.isNotEmpty(files)) {
                    fileList.addAll(files);
                }
            }else{
                dictVo.setLevelFlag(1);
            }
        }
        //对附件进行处理
        if (CollectionUtils.isNotEmpty(fileList)) {
            for (WorkAttachmentInfoDTO workAttachmentInfoDTO : fileList) {
                FileDictVo info = new FileDictVo();
                info.setId(workAttachmentInfoDTO.getId());
                info.setParentId(workAttachmentInfoDTO.getAttachmentId());
                info.setAttachmentName(workAttachmentInfoDTO.getAttachmentName());
                info.setWorkAttachmentType(workAttachmentInfoDTO.getType());
                info.setFileSize(workAttachmentInfoDTO.getFileSize());
                info.setCreateDate(workAttachmentInfoDTO.getCreateTime());
                info.setUrl(workAttachmentInfoDTO.getUrl());
                info.setLsUrl(getFileTemporaryLookUrl(aliyunUrl + workAttachmentInfoDTO.getUrl()));
                //此处为子集菜单，需根据项目id和附件类型id查询对应附件信息
                info.setLevelFlag(3);
                list.add(info);
            }
        }


        return list;
    }

    /**
     * 查询
     * @param projectDictDto
     * @return
     */
    public List<FileDictVo> list(ProjectDictDto projectDictDto) {
        List<FileDictVo> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(projectDictDto.getAttachmentProjectType()) /*&& StringUtils.isNotEmpty(projectDictDto.getAttachmentProjectSort())*/) {
            //查询父级
            List<FileDictVo> parentList = projectDictMapper.parentList();
            list.addAll(parentList);
            //查询子级
            List<FileDictVo> dictVos = projectDictMapper.list(projectDictDto.getAttachmentProjectType(),projectDictDto.getAttachmentProjectSort(), projectDictDto.getProjectLevel());
            list.addAll(dictVos);
        }
        return list;
    }

    /**
     * 保存
     * @param projectDictDto
     * @return
     */
    public String save(ProjectDictDto projectDictDto) {
        if (StringUtils.isNotEmpty(projectDictDto.getId())) {
            return update(projectDictDto);
        } else {
            return add(projectDictDto);
        }
    }

    /**
     * 新增
     * @param projectDictDto
     * @return
     */
    public String add(ProjectDictDto projectDictDto) {
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        String id = UUID.randomUUID().toString().replace("-", "");
        ProgramProjectDict dict = new ProgramProjectDict();
        BeanUtils.copyProperties(projectDictDto, dict);
        dict.setId(id);
        dict.setCreateById(userDTO.getId());
        dict.setCreateTime(new Date());
        dict.setUpdateById(userDTO.getId());
        dict.setUpdateTime(new Date());
        dict.setDelFlag(0);
        projectDictMapper.insert(dict);
        return "操作成功";
    }

    /**
     * 修改
     * @param projectDictDto
     * @return
     */
    public String update(ProjectDictDto projectDictDto) {
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        ProgramProjectDict dict = new ProgramProjectDict();
        BeanUtils.copyProperties(projectDictDto, dict);
        dict.setUpdateById(userDTO.getId());
        dict.setUpdateTime(new Date());
        dict.setDelFlag(0);
        projectDictMapper.updateById(dict);
        return "操作成功";
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public String deleteById(String id) {
        projectDictMapper.deleteById(id);
        return "操作成功";
    }

    /**
     * 新增附件结构信息附件名称查询
     * @param projectDictDto
     * @return
     */
    public List<ProgramFileDict> getFileList(ProjectDictDto projectDictDto) {
        List<FileDictVo> list = list(projectDictDto);
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> fileIds = list.stream().map(i -> i.getFileId()).collect(Collectors.toList());
            // 根据fileId查询所属层级
            String parentId = programFileDictMapper.selectById(projectDictDto.getFileId()).getParentId();
            if (CollectionUtil.isNotEmpty(fileIds) && StringUtils.isNotEmpty(projectDictDto.getFileId()) && !"0".equals(parentId)) {
                fileIds.remove(projectDictDto.getFileId());
                return projectDictMapper.getFileList(projectDictDto.getFileId(), fileIds);
            } else {
                return projectDictMapper.getFileParentList(projectDictDto.getFileId(),  fileIds);
            }
        }
        return new ArrayList<>();
    }

    /**
     * 根据fileId查询
     * @param id
     * @return
     */
    public ProgramFileDict findByFileId(String id) {
        return projectDictMapper.findById(id);
    }

    public String getFileTemporaryLookUrl(String url){
        url = url.replace("amp;","");
        String cons = "";
        if (url.contains(aliyunUrl)){
            cons = aliyunUrl;
        }else if (url.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
            cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
        }else {
            cons = aliyunDownloadUrl;
        }
        String key = "";
        String[] split = url.split(cons + "/");
        if(split.length>1){
            key = split[1];
        }else{
            key = url;
        }
        // 指定过期时间为24小时。
        Date expiration = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 );
        //初始化OSSClient
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        return ossClient.generatePresignedUrl(bucketName, key, expiration).toString();
    }
}
