package cn.ey.biz.module.system.service.bpm;

import cn.ey.biz.common.exception.ErrorCode;
import cn.ey.biz.module.system.api.bpm.dto.*;
import cn.ey.biz.module.system.controller.bpm.task.vo.*;
import cn.ey.biz.module.system.enums.bpm.MaimDateTyepEnum;
import cn.ey.biz.module.system.service.hrm.HrmUserInfoWithService;
import cn.ey.biz.module.system.service.hrm.HrmUserInfoWithServicelmpl;
import cn.ey.biz.module.weaver.api.*;
import cn.ey.biz.module.weaver.common.RSP;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import jodd.util.StringUtil;
import jodd.util.Util;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static cn.ey.biz.common.exception.util.ServiceExceptionUtil.exception;

@Service
@Validated
public class BpmTaskServiceImpl implements BpmTaskService {

    @Resource
    SubmitRequestService submitRequestService;
    @Resource
    RejectRequestService rejectRequestService;
    @Resource
    HrmUserInfoWithService hrmUserInfoWithService;

    @Override
    public void batchApproveTask(Long userId,List<BpmTaskApproveReqVO> reqVO) {
        if(reqVO!=null &&reqVO.size()>0){
            for(BpmTaskApproveReqVO req:reqVO){
                approveTask(userId,req);
            }
        }
    }

    @Override
    public void batchRejectTask(Long userId,List<BpmTaskRejectReqVO> reqVO) {
        if(reqVO!=null &&reqVO.size()>0){
            for(BpmTaskRejectReqVO req:reqVO){
                rejectTask(userId,req);
            }
        }
    }

    /**
     * 通过任务(提供给前端)
     * @param userId 用户编号
     * @param reqVO  通过请求
     */
    @Override
    public void approveTask(Long userId, BpmTaskApproveReqVO reqVO) {
        SubmitRequestService.SubmitRequest request = new SubmitRequestService.SubmitRequest();
        request.setRequestId(reqVO.getId());
        request.setRemark(reqVO.getReason());
        request.setDetailData(reqVO.getDetailData());
        request.setMainData(JSON.toJSONString(reqVO.getVariables().get("mainData")));
        request.setOtherParams(reqVO.getOtherParams());
        RSP<SubmitRequestService.SubmitResponse> response=submitRequestService.submitRequest(request);
        if(!response.isSuccess()){
            throw exception(new ErrorCode(-1, JSON.toJSONString(response.getErrMsg())));
        }
    }

    /**
     * 不通过任务(提供给前端)
     * @param userId 用户编号
     * @param reqVO  不通过请求
     */
    @Override
    public void rejectTask(Long userId, BpmTaskRejectReqVO reqVO) {
        RejectRequestService.RejectRequest request = new RejectRequestService.RejectRequest();
        request.setRequestId(reqVO.getId());
        request.setRemark(reqVO.getReason());
        request.setOtherParams(reqVO.getOtherParams());
        RSP<RejectRequestService.RejectResponse> response=rejectRequestService.rejectRequest(request);
        if(!response.isSuccess()){
            throw exception(new ErrorCode(-1, JSON.toJSONString(response.getErrMsg())));
        }
    }

    /**
     * 通过任务(提供给系统)
     * @param userId 用户编号
     * @param reqDTO  通过请求
     */
    @Override
    public void approveTask(String userId, @Valid BpmTaskApproveDTO reqDTO) {
        SubmitRequestService.SubmitRequest request = new SubmitRequestService.SubmitRequest();
        request.setRequestId(reqDTO.getRequestId());
        request.setRemark(reqDTO.getReason());
        request.setDetailData(reqDTO.getDetailData());
        request.setRequestName(reqDTO.getName());
        request.setRemark(reqDTO.getRemark());
        //人力code转泛微id
        List<BpmProcessInstanceMainDataDTO> mainData=reqDTO.getMainData();
        manpowerAnalysis(mainData);
        request.setMainData(JSON.toJSONString(mainData));
        //附加参数
        if(StringUtil.isNotBlank(reqDTO.getSrc())){
            Map<String,String> mapOtherParams=new HashMap<>();
            mapOtherParams.put("src",String.valueOf(reqDTO.getSrc()));
            request.setOtherParams(JSON.toJSONString(mapOtherParams));
        }
        RSP<SubmitRequestService.SubmitResponse> response=submitRequestService.submitRequest(request);
        if(!response.isSuccess()){
            throw exception(new ErrorCode(-1, JSON.toJSONString(response)));
        }
    }

