package com.bonus.material.part.service.impl;

import com.bonus.common.biz.domain.BmFileInfo;
import com.bonus.common.biz.enums.PartLeaseTaskStatusEnum;
import com.bonus.common.biz.enums.PurchaseTaskStatusEnum;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.basic.mapper.BmFileInfoMapper;
import com.bonus.material.countersign.domain.SignProcessVo;
import com.bonus.material.countersign.mapper.SignProcessMapper;
import com.bonus.material.part.domain.PartLeaseDetails;
import com.bonus.material.part.domain.PartTypeCheckDetails;
import com.bonus.material.part.domain.PartTypeQueryDto;
import com.bonus.material.part.domain.vo.PartChaseVerifyVo;
import com.bonus.material.part.mapper.PartArrivedMapper;
import com.bonus.material.part.mapper.PartCheckMapper;
import com.bonus.material.part.service.IPartCheckInfoService;
import com.bonus.material.purchase.domain.PurchaseCheckDetails;
import com.bonus.material.purchase.domain.PurchaseSignRecord;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author ma_sh
 * @create 2025/2/18 17:10
 */
@Service
public class IPartCheckInfoServiceImpl implements IPartCheckInfoService {

    @Resource
    private SignProcessMapper signProcessMapper;

    @Resource
    private PartCheckMapper partCheckMapper;

    @Resource
    private PartArrivedMapper partArrivedMapper;

    @Resource
    private BmFileInfoMapper bmFileInfoMapper;

