//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.horizon.workflow.rest.web;

import com.horizon.common.base.Function;
import com.horizon.common.base.Objects;
import com.horizon.common.collect.Collections2;
import com.horizon.common.collect.Lists;
import com.horizon.core.HorizonCore;
import com.horizon.language.Hi18n;
import com.horizon.utils.HorizonPorps;
import com.horizon.utils.StringUtil;
import com.horizon.utils.json.JsonUtil;
import com.horizon.wf.bean.WorkParaBean;
import com.horizon.wf.core.mem.MemCacheUtil;
import com.horizon.wf.entity.db.DBLog;
import com.horizon.workflow.form.entity.FieldAuth;
import com.horizon.workflow.form.service.ISimpleFormFieldAuthService;
import com.horizon.workflow.monitor.service.IFlowLogService;
import com.horizon.workflow.rest.model.RequestParams;
import com.horizon.workflow.rest.model.ResponseResult;
import com.horizon.workflow.rest.util.RestWorkUtil;
import com.horizon.workflow.rest.web.base.RestSuperController;
import com.horizon.workflow.support.model.FlowAction;
import com.horizon.workflow.support.model.FlowForm;
import com.horizon.workflow.support.model.FlowResult;
import com.horizon.workflow.support.service.IFlowSupportService;
import com.horizon.workflow.tenant.service.ITenantGrantService;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"${url.prefix}/rest"})
public class RestFlowSupportController extends RestSuperController {
    @Autowired
    private IFlowSupportService flowSupportService;
    @Autowired
    private IFlowLogService flowLogService;
    @Autowired
    private ISimpleFormFieldAuthService simpleFormFieldAuthService;
    @Autowired
    private ITenantGrantService tenantGrantService;

    public RestFlowSupportController() {
    }

    @ResponseBody
    @RequestMapping({"/flow/support/open${url.suffix}"})
    public String open() {
        WorkParaBean workParaBean = null;
        ResponseResult result = super.getParamWithToken();
        if (!result.isSuccess()) {
            return this.renderJson(result);
        } else {
            RequestParams params = (RequestParams)result.getData();
            workParaBean = RestWorkUtil.workParaBeanSet(params);
            String workId = workParaBean.getWorkId();
            List activeInstanceIds;
            if ("true".equals(HorizonPorps.getConfig("isValidateOfTenant"))) {
                activeInstanceIds = this.findActiveInstanceIds();
                if (!activeInstanceIds.contains(workId)) {
                    boolean check = this.tenantGrantService.checkTenantWork(HorizonCore.TENANT_CODE.value(), activeInstanceIds.size());
                    if (!check) {
                        return this.renderJson(ResponseResult.failure(Hi18n.getVal("tenant-grant", "checkWork")));
                    }
                }
            }

            activeInstanceIds = null;
            FlowResult flowResult;
            if (StringUtil.hasValue(workId)) {
                flowResult = this.flowSupportService.open(workParaBean);
            } else {
                //2023-06-09 yangff add 创建流程增加变量传递
                if (null != params.get("actionData")) {
                    String actionData = JsonUtil.toJson(params.get("actionData"));
                    FlowAction flowAction = JsonUtil.fromJson(actionData, FlowAction.class);
                    if(null!=flowAction.getFlowVars()) workParaBean.setFlowVarMap(flowAction.getFlowVars());
                }
                //2023-06-09 add 创建流程增加变量传递 end
                flowResult = this.flowSupportService.create(workParaBean);
            }

            this.setFormFieldAuth(flowResult.getFlowForms());
            return this.renderJson(flowResult);
        }
    }

    @ResponseBody
    @RequestMapping({"/flow/support/action${url.suffix}"})
    public String action(HttpServletRequest request) {
        ResponseResult result = super.getParamWithToken();
        if (!result.isSuccess()) {
            return this.renderJson(result);
        } else {
            RequestParams params = (RequestParams)result.getData();
            WorkParaBean workParaBean = new WorkParaBean();
            FlowAction flowAction = RestWorkUtil.getFlowPara(params, workParaBean);
            String data = "";
            if (flowAction != null) {
                if (!Objects.equal("close", flowAction.getOperate())) {
                    RestWorkUtil.setMessageType(workParaBean, flowAction.getMessageType());
                    RestWorkUtil.setFormData(request, workParaBean);
                    data = this.flowSupportService.operate(workParaBean, flowAction);
                } else if (Objects.equal(flowAction.getReOpen(), "false")) {
                    this.flowSupportService.close(flowAction.getWorkId(), flowAction.getTrackId(), workParaBean.getUserId());
                    flowAction.setOperateStatus("success");
                    data = flowAction.toString();
                }
            }

            return data;
        }
    }

    @ResponseBody
    @RequestMapping({"/flow/support/history${url.suffix}"})
    public String history() {
        ResponseResult result = super.getParamWithToken();
        if (!result.isSuccess()) {
            return this.renderJson(result);
        } else {
            RequestParams params = (RequestParams)result.getData();
            String workId = (String)params.get("workId");
            List<DBLog> flowLogs = this.flowLogService.findFlowLogById(workId);
            ResponseResult responseResult = ResponseResult.success().data(flowLogs).recordsTotal(flowLogs.size() + "");
            return super.skipFieldsToJson(responseResult, params);
        }
    }

    protected void setFormFieldAuth(List<FlowForm> forms) {
        if (forms != null && !forms.isEmpty()) {
            Iterator var2 = forms.iterator();

            while(var2.hasNext()) {
                FlowForm flowForm = (FlowForm)var2.next();
                String formId = flowForm.getFormId();
                if (!"FlowTrack".equals(formId)) {
                    String authId = flowForm.getFormAuthId();
                    if (!"allreadonly".equals(authId) && !"alleditable".equals(authId)) {
                        FieldAuth fieldAuth = this.simpleFormFieldAuthService.getFieldAuth(authId);
                        flowForm.setFormFieldAuth(fieldAuth);
                    }
                }
            }
        }

    }

    private List<String> findActiveInstanceIds() {
        List<Map<String, Object>> instanceLst = MemCacheUtil.getInstanceLstFromMemory(HorizonCore.TENANT_CODE.value());
        if (instanceLst == null && instanceLst.isEmpty()) {
            return Lists.newArrayList();
        } else {
            Collection<String> instanceIds = Collections2.transform(instanceLst, new Function<Map<String, Object>, String>() {
                public String apply(Map<String, Object> instance) {
                    return (String)instance.get("workid");
                }
            });
            return Lists.newArrayList(instanceIds.iterator());
        }
    }
}
