package com.yeejoin.amos.supervision.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.service.IWorkflowExcuteService;
import com.yeejoin.amos.boot.biz.common.workflow.feign.WorkflowFeignService;
import com.yeejoin.amos.supervision.business.dao.repository.IPlanAuditDao;
import com.yeejoin.amos.supervision.business.dao.repository.IPlanAuditLogDao;
import com.yeejoin.amos.supervision.business.dao.repository.IPlanDao;
import com.yeejoin.amos.supervision.business.service.intfc.IPlanAuditService;
import com.yeejoin.amos.supervision.common.enums.CheckTypeSuEnum;
import com.yeejoin.amos.supervision.common.enums.DangerCheckTypeLevelEnum;
import com.yeejoin.amos.supervision.common.enums.PlanStatusEnum;
import com.yeejoin.amos.supervision.common.enums.WorkFlowBranchEnum;
import com.yeejoin.amos.supervision.dao.entity.Plan;
import com.yeejoin.amos.supervision.dao.entity.PlanAudit;
import com.yeejoin.amos.supervision.dao.entity.PlanAuditLog;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("planAuditService")
public class PlanAuditServiceImpl implements IPlanAuditService {

    @Autowired
    private IWorkflowExcuteService workflowExcuteService;

    @Autowired
    private IPlanAuditDao planAuditDao;

    @Autowired
    private IPlanAuditLogDao planAuditLogDao;

    @Autowired
    private IPlanDao planDao;

    @Autowired
    WorkflowFeignService workflowFeignService;

    @Override
    @Transactional
    public Boolean auditWorkFlow(PlanAuditLog planAuditLog, Integer status, String condition, ReginParams reginParams) throws Exception {
        PlanAudit planAudit = planAuditDao.findByPlanId(planAuditLog.getPlanId());
        if (ObjectUtils.isNotEmpty(planAudit)) {
            String instanceId = planAudit.getProcessInstanceId();
            Map<String, Object> taskAuthMap = workflowExcuteService.checkTaskAuthMap(instanceId, reginParams);
            if (taskAuthMap != null && !taskAuthMap.isEmpty()) {
                // 获取当前计划
                Plan plan = planDao.getOne(planAuditLog.getPlanId());
                String taskId = taskAuthMap.get("taskId") == null ? null : taskAuthMap.get("taskId").toString();
                String name = taskAuthMap.get("name") == null ? null : taskAuthMap.get("name").toString();
                String roleName = reginParams.getRole().getRoleName();
                workflowExcuteService.CompleteTask(instanceId, condition, reginParams);
                ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
                String userId = reginParams.getUserModel().getUserId();
                // 更新计划状态,指定执行人
                updatePlanStatus(condition,plan,instanceId,userId);
                // 更新流水表
                planAuditLog.setPlanId(planAudit.getPlanId());
                planAuditLog.setPlanAuditId(planAudit.getId());
                planAuditLog.setExcuteUserId(personIdentity.getPersonSeq());
                planAuditLog.setExcuteUserName(personIdentity.getPersonName());
                planAuditLog.setFlowTaskId(taskId);
                planAuditLog.setFlowTaskName(name);
                planAuditLog.setFlowJson(condition);
                planAuditLog.setRoleName(roleName);
                planAuditLogDao.save(planAuditLog);
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }

    /**
     * 更新计划id
     * @param condition 同意0 不同意1
     * @param plan 当前计划对象
     */
    private void updatePlanStatus (String condition, Plan plan, String instanceId, String userId) throws Exception {
        String fail = "1";
        if (fail.equals(condition)) {
            planDao.updatePlanStatus(PlanStatusEnum.DRAFT.getValue(), plan.getId());
        } else {
            //检查级别
            DangerCheckTypeLevelEnum dangerCheckTypeLevelEnum = DangerCheckTypeLevelEnum.getEumByCode(plan.getCheckLevel());
            //检查类型
            CheckTypeSuEnum checkTypeSuEnum = CheckTypeSuEnum.getEumByCode(plan.getCheckTypeId());
            String branch = PlanServiceImpl.workFlowExcuteBranch(dangerCheckTypeLevelEnum.getCondition(), checkTypeSuEnum.getCondition());
            if (branch.equals(WorkFlowBranchEnum.DAILY.getWorkFlowBranch())) {
                if (PlanStatusEnum.EXAMINE_THREE.getValue() == plan.getStatus()) {
                    workflowExcuteService.setTaskAssign(instanceId, plan.getLeadPeopleIds());
                }
                PlanStatusEnum statusEnum = PlanStatusEnum.getEnum(plan.getStatus());
                planDao.updatePlanStatus(statusEnum != null ? statusEnum.getNextStatus() : PlanStatusEnum.DRAFT.getValue(), plan.getId());
            } else {
                if (PlanStatusEnum.EXAMINE_ONE.getValue() == plan.getStatus()) {
                    workflowExcuteService.setTaskAssign(instanceId, plan.getLeadPeopleIds());
                }
                planDao.updatePlanStatus(PlanStatusEnum.EXAMINE_FORMULATE.getValue(), plan.getId());
            }
        }
    }

    @Override
    public List<PlanAuditLog> listByPlanId(Long planId) {
        Sort.Order idOrder = new Sort.Order(Sort.Direction.ASC, "createDate");
        List<Sort.Order> orders = new ArrayList<Sort.Order>();
        orders.add(idOrder);
        Sort sort = Sort.by(orders);
        return planAuditLogDao.findAllByPlanId(planId, sort);
    }

//    @Override
//    @Transactional
//    public Boolean auditWorkFlow(PlanAuditLog planAuditLog, String condition, ReginParams reginParams) {
//        PlanAudit planAudit = planAuditDao.findByPlanId(planAuditLog.getPlanId());
//        Map<String, Object> taskAuthMap = workflowExcuteService.checkTaskAuthMap(instanceId);
//        if (taskAuthMap != null && !taskAuthMap.isEmpty()) {
//            String taskId = taskAuthMap.get("taskId").toString();
//            String name = taskAuthMap.get("name").toString();
//            if (StringUtils.isNotBlank(taskId)) {
//                String roleName = reginParams.getRole().getRoleName();
////                JSONObject taskGroupName = workflowFeignService.getTaskGroupName(taskId);
////                JSONArray taskGroupNameDetail = taskGroupName.getJSONArray("data");
//////                JSONObject taskGroupNameDetail = JSONObject.parseObject(JSONObject.toJSONString(data.get(data.size() - 2)));
////                if (!ObjectUtils.isEmpty(taskGroupNameDetail)) {
////                    String defaultExecutionRoleProcess = taskGroupNameDetail.getJSONObject(0).getString("groupId");
////                }
//                boolean b = workflowExcuteService.CompleteTask(instanceId, condition);
//                if (b) {
//                    ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
//                    workflowExcuteService.setTaskAssign(instanceId, personIdentity.getPersonSeq());
//
//                    if (ObjectUtils.isNotEmpty(planAudit)) {
//                        planAuditLog.setPlanId(planAudit.getPlanId());
//                        planAuditLog.setPlanAuditId(planAudit.getId());
//                        planAuditLog.setExcuteUserId(personIdentity.getPersonSeq());
//                        planAuditLog.setExcuteUserName(personIdentity.getPersonName());
//                        planAuditLog.setFlowTaskId(taskId);
//                        planAuditLog.setFlowTaskName(name);
//                        planAuditLog.setFlowJson(condition);
//                        planAuditLog.setRoleName(roleName);
//                        planAuditLogDao.save(planAuditLog);
//                    }
//                }
//                return b;
//            }
//        }
//        return Boolean.FALSE;
//    }
}
