package com.huigou.topsun.base.bsnMessage.appliction.impl;


import com.huigou.cache.SystemCache;
import com.huigou.context.Operator;
import com.huigou.context.ThreadLocalUtil;
import com.huigou.topsun.base.bsnMessage.appliction.MannualStartWorkApplication;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import com.huigou.uasp.bmp.fn.CodeGenerator;
import com.huigou.uasp.bmp.operator.OperatorApplication;
import com.huigou.uasp.bpm.ProcessAction;
import com.huigou.uasp.bpm.ProcessStartModel;
import com.huigou.uasp.bpm.engine.application.WorkflowApplication;
import com.huigou.util.ClassHelper;
import com.huigou.util.Constants;
import com.huigou.util.SDO;
import com.huigou.util.StringUtil;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("mannualStartWorkApplication")
public class MannualStartWorkApplicationImpl extends BaseApplication implements MannualStartWorkApplication {

    @Autowired
    private CodeGenerator codeGenerator;
    @Autowired
    private WorkflowApplication workflowApplication;
    @Resource
    private OperatorApplication operatorApplication;

    @Override
    public String  startWorkflow(Object entity,String processDefinitionKey,String codeRule){
        Map<String, Object> map = ClassHelper.beanToMap(entity);
        return this.startWorkflow(map,processDefinitionKey,codeRule);
    }

    @Override
    @Transactional
    public String startWorkflow(Map<String, Object> map, String processDefinitionKey, String codeRule) {
        Operator operator = null;
        operator = ThreadLocalUtil.getOperator();
        if (operator == null) {
            String createdById = SystemCache.getParameter("adminPersonId", String.class);
            operator = operatorApplication.createOperatorByPersonMemberId(createdById);
            ThreadLocalUtil.putOperator(operator);
        }

        // Assert.notNull(operator, "未获取到当前操作用户，无法创建流程");
        SDO sdo = ThreadLocalUtil.getVariable(Constants.SDO, SDO.class);
        if (sdo == null) {
            sdo = new SDO();
        }
        try {
            // 业务数据
            sdo.setProperties(map);

            // 启动流程的必要参数
            sdo.putProperty("fullId", operator.getFullId());
            sdo.putProperty("organId", operator.getOrgId());
            sdo.putProperty("organName", operator.getOrgName());
            sdo.putProperty("deptId", operator.getDeptId());
            sdo.putProperty("deptName", operator.getDeptName());
            sdo.putProperty("positionId", operator.getPositionId());
            sdo.putProperty("positionName", operator.getPositionName());
            sdo.putProperty("personMemberId", operator.getPersonMemberId());
            sdo.putProperty("personMemberName", operator.getPersonMemberName());
            sdo.putProperty("processAction", ProcessAction.SAVE);
            sdo.putProperty("procUnitId", "");
            //  sdo.putProperty("bizId", purchaseOrder.getId());
            sdo.putProperty("createdDate", new Date());
            sdo.putProperty("fillinDate", new Date());
            String billCode = sdo.getString("billCode");
            if (StringUtil.isBlank(billCode)){
                String nextCode = codeGenerator.getNextCode(codeRule);

                sdo.putProperty("billCode", nextCode);
            }
            ThreadLocalUtil.putVariable(Constants.SDO, sdo);
            Map<String, Object> variables = new HashMap<>();
            variables.put("startModel", ProcessStartModel.MANUAL.getId());
            variables.put("executorFullId", operator.getFullId());
            variables.put("executorFullName", operator.getFullName());
            ThreadLocalUtil.putOperator(operator);
            ExecutionEntity pi = (ExecutionEntity) workflowApplication.startProcessInstanceByKey(processDefinitionKey, null, variables);
            // 业务参数
            TaskEntity applyTask = pi.getTasks().get(0);
            sdo.putProperty("processAction", ProcessAction.ADVANCE);
            sdo.putProperty("bizId", pi.getBusinessKey());
            sdo.putProperty("id", pi.getBusinessKey());
            sdo.putProperty("statusId", BizBillStatus.APPLYING.getId());
            ThreadLocalUtil.removeVariable("_approvalParameter_");
            ThreadLocalUtil.putVariable(Constants.SDO, sdo);
            workflowApplication.advance(applyTask.getId(), Collections.emptyMap());
            // return this.sapPurchaseRepository.findOne(pi.getBusinessKey());
            return pi.getBusinessKey();
        }catch(Exception ex){
            ex.printStackTrace();
            throw ex;
        }
    }

}
