package org.dromara.zjk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.zjk.domain.InoutCheck;
import org.dromara.zjk.domain.bo.InoutCheckBo;
import org.dromara.zjk.domain.vo.CheckSupportVo;
import org.dromara.zjk.domain.vo.InoutCheckVo;
import org.dromara.zjk.mapper.InoutCheckMapper;
import org.dromara.zjk.service.IInoutCheckService;
import org.dromara.zjk.service.IZjkInvoiceService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ygh
 * @date 2025-07-30
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class InoutCheckServiceImpl implements IInoutCheckService {
    @Resource
    private final InoutCheckMapper baseMapper;
    @Resource
    private final IZjkInvoiceService zjkInvoiceService;


    /**
     * 查询【请填写功能名称】
     *
     * @param ID 主键
     * @return 【请填写功能名称】
     */
    @Override
    public InoutCheckVo queryById(String ID) {
        return baseMapper.selectVoById(ID);
    }

    /**
     * 分页查询【请填写功能名称】列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 【请填写功能名称】分页列表
     */
    @Override
    public TableDataInfo<InoutCheckVo> queryPageList(InoutCheckBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<InoutCheck> lqw = buildQueryWrapper(bo);
        Page<InoutCheckVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的【请填写功能名称】列表
     *
     * @param bo 查询条件
     * @return 【请填写功能名称】列表
     */
    @Override
    public List<InoutCheckVo> queryList(InoutCheckBo bo) {
        LambdaQueryWrapper<InoutCheck> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<InoutCheck> buildQueryWrapper(InoutCheckBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<InoutCheck> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getID()), InoutCheck::getID, bo.getID());
        lqw.like(StringUtils.isNotBlank(bo.getCheckNo()), InoutCheck::getCheckNo, bo.getCheckNo());
        lqw.eq(bo.getCheckRangeStart() != null, InoutCheck::getCheckRangeStart, bo.getCheckRangeStart());
        lqw.eq(bo.getCheckRangeEnd() != null, InoutCheck::getCheckRangeEnd, bo.getCheckRangeEnd());
        lqw.eq(bo.getFileId() != null, InoutCheck::getFileId, bo.getFileId());
        lqw.eq(bo.getCreateBy() != null, InoutCheck::getCreateBy, bo.getCreateBy());
        lqw.eq(bo.getCreateTime() != null, InoutCheck::getCreateTime, bo.getCreateTime());
        lqw.eq(bo.getUpdateBy() != null, InoutCheck::getUpdateBy, bo.getUpdateBy());
        lqw.eq(bo.getUpdateTime() != null, InoutCheck::getUpdateTime, bo.getUpdateTime());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(InoutCheckBo bo) {
        InoutCheck add = MapstructUtils.convert(bo, InoutCheck.class);
        add.setCheckNo(baseMapper.getCheckNo());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setID(add.getID());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(InoutCheckBo bo) {
        InoutCheck update = MapstructUtils.convert(bo, InoutCheck.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(InoutCheck entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除【请填写功能名称】信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public TableDataInfo<CheckSupportVo> checkInfoList(CheckSupportVo bo, PageQuery pageQuery) {
        Page<CheckSupportVo> result = baseMapper.selectCheckInfoList(pageQuery.build(), bo);
        List<CheckSupportVo> records = result.getRecords();
        handleInv(records);
        return TableDataInfo.build(result);
    }

    private void handleInv(List<CheckSupportVo> records) {
        records.forEach(o -> {
            // 根据 reviewSn 设置对应的中文名称
            if ("1".equals(o.getReviewSn())) {
                o.setReviewSnName("立项");
            } else if ("2".equals(o.getReviewSn())) {
                o.setReviewSnName("招标");
            } else if ("3".equals(o.getReviewSn())) {
                o.setReviewSnName("初验");
            } else if ("4".equals(o.getReviewSn())) {
                o.setReviewSnName("终验");
            } else {
                o.setReviewSnName(o.getReviewSn());
            }
            //通过项目id,项目阶段，专家id查询结算单，获取专家费用和总花费，通过结算单关联发票获取开票情况和金额
            CheckSupportVo otherInfo = zjkInvoiceService.getInvByProductInfo(o.getProductId(), o.getReviewSn(), o.getExpertId());
            if (otherInfo != null) {
                o.setInvFileId(otherInfo.getInvFileId());
                o.setInvoiceMoney(otherInfo.getInvoiceMoney());
                o.setInvStu(otherInfo.getInvStu());
                o.setExpertTypeMoneyFee(otherInfo.getExpertTypeMoneyFee());
                o.setExpertMoney(otherInfo.getExpertMoney());
                if (StringUtils.isNotBlank(otherInfo.getInvFileId())) {
                    o.setFids(otherInfo.getFids());
                    o.setInvFileName(baseMapper.getInvFileNameById(otherInfo.getInvFileId()));
                }
            }

        });
    }

    @Override
    public List<CheckSupportVo> checkInfoListToExpert(CheckSupportVo bo) {
        List<CheckSupportVo> result = baseMapper.getInfoListToExpert(bo);
        handleInv(result);
        return result;
    }

    @Override
    public List<String> downloadFpToZip(CheckSupportVo bo) {
        List<CheckSupportVo> result = baseMapper.getInfoListToExpert(bo);
        List<String> fpids = new ArrayList<>();
        result.stream().forEach(o -> {
            //通过项目id,项目阶段，专家id查询结算单，获取专家费用和总花费，通过结算单关联发票获取开票情况和金额
            CheckSupportVo otherInfo = zjkInvoiceService.getInvByProductInfo(o.getProductId(), o.getReviewSn(), o.getExpertId());
            if (!CollectionUtils.isEmpty(otherInfo.getFids())) {
                fpids.addAll(otherInfo.getFids());
            }
        });
        if (fpids.size() > 0) {
            List<Long> ids = fpids.stream().map(o -> Long.parseLong(o)).collect(Collectors.toList());
        }
        return fpids;
    }


}
