package com.zg.project.wisdom.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.zg.common.exception.ServiceException;
import com.zg.common.utils.DateUtils;
import com.zg.common.utils.SecurityUtils;
import com.zg.common.utils.StringUtils;
import com.zg.project.wisdom.domain.RkInfo;
import com.zg.project.wisdom.domain.vo.AuditSignatureReviewVO;
import com.zg.project.wisdom.domain.vo.AuditSignatureVo;
import com.zg.project.wisdom.mapper.GysJhMapper;
import com.zg.project.wisdom.mapper.RkInfoMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zg.project.wisdom.mapper.AuditSignatureMapper;
import com.zg.project.wisdom.domain.AuditSignature;
import com.zg.project.wisdom.service.IAuditSignatureService;
import org.springframework.transaction.annotation.Transactional;

import static com.zg.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 审批记录Service业务层处理
 * 
 * @author zg
 * @date 2025-07-11
 */
@Service
public class AuditSignatureServiceImpl implements IAuditSignatureService 
{
    @Autowired
    private AuditSignatureMapper auditSignatureMapper;

    @Autowired
    private RkInfoMapper rkInfoMapper;

    @Autowired
    private GysJhMapper gysJhMapper;

    /**
     * 查询审批记录
     * 
     * @param id 审批记录主键
     * @return 审批记录
     */
    @Override
    public AuditSignature selectAuditSignatureById(Long id)
    {
        return auditSignatureMapper.selectAuditSignatureById(id);
    }

    /**
     * 查询审批记录列表
     * 
     * @param auditSignature 审批记录
     * @return 审批记录
     */
    @Override
    public List<AuditSignature> selectAuditSignatureList(AuditSignature auditSignature)
    {
        return auditSignatureMapper.selectAuditSignatureList(auditSignature);
    }


    /**
     * 修改审批记录
     * 
     * @param auditSignature 审批记录
     * @return 结果
     */
    @Override
    public int updateAuditSignature(AuditSignature auditSignature)
    {
        auditSignature.setUpdateTime(DateUtils.getNowDate());
        return auditSignatureMapper.updateAuditSignature(auditSignature);
    }

    /**
     * 批量删除审批记录
     * 
     * @param ids 需要删除的审批记录主键
     * @return 结果
     */
    @Override
    public int deleteAuditSignatureByIds(Long[] ids)
    {
        return auditSignatureMapper.deleteAuditSignatureByIds(ids);
    }

    /**
     * 删除审批记录信息
     * 
     * @param id 审批记录主键
     * @return 结果
     */
    @Override
    public int deleteAuditSignatureById(Long id)
    {
        return auditSignatureMapper.deleteAuditSignatureById(id);
    }