    /**
     * 配件内层批量验收API
     * @param partChaseVerifyVo
     * @return
     */
    @Override
    public AjaxResult innerVerify(PartChaseVerifyVo partChaseVerifyVo) {
        try {
            AjaxResult result = new AjaxResult();
            if (!CollectionUtils.isEmpty(partChaseVerifyVo.getPurchaseCheckDetailsList())) {
                Long loginUserDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
                if (BooleanUtils.isTrue(partChaseVerifyVo.getVerifyPass())) {
                    // 验收通过处理流程
                    for (PartTypeCheckDetails details : partChaseVerifyVo.getPurchaseCheckDetailsList()) {
                        // 前端选择验收通过操作，进入会签校验流程
                        if (null != details && null != details.getTaskId()) {
                            // 查询已进行会签的org_id集合
                            List<PurchaseSignRecord> purchaseSignRecordList = signProcessMapper.getPurchaseSignRecordByTask(details.getTaskId());
                            if (null == loginUserDeptId || 0 == loginUserDeptId) {
                                return AjaxResult.error("会签失败!，请检查用户部门信息");
                            }
                            if (CollectionUtils.isEmpty(purchaseSignRecordList)) {
                                // 如果该任务没有进行过会签，则无需校验 直接进行会签流程
                                int addPurchaseSignResult = signProcessMapper.insertPurchaseSignRecord(new PurchaseSignRecord(details.getTaskId(), SecurityUtils.getLoginUser().getUserid(), loginUserDeptId,
                                        details.getCheckResult()));
                                if (0 < addPurchaseSignResult) {
                                    return AjaxResult.success("会签成功");
                                } else {
                                    return AjaxResult.error("会签失败!，插入0条数据");
                                }
                            } else {

                                // 查询需要进行会签的org_id集合
                                List<SignProcessVo> signProcessVoList = signProcessMapper.getList(new SignProcessVo());
                                if (CollectionUtils.isEmpty(signProcessVoList)) {
                                    return AjaxResult.error("会签失败!，未查询到会签配置流程!");
                                } else {
                                    // 查询出配置需要会签的org_id集合
                                    Set<Long> configSignOrgSet = signProcessVoList.stream().map(SignProcessVo::getOrgId).collect(Collectors.toSet());
                                    // 获取已进行会签的org_id集合
                                    Set<Long> signedOrgSet = purchaseSignRecordList.stream().map(PurchaseSignRecord::getOrgId).collect(Collectors.toSet());
                                    // 移除已会签的org_id
                                    configSignOrgSet.removeAll(signedOrgSet);
                                    if (!CollectionUtils.isEmpty(configSignOrgSet)) {
                                        // 如果还有需要进行会签的数据，那么进行本次会签
                                        // 如果还有需要进行会签的数据，那么进行本次会签
                                        PurchaseSignRecord purchaseSignRecord = new PurchaseSignRecord();
                                        purchaseSignRecord.setTaskId(details.getTaskId());
                                        purchaseSignRecord.setUserId(SecurityUtils.getLoginUser().getUserid());
                                        purchaseSignRecord.setOrgId(loginUserDeptId);
                                        // 审核通过
                                        purchaseSignRecord.setAuditStatus("1");
                                        purchaseSignRecord.setCreateTime(DateUtils.getNowDate());
                                        purchaseSignRecord.setAuditRemark(details.getCheckResult());
                                        int addPurchaseSignResult = signProcessMapper.insertPurchaseSignRecord(purchaseSignRecord);
                                        if (0 < addPurchaseSignResult) {
                                            // 会签成功，对配置的流程进行处理
                                            configSignOrgSet.remove(loginUserDeptId);
                                            // 如果loginUserDeptId包含库管一班、库管二班或者库管三班的任意一个组织id，那么库管班就算审核通过
                                            if (loginUserDeptId == 106L || loginUserDeptId == 334L || loginUserDeptId == 335L) {
                                                System.out.println("ONE会签成功,放行进行验收流程!");
                                            } else {
                                                // 如果本次会签完成后还有需要进行会签的，那么本次会签完成，返回前端
                                                return AjaxResult.success("会签成功!");
                                            }
                                        } else {
                                            return AjaxResult.error("会签失败!，插入0条数据");
                                        }
                                    } else {
                                        System.out.println("TWO会签成功,已全部进行会签,放行进行验收流程!");
                                    }
                                }
                            }

                        } else {
                            return AjaxResult.error("detail数据异常,任务ID为空");
                        }
                        details.setCheckUser(SecurityUtils.getLoginUser().getUserid());
                        details.setStatus(PurchaseTaskStatusEnum.TO_STORE.getStatus());
                        result = 0 < partCheckMapper.updatePurchaseDetails4Check(details) ? AjaxResult.success("验收成功") : AjaxResult.error("details无验证信息");
                        extractedFile(details);
                    }
                } else {
                    // 验收驳回处理流程
                    for (PartTypeCheckDetails details : partChaseVerifyVo.getPurchaseCheckDetailsList()) {
                        details.setStatus(PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus());
                        int res = partCheckMapper.updatePurchaseDetails4Check(details);
                        if (res < 1) {
                            return AjaxResult.error("验收驳回失败,请联系管理员");
                        }
                        extractedFile(details);
                        PurchaseSignRecord purchaseSignRecord = new PurchaseSignRecord();
                        purchaseSignRecord.setTaskId(details.getTaskId());
                        purchaseSignRecord.setUserId(SecurityUtils.getLoginUser().getUserid());
                        purchaseSignRecord.setOrgId(loginUserDeptId);
                        // 审核驳回
                        purchaseSignRecord.setAuditStatus("2");
                        purchaseSignRecord.setCreateTime(DateUtils.getNowDate());
                        purchaseSignRecord.setAuditRemark(details.getCheckResult());
                        int addPurchaseSignResult = signProcessMapper.insertPurchaseSignRecord(purchaseSignRecord);
                        if (addPurchaseSignResult < 1) {
                            return AjaxResult.error("会签失败，purchase_audit_record表插入0条数据");
                        }
                    }
                }
                List<Long> taskIdList = partChaseVerifyVo.getPurchaseCheckDetailsList().stream().
                        map(PartTypeCheckDetails::getTaskId)
                        .distinct()
                        .collect(Collectors.toList());
                for (Long taskId : taskIdList) {
                    PartTypeQueryDto partTypeQueryDto = new PartTypeQueryDto();
                    partTypeQueryDto.setTaskId(taskId);
                    List<PartTypeCheckDetails> partTypeCheckDetailsList = partArrivedMapper.selectPartTypeCheckDetailsListByQueryDto(partTypeQueryDto);
                    // 将集合中的status取出
                    List<Integer> statusList = partTypeCheckDetailsList.stream()
                            .map(PartTypeCheckDetails::getStatus)
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(statusList)) {
                        int publishedStatus = PurchaseTaskStatusEnum.TO_CHECK.getStatus();
                        int inProgressStatus = PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus();
                        boolean notContainsNoFinished =!statusList.contains(publishedStatus);
                        boolean allReject = statusList.stream()
                                .allMatch(status -> status.equals(inProgressStatus));
                        int res = 0;
                        if (notContainsNoFinished && !allReject) {
                             res = partArrivedMapper.updateTaskStatus(taskId, PurchaseTaskStatusEnum.TO_STORE.getStatus());
                        } else if (notContainsNoFinished && allReject) {
                             res = partArrivedMapper.updateTaskStatus(taskId, PurchaseTaskStatusEnum.TO_CHECK_AFTER_REJECT.getStatus());
                        }
                        if (res < 1) {
                            return AjaxResult.error("会签驳回失败");
                        } else {
                            return AjaxResult.success("会签驳回成功");
                        }
                    }
                }
            }
            return result;
        } catch (final Exception e) {
            return AjaxResult.error("验收状态更改失败,异常报错:" + e.getMessage());
        }
    }

    /**
     * 验收文件上传
     * @param details
     */
    private void extractedFile(PartTypeCheckDetails details) {
        if (!CollectionUtils.isEmpty(details.getBmFileInfos())) {
            for (final BmFileInfo bmFileInfo : details.getBmFileInfos()) {
                if (null != bmFileInfo.getTaskType() && Objects.equals(TmTaskTypeEnum.TM_TASK_AGREEMENT_MANAGEMENT.getTaskTypeId(), bmFileInfo.getTaskType())) {
                    bmFileInfo.setTaskId(details.getTaskId());
                    bmFileInfo.setModelId(details.getId());
                    bmFileInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                    bmFileInfo.setCreateTime(DateUtils.getNowDate());
                    bmFileInfoMapper.insertBmFileInfo(bmFileInfo);
                }
            }
        }
    }
}
