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


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.object.BeanUtils;
import com.unis.module.coding.controller.admin.lqjcxx.vo.LqjcxxPageReqVO;
import com.unis.module.coding.controller.admin.lqjcxx.vo.LqjcxxRespVO;
import com.unis.module.coding.controller.admin.lqjcxx.vo.LqjcxxSaveReqVO;
import com.unis.module.coding.dal.dataobject.hwk.HwkDO;
import com.unis.module.coding.dal.dataobject.lqjcxx.LqjcxxDO;
import com.unis.module.coding.dal.mysql.hwk.HwkMapper;
import com.unis.module.coding.dal.mysql.lqjcxx.LqjcxxMapper;
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.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;

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

/**
 * 粮情检测信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class LqjcxxServiceImpl implements LqjcxxService {

    @Resource
    private LqjcxxMapper lqjcxxMapper;
    @Resource
    private HwkMapper hwkMapper;
    @Resource
    private FileService fileService;


    @Override
    public Long createLqjcxx(LqjcxxSaveReqVO createReqVO) {
        List<Long> ids = com.unis.framework.common.util.collection.CollectionUtils.getLongs(createReqVO.getFileIds());

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

        // 返回
        return lqjcxx.getId();
    }

    @Override
    public void updateLqjcxx(LqjcxxSaveReqVO updateReqVO) {
        // 校验存在
        validateLqjcxxExists(updateReqVO.getId());
        // 更新
        LqjcxxDO updateObj = BeanUtils.toBean(updateReqVO, LqjcxxDO.class);
        List<Long> ids = com.unis.framework.common.util.collection.CollectionUtils.getLongs(updateReqVO.getFileIds());
        updateObj.setFileIds(ids.toString().replaceFirst("^\"", "").replaceAll("\"$", ""));
        lqjcxxMapper.updateById(updateObj);
    }

    @Override
    public void deleteLqjcxx(Long id) {
        // 校验存在
        validateLqjcxxExists(id);
        // 删除
        lqjcxxMapper.deleteById(id);
    }

    private void validateLqjcxxExists(Long id) {
        if (lqjcxxMapper.selectById(id) == null) {
            throw exception(LQJCXX_NOT_EXISTS);
        }
    }

    @Override
    public LqjcxxDO getLqjcxx(Long id) {
        return lqjcxxMapper.selectById(id);
    }

    @Override
    public PageResult<LqjcxxDO> getLqjcxxPage(LqjcxxPageReqVO pageReqVO) {
        return lqjcxxMapper.selectPage(pageReqVO);
    }

    @Override
    public LqjcxxRespVO getLqjcxxByCfId(Long cfId) {
        List<LqjcxxDO> cf_id = lqjcxxMapper.selectList(new QueryWrapper<LqjcxxDO>().eq("CF_ID", cfId));
        LqjcxxDO lqjcxxDO = null;
        if (!CollectionUtils.isEmpty(cf_id)) {
            lqjcxxDO = cf_id.get(0);
        }
        if (lqjcxxDO == null) {
            return null;
        }
        //获取文件id
        String fileIds = lqjcxxDO.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);
        }
        LqjcxxRespVO lqjcxxRespVO = BeanUtils.toBean(lqjcxxDO, LqjcxxRespVO.class);
        lqjcxxRespVO.setFileIds(files);

        return lqjcxxRespVO;
    }

    @Override
    public LqjcxxRespVO getLqjcxxFiles(Long id) {
        LqjcxxDO lqjcxxDO = lqjcxxMapper.selectById(id);
        //获取文件id
        String fileIds = lqjcxxDO.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);
        }
        LqjcxxRespVO lqjcxxRespVO = BeanUtils.toBean(lqjcxxDO, LqjcxxRespVO.class);
        lqjcxxRespVO.setFileIds(files);
        return lqjcxxRespVO;
    }

}