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

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.pojo.PageResult;
import com.unis.framework.common.util.collection.CollectionUtils;
import com.unis.framework.common.util.object.BeanUtils;
import com.unis.framework.common.util.object.ObjectUtils;
import com.unis.module.coding.controller.admin.crkxx.vo.CrkxxRespVO;
import com.unis.module.coding.controller.admin.zjxx.vo.ZjxxPageReqVO;
import com.unis.module.coding.controller.admin.zjxx.vo.ZjxxRespVO;
import com.unis.module.coding.controller.admin.zjxx.vo.ZjxxSaveReqVO;
import com.unis.module.coding.dal.dataobject.hwk.HwkDO;
import com.unis.module.coding.dal.dataobject.zjxx.ZjxxDO;
import com.unis.module.coding.dal.mysql.hwk.HwkMapper;
import com.unis.module.coding.dal.mysql.zjxx.ZjxxMapper;
import com.unis.module.infra.dal.dataobject.file.FileDO;
import com.unis.module.infra.service.file.FileService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

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

/**
 * 质检信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class ZjxxServiceImpl implements ZjxxService {

    @Resource
    private ZjxxMapper zjxxMapper;
    @Resource
    private HwkMapper hwkMapper;
    @Resource
    private FileService fileService;

    @Override
    public Long createZjxx(ZjxxSaveReqVO createReqVO) {
        //files 图片处理
        ZjxxDO zjxx = BeanUtils.toBean(createReqVO, ZjxxDO.class);
        //图片的集合
        if (createReqVO.getFileIds() != null && createReqVO.getFileIds().size() > 0) {
            List<Long> ids = CollectionUtils.getLongs(createReqVO.getFileIds());
            zjxx.setFileIds(ids.toString().replaceFirst("^\"", "").replaceAll("\"$", ""));

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

    @Override
    public void updateZjxx(ZjxxSaveReqVO updateReqVO) {
        // 校验存在
        validateZjxxExists(updateReqVO.getId());
        List<Long> ids = CollectionUtils.getLongs(updateReqVO.getFileIds());
        // 更新
        ZjxxDO zjxx = BeanUtils.toBean(updateReqVO, ZjxxDO.class);
        zjxx.setFileIds(ids.toString().replaceFirst("^\"", "").replaceAll("\"$", ""));
        zjxxMapper.updateById(zjxx);
    }

    @Override
    public void deleteZjxx(Long id) {
        // 校验存在
        validateZjxxExists(id);
        // 删除
        zjxxMapper.deleteById(id);
    }

    private void validateZjxxExists(Long id) {
        if (zjxxMapper.selectById(id) == null) {
            throw exception(ZJXX_NOT_EXISTS);
        }
    }

    @Override
    public ZjxxDO getZjxx(Long id) {
        return zjxxMapper.selectById(id);
    }

    @Override
    public PageResult<ZjxxDO> getZjxxPage(ZjxxPageReqVO pageReqVO) {
        return zjxxMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<ZjxxRespVO> getZjxxPageFiles(ZjxxPageReqVO pageReqVO) {
        PageResult<ZjxxDO> zjxxDOPageResult = zjxxMapper.selectPage(pageReqVO);
        PageResult<ZjxxRespVO> zjxxRespVOPageResult = new PageResult<>();
        List<ZjxxRespVO> zjxxRespVOList = new ArrayList<>();
        zjxxRespVOPageResult.setTotal(zjxxDOPageResult.getTotal());
        //处理文件问题
        zjxxDOPageResult.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);
            }
            //循环获取文件信息
            ZjxxRespVO respVO = BeanUtils.toBean(dos, ZjxxRespVO.class);
            respVO.setFileIds(files);
            zjxxRespVOList.add(respVO);
        });

        zjxxRespVOPageResult.setList(zjxxRespVOList);
        return zjxxRespVOPageResult;
    }

}