package com.jeeplus.pubmodules.workCollectAccessory.service;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.pubmodules.workCollectAccessory.domain.WorkCollectAccessory;
import com.jeeplus.pubmodules.workCollectAccessory.mapper.WorkCollectAccessoryMapper;
import com.jeeplus.pubmodules.workCollectAccessory.service.dto.DictType;
import com.jeeplus.pubmodules.workCollectAccessory.service.dto.DictValue;
import com.jeeplus.pubmodules.workCollectAccessory.service.dto.DictValueDTO;
import com.jeeplus.pubmodules.workCollectAccessory.service.dto.WorkCollectAccessoryDTO;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.*;

/**
 * @Author hgc
 * @Date 2024/12/16/16:21
 * @ClassName WorkCollectAccessoryService
 * @Description
 */
@Service
public class WorkCollectAccessoryService {
    @Autowired
    private WorkCollectAccessoryMapper workCollectAccessoryMapper;

    /**
     * 资料库列表
     * @param workCollectAccessory
     * @param page
     * @return
     */
    public IPage<WorkCollectAccessory> findPageList(WorkCollectAccessory workCollectAccessory, Page<WorkCollectAccessory> page) throws Exception {
        QueryWrapper<WorkCollectAccessory> workCollectAccessoryMapperQueryWrapper = QueryWrapperGenerator.buildQueryCondition(workCollectAccessory, WorkCollectAccessory.class);
        // 确保 del_flag = 0 条件正确应用
        workCollectAccessoryMapperQueryWrapper.eq("a.del_flag", 0);
        // 附件名称
        if (StringUtils.isNotBlank(workCollectAccessory.getFileName())) {
            workCollectAccessoryMapperQueryWrapper.like("a.file_name", workCollectAccessory.getFileName());
        }
        // 上传人
        if (StringUtils.isNotBlank(workCollectAccessory.getUserName())) {
            workCollectAccessoryMapperQueryWrapper
                    .like("b.name", workCollectAccessory.getUserName()); // 使用 b.name 作为条件
        }
        // 收藏分类
        if (StringUtils.isNotBlank(workCollectAccessory.getClassification())) {
            workCollectAccessoryMapperQueryWrapper
                    .eq("a.classification", workCollectAccessory.getClassification()); // 使用 b.name 作为条件
        }
        // 公司
        if (StringUtils.isNotBlank(workCollectAccessory.getCompanyId())) {
            workCollectAccessoryMapperQueryWrapper.eq("a.company_id", workCollectAccessory.getCompanyId());
        }
        // 部门
        if (StringUtils.isNotBlank(workCollectAccessory.getOfficeId())) {
            workCollectAccessoryMapperQueryWrapper.eq("a.office_id", workCollectAccessory.getOfficeId());
        }
        if (StringUtils.isNotBlank(workCollectAccessory.getCreateById())) {
            // 明确查询条件的优先级
            workCollectAccessoryMapperQueryWrapper
                    .and(wrapper -> wrapper
                            .and(innerWrapper -> innerWrapper
                                    .eq("a.create_by_id", workCollectAccessory.getCreateById())
                                    .ne("a.collect_type", 1)) // 在 create_by_id 条件中添加 collect_type != 1
                            .or().eq("a.collect_user_id", workCollectAccessory.getCreateById())); // collect_user_id 条件单独处理
        }

        IPage<WorkCollectAccessory> iPage = workCollectAccessoryMapper.findPageList(page, workCollectAccessoryMapperQueryWrapper);

        return iPage;
    }

    /**
     * 收藏附件
     * @return
     */
    public void collectionAttachment(String userId,String attachmentId )  {
//        查询已存在的文件
        WorkCollectAccessory attachment = workCollectAccessoryMapper.selectById(attachmentId);
//
        WorkCollectAccessory workCollectAccessory = new WorkCollectAccessory();
        BeanUtils.copyProperties(attachment,workCollectAccessory);
        workCollectAccessory.setId("");
        workCollectAccessory.setCompanyId(null);
        workCollectAccessory.setOfficeId(null);
        workCollectAccessory.setCollectType("1");
        workCollectAccessory.setCollectUserId(userId);
        workCollectAccessory.setCreateTime(new Date());
//        String classification = workCollectAccessory.getClassification();
//        if(StringUtils.isNotEmpty(classification)){
//            List<DictValue> dictList = getDictValueByName("classification");
//            boolean containsValue = false;
//            for (DictValue dictValue : dictList) {
//                if (dictValue.getValue().equals(workCollectAccessory.getClassification())) {
//                    containsValue = true;
//                    break; // 一旦找到匹配值，退出循环
//                }
//            }
//            if(!containsValue){
//                DictType dictType = getDictByName("classification");
//                DictValueDTO dictValue = new DictValueDTO();
//                dictValue.setDictTypeId(dictType.getId());
//                dictValue.setValue(classification);
//                dictValue.setLabel(classification);
//                dictValue.setSort(generateRandomString());
//                dictValue.setId(generateId());
//                dictValue.setCreateById(userId);
//                dictValue.setCreateTime(new Date());
//                dictValue.setUpdateById(userId);
//                dictValue.setUpdateTime(new Date());
//                dictValue.setDelFlag(0);
//                dictValue.setTenantId("10000");
//                workCollectAccessoryMapper.insertDictValue(dictValue);
//            }
//        }

        workCollectAccessoryMapper.insert(workCollectAccessory);
    }

