package com.unis.module.coding.service.crkxx;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yitter.idgen.YitIdHelper;
import com.unis.framework.common.util.collection.CollectionUtils;
import com.unis.module.coding.dal.dataobject.hwk.HwkDO;
import com.unis.module.coding.dal.mysql.hwk.HwkMapper;
import com.unis.module.infra.dal.dataobject.file.FileDO;
import com.unis.module.infra.service.file.FileService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import com.unis.module.coding.controller.admin.crkxx.vo.*;
import com.unis.module.coding.dal.dataobject.crkxx.CrkxxDO;
import com.unis.framework.common.pojo.PageResult;
import com.unis.framework.common.util.object.BeanUtils;

import com.unis.module.coding.dal.mysql.crkxx.CrkxxMapper;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.unis.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.unis.module.core.enums.ErrorCodeConstants.CRKXX_NOT_EXISTS;

/**
 * 出入库信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class CrkxxServiceImpl implements CrkxxService {

    @Resource
    private CrkxxMapper crkxxMapper;
    @Resource
    private HwkMapper hwkMapper;
    @Resource
    private FileService fileService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createCrkxx(CrkxxSaveReqVO createReqVO) {
        List<Long> ids = new ArrayList<>();
        if (createReqVO.getFileIds() != null && createReqVO.getFileIds().size() > 0) {
            //files 图片处理
            List<Map> fileIds = createReqVO.getFileIds();
            //图片的集合
            fileIds.forEach(files -> {
                Integer fileId = (Integer) files.get("id");
                ids.add(fileId.longValue());

            });
        }

        CrkxxDO crkxx = BeanUtils.toBean(createReqVO, CrkxxDO.class);
        // 插入前查询一下是否有hwkId
        List<HwkDO> hwks = hwkMapper.selectList(new QueryWrapper<HwkDO>().eq("CF_ID", createReqVO.getCfId()));
        if (CollectionUtil.isNotEmpty(hwks)) {
            //将已经存在的货位卡id放进去
            crkxx.setHwkId(hwks.get(0).getId());
        }
        crkxx.setId(YitIdHelper.nextId());
        crkxx.setDeleted(false);

        crkxx.setFileIds(ids.toString().replaceFirst("^\"", "").replaceAll("\"$", ""));
        crkxxMapper.insert(crkxx);
        // 返回
        return crkxx.getId();
    }

    @Override
    public void updateCrkxx(CrkxxSaveReqVO updateReqVO) {


        // 校验存在
        validateCrkxxExists(updateReqVO.getId());
        // 更新
        CrkxxDO crkxx = BeanUtils.toBean(updateReqVO, CrkxxDO.class);
        List<Long> ids = CollectionUtils.getLongs(updateReqVO.getFileIds());
        crkxx.setFileIds(ids.toString().replaceFirst("^\"", "").replaceAll("\"$", ""));

        crkxxMapper.updateById(crkxx);
    }

    @Override
    public void deleteCrkxx(Long id) {
        // 校验存在
        validateCrkxxExists(id);
        // 删除
        crkxxMapper.deleteById(id);
    }

    private void validateCrkxxExists(Long id) {
        if (crkxxMapper.selectById(id) == null) {
            throw exception(CRKXX_NOT_EXISTS);
        }
    }

    @Override
    public CrkxxDO getCrkxx(Long id) {

        return crkxxMapper.selectById(id);
    }

    @Override
    public PageResult<CrkxxDO> getCrkxxPage(CrkxxPageReqVO pageReqVO) {
        return crkxxMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<CrkxxRespVO> getCrkxxPageFiles(CrkxxPageReqVO pageReqVO) {
        PageResult<CrkxxDO> crkxxDOPageResult = crkxxMapper.selectPage(pageReqVO);
        PageResult<CrkxxRespVO> crkxxRespVOPageResult = new PageResult<>();
        List<CrkxxRespVO> crkxxRespVOList = new ArrayList<>();
        crkxxRespVOPageResult.setTotal(crkxxDOPageResult.getTotal());
        //处理文件问题
        crkxxDOPageResult.getList().forEach(dos -> {
            //获取文件id
            String fileIds = dos.getFileIds();
            List<Long> longList = new ArrayList<>();
            if(ObjectUtil.isNotEmpty(fileIds)){
                fileIds = fileIds.replaceAll(Pattern.quote("["), "").replaceAll(Pattern.quote("]"), "");
                String[] parts = fileIds.split(",");
                for (String part : parts) {
                    try {
                        longList.add(Long.parseLong(part.trim()));
                    } catch (NumberFormatException e) {
                        System.err.println("无法将 " + part + " 转换为 Long 类型: " + e.getMessage());
                    }
                }
            }
            List<FileDO> files = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(longList)) {
                files = fileService.getFiles(longList);
            }
            //循环获取文件信息

            CrkxxRespVO respVO = BeanUtils.toBean(dos, CrkxxRespVO.class);
            respVO.setFileIds(files);
            crkxxRespVOList.add(respVO);
        });

        crkxxRespVOPageResult.setList(crkxxRespVOList);
        return crkxxRespVOPageResult;
    }

    @Override
    public CrkxxRespVO getCrkxxFiles(CrkxxDO dos) {
        //获取文件id
        String fileIds = dos.getFileIds();

        List<Long> longList = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(fileIds)){
            fileIds = fileIds.replaceAll(Pattern.quote("["), "").replaceAll(Pattern.quote("]"), "");
            String[] parts = fileIds.split(",");
            for (String part : parts) {
                try {
                    longList.add(Long.parseLong(part.trim()));
                } catch (NumberFormatException e) {
                    System.err.println("无法将 " + part + " 转换为 Long 类型: " + e.getMessage());
                }
            }
        }

        //循环获取文件信息
        List<FileDO> files = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(longList)) {
            files = fileService.getFiles(longList);
        }
        CrkxxRespVO respVO = BeanUtils.toBean(dos, CrkxxRespVO.class);
        respVO.setFileIds(files);
        return respVO;
    }

}