/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.policy.info.modular.auditRequest.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.policy.info.modular.alPolicyFileReport.entity.AlPolicyFileReport;
import com.unis.policy.info.modular.alPolicyFileReport.service.AlPolicyFileReportService;
import com.unis.policy.info.modular.auditRecord.entity.AuditRecord;
import com.unis.policy.info.modular.auditRecord.service.AuditRecordService;
import com.unis.policy.info.modular.auditRequest.param.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.policy.info.modular.auditRequest.entity.AuditRequest;
import com.unis.policy.info.modular.auditRequest.mapper.AuditRequestMapper;
import com.unis.policy.info.modular.auditRequest.service.AuditRequestService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 审核请求Service接口实现类
 *
 * @author TS
 * @date  2024/04/18 14:51
 **/
@Service
public class AuditRequestServiceImpl extends ServiceImpl<AuditRequestMapper, AuditRequest> implements AuditRequestService {

    @Autowired
    private AlPolicyFileReportService alPolicyFileReportService;

    @Autowired
    private AuditRecordService auditRecordService;

    @Resource
    private  AuditRequestMapper auditRequestMapper;

    @Override
    public Page<AuditRequest> page(AuditRequestPageParam auditRequestPageParam) {
        QueryWrapper<AuditRequest> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(auditRequestPageParam.getSortField(), auditRequestPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(auditRequestPageParam.getSortOrder());
            queryWrapper.orderBy(true, auditRequestPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(auditRequestPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(AuditRequest::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void audit(AuditRequestAddParam auditRequestAddParam) {
        //设置默认值
        auditRequestAddParam.setAuditStatus(1); // 审核通过，默认
        auditRequestAddParam.setType("1"); //默认值 业务类型 1：政策规范性文件申报
        AlPolicyFileReport alPolicyFileReport = alPolicyFileReportService.getById(auditRequestAddParam.getRequestId());
        if (ObjectUtil.isEmpty(alPolicyFileReport)){
            throw new CommonException("政策规范性文件申报不存在，id为{}",auditRequestAddParam.getRequestId());
        }
        //判断文件申报是否已经发起流程
        if (alPolicyFileReport.getStatus() != 1){
            throw new CommonException("政策规范性文件申报未发起流程，id为{}",auditRequestAddParam.getRequestId());
        }

        AuditRequest request = BeanUtil.toBean(auditRequestAddParam, AuditRequest.class);

        //查询审核是否已经存在
        LambdaQueryWrapper<AuditRequest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuditRequest::getType,auditRequestAddParam.getType());
        queryWrapper.eq(AuditRequest::getStep,auditRequestAddParam.getStep());
        queryWrapper.eq(AuditRequest::getRequestId,auditRequestAddParam.getRequestId());
        AuditRequest request1  = super.getOne(queryWrapper,false);
        if (request1 != null){ //表示数据已经进行审核或者驳回
            if (request1.getAuditStatus() == 1 ) { //表示是审核通过
                throw new CommonException(StringUtils.equals("1", auditRequestAddParam.getStep()) ? "已进行合法性审核" : "已进行过会审核");
            }else{ //
                request.setId(request1.getId()); //设置id进行修改操作
            }

        }
        //如果是过会审核要查询已进行合法性审核并且通过
        if (StringUtils.equals("2",auditRequestAddParam.getStep())){
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AuditRequest::getType,auditRequestAddParam.getType());
            queryWrapper.eq(AuditRequest::getStep,1); // 合法性审核
            queryWrapper.eq(AuditRequest::getRequestId,auditRequestAddParam.getRequestId());
            queryWrapper.eq(AuditRequest::getAuditStatus,1); //审核通过
            if (super.getOne(queryWrapper,false) == null){
                throw new CommonException("未进行合法性审核或合法性审核未通过");
            }
        }


        if (!this.saveOrUpdate(request)){
            throw new CommonException("保存审核请求失败");
        }
        //保存审核记录
        saveRecord(request);
    }

    private void saveRecord(AuditRequest request) {
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setAuditRequestId(request.getId());
        auditRecord.setStep(request.getStep());
        auditRecord.setType(request.getType());
        auditRecord.setRequestId(request.getRequestId()); //申请id
        auditRecord.setAuditStatus(request.getAuditStatus());
        auditRecord.setAuditAdvice(request.getAuditAdvice());
        auditRecord.setAuditUserId(request.getAuditUserId());
        auditRecord.setAuditTime(request.getAuditTime());
        auditRecord.setAttachment(request.getAttachment());
        if (!auditRecordService.save(auditRecord)){
            throw new CommonException("保存审核记录失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void reject(AuditRequestAddParam auditRequestAddParam) {
        //设置默认值
        auditRequestAddParam.setAuditStatus(2); // 审核驳回，默认
        auditRequestAddParam.setType("1"); //默认值 业务类型 1：政策规范性文件申报
        AlPolicyFileReport alPolicyFileReport = alPolicyFileReportService.getById(auditRequestAddParam.getRequestId());
        if (ObjectUtil.isEmpty(alPolicyFileReport)){
            throw new CommonException("政策规范性文件申报不存在，id为{}",auditRequestAddParam.getRequestId());
        }
        //判断文件申报是否已经发起流程
        if (alPolicyFileReport.getStatus() != 1){
            throw new CommonException("政策规范性文件申报未发起流程，id为{}",auditRequestAddParam.getRequestId());
        }

        AuditRequest request = BeanUtil.toBean(auditRequestAddParam, AuditRequest.class);

        //查询审核是否已经存在
        LambdaQueryWrapper<AuditRequest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuditRequest::getType,auditRequestAddParam.getType());
        queryWrapper.eq(AuditRequest::getStep,auditRequestAddParam.getStep());
        queryWrapper.eq(AuditRequest::getRequestId,auditRequestAddParam.getRequestId());
        AuditRequest request1  = super.getOne(queryWrapper,false);
        if (!ObjectUtil.isEmpty(request1)){ //表示数据已经进行审核或者驳回
            if (request1.getAuditStatus() == 1 ) { //表示是审核通过
                throw new CommonException(StringUtils.equals("1", auditRequestAddParam.getStep()) ? "已进行合法性审核,不能驳回" : "已进行过会审核,不能驳回");
            }else{ //
                request.setId(request1.getId()); //设置id进行修改操作
            }

        }
        AuditRequest request2 = null;
        //如果是过会审核要查询已进行合法性审核并且通过
        if (StringUtils.equals("2",auditRequestAddParam.getStep())){
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AuditRequest::getType,auditRequestAddParam.getType());
            queryWrapper.eq(AuditRequest::getRequestId,auditRequestAddParam.getRequestId());
            queryWrapper.eq(AuditRequest::getStep,1); // 合法性审核
            queryWrapper.eq(AuditRequest::getAuditStatus,1); //审核通过
            request2 = super.getOne(queryWrapper,false);
            if (ObjectUtil.isEmpty(request2)){
                throw new CommonException("未进行合法性审核或合法性审核未通过");
            }
        }
        if (!this.saveOrUpdate(request)){
            throw new CommonException("保存驳回请求失败");
        }
        //保存当前审核操作审核记录
        saveRecord(request);
        //驳回是一驳到底，需要重新启动流程
        alPolicyFileReport.setStatus(2); //状态 0：待发起；1：已发起；2：驳回；
        if(!alPolicyFileReportService.updateById(alPolicyFileReport)){
            throw new CommonException("修改政策规范性文件申报失败，id为{}",auditRequestAddParam.getRequestId());
        }
        //如果是过会审核要查询已进行合法性审核并且通过
        if (StringUtils.equals("2",auditRequestAddParam.getStep())){
            if (!ObjectUtil.isEmpty(request2)){
                //设置合法性审核为驳回状态，并保存驳回记录
                request2.setAuditStatus(2); //状态 0：待审核；1：已审核；2：驳回；
                request2.setAuditTime(request.getAuditTime());
                request2.setAuditAdvice(request.getAuditAdvice());
                request2.setAttachment(request.getAttachment());
                if (!this.saveOrUpdate(request2)){
                    throw new CommonException("保存驳回合法性请求失败");
                }
                //保存合法性驳回审核记录
                saveRecord(request2);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<AuditRequestIdParam> auditRequestIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(auditRequestIdParamList, AuditRequestIdParam::getId));
    }

    @Override
    public JSONObject detail(AuditRequestDetailParam auditRequestDetailParam) {
        JSONObject jsonObject = new JSONObject();
        AlPolicyFileReport alPolicyFileReport = alPolicyFileReportService.queryEntity(auditRequestDetailParam.getReportId());
        if(ObjectUtil.isEmpty(alPolicyFileReport)) {
            throw new CommonException("政策规范性文件申报不存在，id值为：{}", auditRequestDetailParam.getReportId());
        }
        jsonObject.put("alPolicyFileReport",alPolicyFileReport);
        if (StringUtils.isNotBlank(auditRequestDetailParam.getRequestId())){
            AuditRequest auditRequest =  this.queryEntity(auditRequestDetailParam.getRequestId());
            jsonObject.put("auditRequest",auditRequest);
        }
        //表示是过会审核，需要展示审核记录
        if (StringUtils.equals("2",auditRequestDetailParam.getType())){
            List<Map<String,Object>> records =auditRequestMapper.queryReconds(alPolicyFileReport.getId());
            jsonObject.put("records",records);
        }
        return jsonObject;
    }

    @Override
    public AuditRequest queryEntity(String id) {
        AuditRequest auditRequest = this.getById(id);
        if(ObjectUtil.isEmpty(auditRequest)) {
            throw new CommonException("审核请求不存在，id值为：{}", id);
        }
        return auditRequest;
    }
}