    /**
     * 不通过任务()(提供给系统)
     * @param userId 用户编号
     * @param reqDTO  不通过请求
     */
    @Override
    public void rejectTask(Long userId, BpmTaskRejectDTO reqDTO) {
        RejectRequestService.RejectRequest request = new RejectRequestService.RejectRequest();
        request.setRequestId(reqDTO.getId());
        request.setRemark(reqDTO.getReason());
        request.setOtherParams(reqDTO.getOtherParams());
        RSP<RejectRequestService.RejectResponse> response=rejectRequestService.rejectRequest(request);
        if(!response.isSuccess()){
            throw exception(new ErrorCode(-1, JSON.toJSONString(response.getErrMsg())));
        }
    }

    /**
     * 通过任务-指定审核人(提供给系统)
     * @param
     * @param reqDTO  通过请求
     */
    @Override
    public void approveTaskNominator( @Valid BpmTaskApproveNominatorDTO reqDTO) {
        SubmitRequestService.SubmitRequest request = new SubmitRequestService.SubmitRequest();
        request.setRequestId(reqDTO.getId());
        request.setRemark(reqDTO.getReason());
        request.setDetailData(reqDTO.getDetailData());
        if(StringUtil.isNotBlank(reqDTO.getWeaverNominatorForm()) &&  StringUtil.isNotBlank(reqDTO.getNominatorId())){
            if(reqDTO.getVariables()!=null){
                List<BpmMainDataDTO> mad= (List<BpmMainDataDTO>) reqDTO.getVariables().get("mainData");
                BpmMainDataDTO bpmMainDataDTO =new BpmMainDataDTO();
                bpmMainDataDTO.setFieldName(reqDTO.getWeaverNominatorForm());
                HrmUserInfoWithServicelmpl.Item item=hrmUserInfoWithService.getWeaverUser(reqDTO.getNominatorId());
                bpmMainDataDTO.setFieldValue(item.getId());
                mad.add(bpmMainDataDTO);
                request.setMainData(JSON.toJSONString(mad));
            }else{
                List<BpmMainDataDTO> lsit=new ArrayList<>();
                BpmMainDataDTO bpmMainDataDTO =new BpmMainDataDTO();
                bpmMainDataDTO.setFieldName(reqDTO.getWeaverNominatorForm());
                HrmUserInfoWithServicelmpl.Item item=hrmUserInfoWithService.getWeaverUser(reqDTO.getNominatorId());
                bpmMainDataDTO.setFieldValue(item.getId());
                lsit.add(bpmMainDataDTO);
                request.setMainData(JSON.toJSONString(lsit));
            }
        }
        request.setOtherParams(reqDTO.getOtherParams());
        RSP<SubmitRequestService.SubmitResponse> response=submitRequestService.submitRequest(request);
        if(!response.isSuccess()){
            throw exception(new ErrorCode(-1, JSON.toJSONString(response)));
        }
    }

    // 人力code转泛微id
    public void manpowerAnalysis(List<BpmProcessInstanceMainDataDTO> mainData){
        if(CollectionUtil.isNotEmpty(mainData)){
            for(BpmProcessInstanceMainDataDTO ma:mainData){
                if(ma.getType()!=null && ma.getType().equals(MaimDateTyepEnum.PERSON.getType())){
                    List<String> strAll=new ArrayList<>();
                    String fieldValue =ma.getFieldValue();
                    if(StringUtil.isNotBlank(fieldValue)){
                        List<String> result = Arrays.asList(fieldValue.split(","));
                        for(String st:result){
                            HrmUserInfoWithServicelmpl.Item item=hrmUserInfoWithService.getWeaverUser(st);
                            strAll.add(item.getId());
                        }
                        String  strval= strAll.stream().collect(Collectors.joining(","));
                        ma.setFieldValue(strval);
                    }
                }
            }
        }
    }

}
