package com.chinaweal.aiccs.aiccs.revoke.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.dto.ResultMap;
import com.chinaweal.aiccs.aiccs.business.entity.dto.TaskListUnionDto;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.revoke.entity.Tsrevtasklist;
import com.chinaweal.aiccs.aiccs.revoke.mapper.TsrevtasklistMapper;
import com.chinaweal.aiccs.aiccs.revoke.service.TsrevtasklistService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.UuidUtil;
import com.chinaweal.aiccs.org.entity.TUsers;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 吊销待办 服务实现类
 * </p>
 *
 * @author Lee
 * @since 2021-03-26
 */
@Slf4j
@Service
public class TsrevtasklistServiceImpl extends BaseServiceImpl<TsrevtasklistMapper, Tsrevtasklist> implements TsrevtasklistService {

    @Autowired
    private UuidUtil uuidUtil;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private TUsersService tUsersService;

    /**
     * 启动待办
     * @param revtaskListModel 待办信息
     * @param user 当前用户
     * @param definitionName 定义名称
     * @return 启动结果
     */
    @Override
    public String startWorkFlow(Tsrevtasklist revtaskListModel, AICUser user, String definitionName) {
        //受理编号
        revtaskListModel.setAcceptno(user.getRegionID().substring(0,6) + uuidUtil.getCurAcceptNo());

        ResultMap resultMap = workFlowService.startAndClaim(user.getPrimaryKey(), null, definitionName, null);
        String workflowid = resultMap.getWorkflowid();
        revtaskListModel.setWorkflowid(workflowid);
        revtaskListModel.setLinkname(resultMap.getWorkflowName());//流程名称
        save(revtaskListModel);
        revtaskListModel = baseMapper.selectByWorkflowID(workflowid);
        return revtaskListModel.getTasklistid();
    }

    @Override
    public void updateWorkFlow(AICUser user, TSOpinion opinionModel, Tsrevtasklist taskListModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        ResultMap resultMap = workFlowService.completeTaskToOther(taskListModel.getWorkflowid(), nextNodeID, Arrays.asList(nextPerformerids));
        LocalDateTime now = LocalDateTime.now();
        if (resultMap.isEnd()) {//流程结束
            taskListModel.setBusstatus(BaseDataConstant.BUSINESS_STATUS_END);
        } else {//非结束流程
            updateTaskList(taskListModel, resultMap, nextPerformerids, nextPerformerNames);

        }
        if (opinionModel != null && opinionModel.getIsagree() != null) {//判断是否有意见
//            String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(taskListModel.getCurrentNode());
            opinionModel.setWorkflowid(taskListModel.getWorkflowid());  //与案件不同，不需使用 TSAuditing
            opinionModel.setHandlerid(user.getPrimaryKey());
            opinionModel.setHandler(user.getName());
//            opinionModel.setOpiniontype(opinionType);
            if(opinionModel.getHandledate() == null){
                opinionModel.setHandledate(now);
            }
            opinionModel.setTrialdate(now.toLocalDate());
//            opinionModel.setIsagree(form.getAuditingModel().getIsagree());
            opinionService.saveOrUpdate(opinionModel);
        }
        taskListModel.setSenderorgid(user.getOrgID());
        taskListModel.setSenderuserid(user.getPrimaryKey());
        taskListModel.setSendername(user.getName());
        taskListModel.setSendertime(now);
        updateById(taskListModel);
    }


    @Override
    public IPage<Tsrevtasklist> todoListWithBizstatu(IPage<Tsrevtasklist> page, Tsrevtasklist tsrevtasklist, Map<String, Object> customParamMap) {
        return baseMapper.todoListWithBizstatu(page,tsrevtasklist,customParamMap);
    }


    private void updateTaskList(Tsrevtasklist taskListModel, ResultMap resultMap, String[] nextPerformerids, String[] nextPerformerNames) {
        if (resultMap.getGroupid() != null) {
            taskListModel.setBusstatus(BaseDataConstant.BUSINESS_STATUS_TOSIGN);
            taskListModel.setSignuserid(null);
            taskListModel.setSignloginname(null);
            taskListModel.setSigntime(null);
            taskListModel.setAcceptgroupid(resultMap.getGroupid());
            taskListModel.setIssignon(BaseDataConstant.NO);
            taskListModel.setLauptime(resultMap.getLaupTime());
        } else {
            taskListModel.setBusstatus(BaseDataConstant.BUSINESS_STATUS_TRANSACT);
            taskListModel.setSigntime(LocalDate.now());
            taskListModel.setSignuserid(nextPerformerids[0]);
            taskListModel.setSignloginname(nextPerformerNames[0]);
            taskListModel.setIssignon(BaseDataConstant.YES);
            taskListModel.setLauptime(resultMap.getLaupTime());
        }
    }

    @Override
    public List<Tsrevtasklist> selectByBizSeqID(String bizseqid) {
        return list(new LambdaQueryWrapper<Tsrevtasklist>().eq(Tsrevtasklist::getBizseqid, bizseqid));
    }

    @Override
    public IPage<TaskListUnionDto> batchRevokeForwardTask(PageRequestDto pageRequestDto) {
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        if (customParamMap != null && customParamMap.containsKey("userName")) {
            String userName = (String) customParamMap.get("userName");
            if (StringUtils.isNotBlank(userName)) {
                TUsers tUsers = tUsersService.selectTusersByUsername(userName);
                if (tUsers == null) throw new BusinessException("用户不存在");
                return baseMapper.selectBatchRevokeTaskPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), tUsers.getUserid());
            }
        }
        return null;
    }

    @Override
    public void batchRevokeForward(String tasklistid, String userId) {
        Tsrevtasklist tsrevtasklist = this.getById(tasklistid);
        if (tsrevtasklist == null) {
            throw new BusinessException("待办不存在");
        }
        tsrevtasklist.setSignuserid(userId);
        this.updateById(tsrevtasklist);
    }

    @Override
    public void updateWorkFlowZx(AICUser user, TSOpinion opinionModel, Tsrevtasklist taskListModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        ResultMap resultMap = workFlowService.completeTaskToOther(taskListModel.getWorkflowid(), nextNodeID, Arrays.asList(nextPerformerids));
        LocalDateTime now = LocalDateTime.now();
        if (resultMap.isEnd()) {//流程结束
            taskListModel.setBusstatus(BaseDataConstant.BUSINESS_STATUS_END);
        } else {//非结束流程
            updateTaskList(taskListModel, resultMap, nextPerformerids, nextPerformerNames);

        }
        if (opinionModel != null && opinionModel.getIsagree() != null) {//判断是否有意见
//            String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(taskListModel.getCurrentNode());
            opinionModel.setWorkflowid(taskListModel.getWorkflowid());  //与案件不同，不需使用 TSAuditing
            opinionModel.setHandlerid(user.getPrimaryKey());
            opinionModel.setHandler(user.getName());
//            opinionModel.setOpiniontype(opinionType);
            if(opinionModel.getHandledate() == null){
                opinionModel.setHandledate(now);
            }
            opinionModel.setTrialdate(now.toLocalDate());
//            opinionModel.setIsagree(form.getAuditingModel().getIsagree());
            opinionService.saveOrUpdate(opinionModel);
        }
        taskListModel.setSenderorgid(user.getOrgID());
        taskListModel.setSenderuserid(user.getPrimaryKey());
        taskListModel.setSendername(user.getName());
        taskListModel.setSendertime(now);
        updateById(taskListModel);
    }
}