    /**
     * 共享附件
     * @return
     */
    public void shareAttachment(String userId,String attachmentId,String shareType ,String companyId)  {
        WorkCollectAccessory newAttachment = new WorkCollectAccessory();
        newAttachment.setId(attachmentId);
//        判断并设置共享状态
        if(StringUtils.isNotEmpty(companyId)){
            if("1".equals(shareType)){
                newAttachment.setOfficeId(companyId);
                newAttachment.setOfficeShare("1");
            }else{
                newAttachment.setCompanyId(companyId);
                newAttachment.setCompanyShare("1");
            }
        }else{
            if("1".equals(shareType)){
                newAttachment.setOfficeId(companyId);
                newAttachment.setOfficeShare("0");
            }else{
                newAttachment.setCompanyId(companyId);
                newAttachment.setCompanyShare("0");
            }
        }

        //更新当前用户的共享状态
        workCollectAccessoryMapper.updateById(newAttachment);
    }

    /**
     * 删除附件
     * @return
     */
    public void delAttachment(String attachmentId )  {
        workCollectAccessoryMapper.deleteById(attachmentId);
    }


    /**
     * 上传附件
     * @return
     */
    public void saveForm(WorkCollectAccessoryDTO workCollectAccessoryDTO)  {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            String id = generateId();
            List<WorkAttachmentInfo> workAttachments = workCollectAccessoryDTO.getWorkAttachments();
            // 保存附件
            if (workAttachments != null && !workAttachments.isEmpty()) {
                saveFiles(workAttachments, userDTO, id);
            }
            WorkCollectAccessory workCollectAccessory = new WorkCollectAccessory();
            WorkAttachmentInfo firstAttachment = workAttachments.get(0);
            workCollectAccessory.setId(id);
            workCollectAccessory.setFileDescription(workCollectAccessoryDTO.getFileDescription());
//            String classification = workCollectAccessoryDTO.getClassification();
//            if(StringUtils.isNotEmpty(classification)){
//                workCollectAccessory.setClassification(classification);
//                List<DictValue> dictList = getDictValueByName("classification");
//                boolean containsValue = false;
//                for (DictValue dictValue : dictList) {
//                    if (dictValue.getValue().equals(workCollectAccessory.getClassification()) && userDTO.getId().equals(dictValue.getCreateById()) ) {
//                        containsValue = true;
//                        break; // 一旦找到匹配值，退出循环
//                    }
//                }
//                if(!containsValue){
//                    DictType dictType = getDictByName("classification");
//                    DictValueDTO dictValue = new DictValueDTO();
//                    dictValue.setDictTypeId(dictType.getId());
//                    dictValue.setValue(classification);
//                    dictValue.setLabel(classification);
//                    dictValue.setSort(generateRandomString());
//                    dictValue.setId(generateId());
//                    dictValue.setCreateById(userDTO.getId());
//                    dictValue.setCreateTime(new Date());
//                    dictValue.setUpdateById(userDTO.getId());
//                    dictValue.setUpdateTime(new Date());
//                    dictValue.setDelFlag(0);
//                    dictValue.setTenantId("10000");
//                    workCollectAccessoryMapper.insertDictValue(dictValue);
//                }
//            }
            workCollectAccessory.setClassification(workCollectAccessoryDTO.getClassification());
            workCollectAccessory.setUrl(firstAttachment.getUrl());
            workCollectAccessory.setFileName(firstAttachment.getName());
            workCollectAccessory.setType("1");
            workCollectAccessory.setCollectType("0");
            workCollectAccessory.setCollectUserId(userDTO.getId());
            workCollectAccessory.setFileSize(firstAttachment.getSize());
            workCollectAccessory.setOfficeShare("0");
            workCollectAccessory.setCompanyShare("0");
            workCollectAccessoryMapper.insert(workCollectAccessory);
    }