    /**
     * 查询待审核的申请
     * @param
     * @return
     */
    @Override
    public int countPendingByUser(String approverId) {
        return auditSignatureMapper.countPendingByUser(approverId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(AuditSignature audit) {
        String userId = SecurityUtils.getUserId().toString();

        // 1. 校验记录是否存在
        AuditSignature db = auditSignatureMapper.selectAuditSignatureById(audit.getId());
        if (db == null || "1".equals(db.getIsDelete())) {
            throw new ServiceException("审核记录不存在");
        }

        // 2. 校验是否已审核
        if ("0".equals(db.getAuditResult()) || "1".equals(db.getAuditResult())) {
            throw new ServiceException("该记录已审核，不能重复操作");
        }

        // 2.1 校验审核结果是否为空
        if (StringUtils.isBlank(audit.getAuditResult())) {
            throw new ServiceException("审核结果不能为空");
        }

        // ✅ 如果是驳回，设置当前记录 is_current = 0
        if ("0".equals(audit.getAuditResult())) {
            audit.setIsCurrent("0");
        }

        // 3. 更新审核记录本身
        audit.setApproverId(userId);
        audit.setUpdateBy(userId);
        audit.setUpdateTime(DateUtils.getNowDate());
        auditSignatureMapper.updateAuditSignature(audit);

        // 4. 构建更新 rk_info 的状态记录（或删除记录）
        RkInfo rk = new RkInfo();
        rk.setUpdateBy(userId);
        rk.setUpdateTime(DateUtils.getNowDate());

        if ("0".equals(db.getBillType())) {
            rk.setBillNo(db.getBillNo()); // 入库
        } else if ("1".equals(db.getBillType())) {
            rk.setBillNoCk(db.getBillNo()); // 出库
        }

        // 5. 处理审核结果
        if ("1".equals(audit.getAuditResult())) {
            rk.setStatus("1"); // 审核通过
            if ("0".equals(db.getBillType())) {
                rk.setIsChuku("0"); // 入库：已入库
            } else if ("1".equals(db.getBillType())) {
                rk.setIsChuku("1"); // 出库：已出库
            }

            // ✅ 如果是入库且通过，更新供应计划状态
            if ("0".equals(db.getBillType())) {
                List<RkInfo> rkList = rkInfoMapper.selectRkInfoListByBillNo(audit.getBillNo());
                Set<Long> jhIdSet = rkList.stream()
                        .map(RkInfo::getGysJhId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toSet());

                for (Long jhId : jhIdSet) {
                    gysJhMapper.updateStatusById(jhId,"1");
                }
            }

            // ✅ 更新 rk_info 状态
            rkInfoMapper.updateStatusByBillNo(rk);

        } else if ("0".equals(audit.getAuditResult())) {
            rk.setStatus("2"); // 审核驳回
            rk.setIsDelete("1"); // 逻辑删除
            rk.setUpdateBy(userId);
            rk.setUpdateTime(DateUtils.getNowDate());

            // ✅ 调用统一逻辑删除方法
            if ("0".equals(db.getBillType())) {
                rk.setBillNo(db.getBillNo());
                rkInfoMapper.markDeleteByBillNo(rk);
            } else if ("1".equals(db.getBillType())) {
                rk.setBillNoCk(db.getBillNo());
                rkInfoMapper.markDeleteByBillNoCk(rk);
                // ✅ 恢复入库状态
                RkInfo revert = new RkInfo();
                revert.setBillNoCk(db.getBillNo()); // 出库单号
                revert.setStatus("1");              // 入库通过
                revert.setIsChuku("0");             // 未出库
                revert.setUpdateBy(userId);
                revert.setUpdateTime(DateUtils.getNowDate());
                rkInfoMapper.revertRkInfoStatusByBillNoCk(revert);
            }
        }
    }


    @Override
    public List<AuditSignatureReviewVO> selectAuditSignatureReviewList(AuditSignature filter) {

        // 1. 查询主记录列表（发起人签字图）
        List<AuditSignature> mainList = auditSignatureMapper.selectAuditMainList(filter);

        // ✅ 批量提取所有 billNo
        Set<String> billNoSet = mainList.stream()
                .map(AuditSignature::getBillNo)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());

        // 2. 一次性查询所有 billNo 对应的入库公共字段
        Map<String, RkInfo> rkInfoMap = new HashMap<>();
        if (!billNoSet.isEmpty()) {
            List<RkInfo> rkInfoList = rkInfoMapper.selectOneForEachBillNo(new ArrayList<>(billNoSet));
            rkInfoMap = rkInfoList.stream()
                    .collect(Collectors.toMap(
                            rk -> StringUtils.isNotBlank(rk.getBillNoCk()) ? rk.getBillNoCk() : rk.getBillNo(),
                            Function.identity(),
                            (a, b) -> a
                    ));
        }

        // 3. 构造返回结果列表
        List<AuditSignatureReviewVO> resultList = new ArrayList<>();
        for (AuditSignature main : mainList) {
            AuditSignatureReviewVO vo = new AuditSignatureReviewVO();
            BeanUtils.copyProperties(main, vo);

            // 设置入库公共字段（若存在）
            RkInfo rk = rkInfoMap.get(main.getBillNo());
            if (rk != null) {
                vo.setRkTypeName(rk.getRkTypeName());
                vo.setCangkuName(rk.getCangkuName());
                vo.setWlTypeName(rk.getWlTypeName());
                vo.setLihuoYName(rk.getLihuoYName());
                vo.setCkTypeName(rk.getCkTypeName());
                vo.setTeamName(rk.getTeamName());
                vo.setLihuoY(rk.getLihuoY());
            }

            // 查询该 billNo 下的现场照片 + 入库字段
            List<AuditSignatureVo> photoList = auditSignatureMapper.selectScenePhotosWithGoodsByBillNo(main.getBillNo());
            vo.setScenePhotos(photoList);

            resultList.add(vo);
        }

        return resultList;
    }


    @Override
    public List<AuditSignatureReviewVO> selectMySubmittedAuditList(AuditSignature filter) {
        // 查询发起人/现场拍照图中主图（image_type = 0）记录
        List<AuditSignature> mainList = auditSignatureMapper.selectAuditMainListBySubmitter(filter);

        List<AuditSignatureReviewVO> resultList = new ArrayList<>();
        for (AuditSignature main : mainList) {
            AuditSignatureReviewVO vo = new AuditSignatureReviewVO();
            BeanUtils.copyProperties(main, vo);

            // 查询现场图（包含货物信息）
            String billNo = main.getBillNo();
            List<AuditSignatureVo> scenePhotos = auditSignatureMapper.selectScenePhotosWithGoodsByBillNo(billNo);
            vo.setScenePhotos(scenePhotos);

            resultList.add(vo);
        }

        return resultList;
    }

    @Override
    public int approveAuditSignature(AuditSignature auditSignature) {
        auditSignature.setUpdateTime(DateUtils.getNowDate());
        auditSignature.setSignerRole("1"); // 审核人
        auditSignature.setIsCurrent("1");  // 当前记录
        return auditSignatureMapper.approveAuditByBillNo(auditSignature);
    }
}
