package com.xdap.self_development.service.impl;

import com.definesys.mpaas.query.db.PageQueryResult;
import com.xdap.api.moudle.user.pojo.XdapUsers;
import com.xdap.self_development.common.BusinessDatabase;
import com.xdap.self_development.controller.request.EngineReviewListRequest;
import com.xdap.self_development.domain.dto.PageResultDTO;
import com.xdap.self_development.domain.enums.ParamValueVersionEnum;
import com.xdap.self_development.domain.pojo.EngineReviewListPojo;
import com.xdap.self_development.domain.pojo.ParamApprovalRecordPojo;
import com.xdap.self_development.domain.pojo.TodoTaskPojo;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.service.EngineReviewListService;
import com.xdap.self_development.service.XdapDeptUsersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 发动机审核列表服务实现类
 *
 * @version 1.0
 * @since 2025
 */
@Service
@Slf4j
public class EngineReviewListServiceImpl implements EngineReviewListService {
    @Resource
    private BusinessDatabase bd;
    @Resource
    private XdapDeptUsersService xdapDeptUsersService;

    /**
     * 根据用户ID查询发动机审核列表
     * 根据请求参数查询发动机审核列表信息
     *
     * @param engineReviewListRequest 发动机审核列表请求
     * @return 分页结果DTO
     */
    @Override
    public PageResultDTO<EngineReviewListPojo> selectEngineReviewListByUserId(EngineReviewListRequest engineReviewListRequest) {

        Integer page = engineReviewListRequest.getPage();
        Integer size = engineReviewListRequest.getSize();
        PageQueryResult<EngineReviewListPojo> engineReviewListPojoPageQueryResult = bd.getBusinessDatabase()
                .like("model_name", engineReviewListRequest.getModelName())
                .like("process_topic", engineReviewListRequest.getProcessTopic())
                .eq("status_description",  engineReviewListRequest.getStatusDescription())
                .eq("applicant", engineReviewListRequest.getApplicant())
                .eq("yc_or_oth", engineReviewListRequest.getYcOrOth())
                .orderBy("creation_date", "desc")
                .doPageQuery(page, size, EngineReviewListPojo.class);


        List<EngineReviewListPojo> engineReviewListPojos = engineReviewListPojoPageQueryResult.getResult();
        //将engineReviewListPojosID改为姓名
        ArrayList<EngineReviewListPojo> engineReviewListPojos1 = new ArrayList<>();
        for (EngineReviewListPojo engineReviewListPojo : engineReviewListPojos) {
            EngineReviewListPojo engineReviewListPojo1 = new EngineReviewListPojo();
            BeanUtils.copyProperties(engineReviewListPojo, engineReviewListPojo1);
            if (StringUtils.isNotEmpty(engineReviewListPojo.getApproverPersons())) {
                ArrayList<String> strings = new ArrayList<>();
                for (String id : Arrays.stream(engineReviewListPojo.getApproverPersons().split(",")).collect(Collectors.toList())) {
                    XdapUsers xdapUsersPojo = xdapDeptUsersService.selectUserByID(id);
                    if (ObjectUtils.isNotEmpty(xdapUsersPojo)) {
                        String username = xdapUsersPojo.getUsername();
                        strings.add(username);
                    }
                }
                engineReviewListPojo1.setApproverPersons(String.join(",", strings));
            }
            if (StringUtils.isNotEmpty(engineReviewListPojo.getApplicant())) {
                String applicantId = engineReviewListPojo.getApplicant();
                XdapUsers xdapUsersPojo = xdapDeptUsersService.selectUserByID(applicantId);
                engineReviewListPojo1.setApplicant(xdapUsersPojo.getUsername());
            }
            engineReviewListPojos1.add(engineReviewListPojo1);
        }

        PageResultDTO<EngineReviewListPojo> pageResultDTO = new PageResultDTO<>();
        pageResultDTO.setList(engineReviewListPojos1);
        pageResultDTO.setTotalCount(engineReviewListPojoPageQueryResult.getCount());
        return pageResultDTO;
    }

    /**
     * 撤回审批
     * 撤回指定ID的审批流程
     *
     * @param approvalId 审批ID
     * @return 撤回结果
     */
    //撤回审批
    @Override
    public String returnApproval(String approvalId) {
        if (StringUtils.isEmpty(approvalId)) {
            throw new CommonException("未传入审批流ID");
        }
        //如果这个审批流没有被审批过
        boolean b = true;
        List<EngineReviewListPojo> engineReviewListPojos = bd.getBusinessDatabase()
                .eq("id", approvalId)
                .doQuery(EngineReviewListPojo.class);
        if (ObjectUtils.isEmpty(engineReviewListPojos)) {
            throw new CommonException("审批流未找到");
        }
        // 获取环节
        List<ParamApprovalRecordPojo> paramApprovalRecordPojos = bd.getBusinessDatabase()
                .eq("approval_id", approvalId)
                .doQuery(ParamApprovalRecordPojo.class);
        if (paramApprovalRecordPojos.stream().anyMatch(x -> "同意".equals(x.getOperator()))) {
            b = false;
        }
        if (b) {
            // 更新审批流状态为已撤回
            bd.getBusinessDatabase()
                    .update("status_code", ParamValueVersionEnum.WITHDRAWN.getCode())
                    .update("status_description", ParamValueVersionEnum.WITHDRAWN.getDesc())
                    .update("approver_persons", "")
                    .update("last_update_date", new Date())
                    .eq("id", approvalId).doUpdate(EngineReviewListPojo.class);
            //删除审批人的待办
            bd.getBusinessDatabase()
                    .update("is_delete", 1)
                    .update("last_update_date", new Date())
                    .eq("document_no", approvalId).doUpdate(TodoTaskPojo.class);
            return "撤回成功";
        }
        return "已经进入审批无法撤回";
    }
}
