package org.springblade.flow.engine.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springblade.common.constant.MonitorConstants;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.flow.engine.constant.BondApplyConstant;
import org.springblade.modules.apply.operationSiteApply.pojo.entity.OperationSiteApplyEntity;
import org.springblade.modules.apply.operationSiteApply.service.impl.OperationSiteApplyServiceImpl;
import org.springblade.modules.flowable.examineInfo.service.impl.ExamineInfoServiceImpl;
import org.springblade.modules.flowable.processForm.utils.FormUtils;
import org.springblade.modules.nh.pojo.entity.AlarmInfoEntity;
import org.springblade.modules.operation.service.impl.OperationSiteServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ApplicationDetailService {

	@Autowired
	private ExamineInfoServiceImpl examineInfoService;

	@Autowired
	OperationSiteServiceImpl siteService;

	@Autowired
	OperationSiteApplyServiceImpl siteApplyService;
	@Autowired
	public TaskService taskService;

	@Autowired
	private RuntimeService runtimeService;


	public void createTaskChangeTaskName(String applicationId,String formId,String taskName,String userId,String processInstanceId){
		log.info(">>>>>>>>>>>>>>>>>createTaskChangeTaskName>>>>formId:{},applicationId:{},taskName{}",formId,applicationId,taskName);
		try{
			log.info(">>>>>>>>>>>>>>>>>createTaskChangeTaskName");
			if(FormUtils.AGENT_ADMISSION_APPLICATION.equals(formId)){   //运维商准入申请
				OperationSiteApplyEntity apply = siteApplyService.getById(applicationId);
				if(apply!=null){
					apply.setTaskName(taskName);
					apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
					siteApplyService.updateById(apply);
				}
			}
		}catch (Exception e){
			log.error(">>>>>>>>>>>审核通过 后执行错误 editApplyStatus  Exeception:{}",e);
			e.printStackTrace();
		}
	}

	//驳回到提交节点
	@Transactional(rollbackFor = Exception.class)
	public void editApplyStatus(String processInstanceId){
		String applicationId = (String)runtimeService.getVariable(processInstanceId, "applicationId");
		Object formId = runtimeService.getVariable(processInstanceId, "formId");
		log.info("editApplyStatus-----{applicationId}:----- "+applicationId+"---------{formId}-----------"+formId);

			if(FormUtils.AGENT_ADMISSION_APPLICATION.equals(formId)){   //代理商准入申请
				LambdaUpdateWrapper<OperationSiteApplyEntity> updateWrapper = new LambdaUpdateWrapper<>();
				updateWrapper.eq(OperationSiteApplyEntity::getId, applicationId)
					.eq(OperationSiteApplyEntity::getStatus, BondApplyConstant.APPLYSTATUS_ONE)
					.set(OperationSiteApplyEntity::getStatus, BondApplyConstant.APPLYSTATUS_TWO)
					.set(OperationSiteApplyEntity::getTaskName,"审核不通过");
				if(!siteApplyService.update(updateWrapper)){
					throw new ServiceException("驳回失败，更新数据错误");
				}
			}

		//Db.update(" UPDATE `crm_item_manage` SET  current_task_name=? WHERE process_instance_id=? ","驳回至提交节点",processInstanceId);
	}

	/**
	 * 现有库存量     代理商的实时库存总额   A
	 * 安装未验收    安装验收下对应电站的物料  B
	 * 并网未验收    电站并网、上传合同、合同签署、并网验收下的物料  C
	 * 未入库订单    平台端代理商订单下待审批、待匹配、待发货订单以及代理商端待收货订单的物料汇总  D
	 * 退货未入库    发起电站的退货，尚未入库的物料汇总  E
	 *
	 *
	 * 授信额增额    申请给代理商的授信额增额
	 * 授信额减额    申请给代理商的授信额减额
	 * 说明:
	 * 1、标准授信额: 保证金 *系数+增+减额
	 * 2、可授信额上限: 保证金*系数+增额+减额
	 * 3、标准授信额余额=标准授信额-A-B-D-E
	 * 4、可授信额上限余额=可授信额上限-A-B-C-D-E
	 */
	@Transactional(rollbackFor = Exception.class)
	public void endProcess(String processInstanceId){
		String applicationId = (String)runtimeService.getVariable(processInstanceId, "applicationId");
		String formId = (String)runtimeService.getVariable(processInstanceId, "formId");
		log.info("endProcess-----{applicationId}:----- "+applicationId+"---------{formId}-----------"+formId);
		BladeUser currentUser = AuthUtil.getUser();
		String userName= currentUser.getNickName();
		String ccUserId="";
		try{
			if(FormUtils.AGENT_ADMISSION_APPLICATION.equals(formId)){   //代理商准入申请
				OperationSiteApplyEntity apply = siteApplyService.getById(applicationId);
				apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
				apply.setTaskName("已完成");

				//添加site 和user 表数据
				String siteId = siteService.saveSite(apply);
				apply.setSiteId(siteId);
				//获取流程审批，最后一级的抄送人
				ccUserId=siteApplyService.getLastAuditStep(apply.getProcessDefId());
				apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);

				siteApplyService.updateById(apply);

			}

			if(StringUtil.isNotBlank(ccUserId)){
				log.info(">>>>>>>>>>>>>>>>OneTaskCompleteListener  ccUserId:{}",ccUserId);
				String[] userids = ccUserId.split(",");
				for(String id:userids){
					log.info("----oneTaskCompleteListener 抄送id:{}",id);
					Task ta = taskService.newTask();
					ta.setName("抄送");
					ta.setCategory(BondApplyConstant.TYPE_THREE);
					ta.setAssignee(id);
					ta.setFormKey(formId);
					ta.setParentTaskId(processInstanceId);
					ta.setTenantId(applicationId);
					taskService.saveTask(ta);
					Map<String,String> mapc=new HashMap<>();
					mapc.put("applicationId",applicationId);
					mapc.put("formId",formId);
					mapc.put("processInstanceId",processInstanceId);
					taskService.setVariables(ta.getId(),mapc);
				}
			}
		}catch (Exception e){
			log.error(">>>>>>>>>>>>审核通过后执行错误 endProcess  Exeception:{}",e);
			log.info(">>>>>审核通过后执行错误 endProcess  formId:{}  ; applicationId {}: ;",formId, applicationId);
			e.printStackTrace();
			throw new ServiceException("请刷新稍后再试!");
		}
		log.info(">>>>>>>>>>>>>>>>>>>>>审批完成 formId:{}",formId);
		//保存流程的过程信息
		examineInfoService.saveExamineInfo(applicationId,userName+"(审批完成)",new Date(),userName,formId);
		//Db.update("UPDATE `crm_item_manage` SET end_time=?,status='2',current_task_name='已完成' WHERE process_instance_id=? AND STATUS='1' ",date,processInstanceId);
		log.info(">>>>>>>>>>>>>>审批完成 ");
	}




}