    /**
     * 根据id修改
     * @return
     */
    public void updateById(WorkCollectAccessory workCollectAccessory)  {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        String id = workCollectAccessory.getId();
        if(StringUtils.isNotEmpty(id)){
            workCollectAccessoryMapper.deleteAttachment(id);
            List<WorkAttachmentInfo> workAttachments = workCollectAccessory.getWorkAttachments();
            // 保存附件
            if (workAttachments != null && !workAttachments.isEmpty()) {
                saveFiles(workAttachments, userDTO, id);
            }
            WorkAttachmentInfo firstAttachment = workAttachments.get(0);
//            String classification = workCollectAccessory.getClassification();
//            if(StringUtils.isNotEmpty(classification)){
//                List<DictValue> dictList = getDictValueByName("classification");
//                boolean containsValue = false;
//                for (DictValue dictValue : dictList) {
//                    if (dictValue.getValue().equals(workCollectAccessory.getClassification()) && userDTO.getId().equals(dictValue.getCreateById())) {
//                        containsValue = true;
//                        break; // 一旦找到匹配值，退出循环
//                    }
//                }
//                if(!containsValue){
//                    DictType dictType = getDictByName("classification");
//                    DictValueDTO dictValue = new DictValueDTO();
//                    dictValue.setDictTypeId(dictType.getId());
//                    dictValue.setValue(classification);
//                    dictValue.setLabel(classification);
//                    dictValue.setSort(generateRandomString());
//                    dictValue.setId(generateId());
//                    dictValue.setCreateById(userDTO.getId());
//                    dictValue.setCreateTime(new Date());
//                    dictValue.setUpdateById(userDTO.getId());
//                    dictValue.setUpdateTime(new Date());
//                    dictValue.setDelFlag(0);
//                    dictValue.setTenantId("10000");
//                    workCollectAccessoryMapper.insertDictValue(dictValue);
//                }
//            }
            workCollectAccessory.setUrl(firstAttachment.getUrl());
            workCollectAccessory.setFileName(firstAttachment.getName());
            workCollectAccessory.setFileSize(firstAttachment.getSize());

            workCollectAccessoryMapper.updateById(workCollectAccessory);
        }
    }

    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        for (WorkAttachmentInfo dto : list) {
            WorkAttachmentInfo i = new WorkAttachmentInfo();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateTime(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateTime(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (CollectionUtils.isNotEmpty(strings)) {
                i.setType(strings.get(strings.size() - 1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("");
            i.setFileSize(dto.getSize());
            i.setSort(j);
//            ossServiceMapper.insertWorkAttachment(i, userDTO);
            Map<String,String> map = new HashMap<>();
            String workAttachment = JSON.toJSONString((i));
            String userDTOInfo = JSON.toJSONString((userDTO));
            map.put("workAttachment",workAttachment);
            map.put("userDTO",userDTOInfo);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
            j++;
        }
    }

    /**
     * 根据分类去重
     */
    public List<WorkCollectAccessory> getClassificationList(WorkCollectAccessory workCollectAccessory)  throws Exception{
        QueryWrapper<WorkCollectAccessory> workCollectAccessoryMapperQueryWrapper = QueryWrapperGenerator.buildQueryCondition(workCollectAccessory, WorkCollectAccessory.class);
        // 确保 del_flag = 0 条件正确应用
        workCollectAccessoryMapperQueryWrapper.eq("a.del_flag", 0);
        // 公司
        if (StringUtils.isNotBlank(workCollectAccessory.getCompanyId())) {
            workCollectAccessoryMapperQueryWrapper.eq("a.company_id", workCollectAccessory.getCompanyId());
        }
        // 部门
        if (StringUtils.isNotBlank(workCollectAccessory.getOfficeId())) {
            workCollectAccessoryMapperQueryWrapper.eq("a.office_id", workCollectAccessory.getOfficeId());
        }
        if (StringUtils.isNotBlank(workCollectAccessory.getCreateById())) {
            // 明确查询条件的优先级
            workCollectAccessoryMapperQueryWrapper
                    .and(wrapper -> wrapper
                            .and(innerWrapper -> innerWrapper
                                    .eq("a.create_by_id", workCollectAccessory.getCreateById())
                                    .ne("a.collect_type", 1)) // 在 create_by_id 条件中添加 collect_type != 1
                            .or().eq("a.collect_user_id", workCollectAccessory.getCreateById())); // collect_user_id 条件单独处理
        }
        return workCollectAccessoryMapper.getClassificationList(workCollectAccessoryMapperQueryWrapper);
    }


    /**
     * 根据id查询当前附件信息
     */
    public WorkCollectAccessory queryById(String id) {
        WorkCollectAccessory workCollectAccessory = workCollectAccessoryMapper.selectById(id);
        return workCollectAccessory;
    }
    /**
     * 根据字典名称获取字典值
     */
    @Transactional(rollbackFor = Exception.class)
    public DictType getDictByName(String dictName) {
        return  workCollectAccessoryMapper.getDictByName(dictName);
    }
    public List<DictValue> getDictValueByName(String dictName){
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        String userId = userDTO.getId();
        return workCollectAccessoryMapper.getDictValueByName(dictName,userId);
    }

    /**
     * 生成uuid
     * @return
     */
    public static String generateId() {
        UUID uuid = UUID.randomUUID();
        BigInteger id = new BigInteger(uuid.toString().replace("-", ""), 16);
        return id.toString();
    }

    /**
     * 随机生成
     * @return
     */
    public static String generateRandomString() {
        Random random = new Random();
        // 随机生成一个 99 到 1000 之间的整数
        int randomNumber = 99 + random.nextInt(1000 - 99);
        // 返回整数转为字符串
        return String.valueOf(randomNumber);
    }
}
