package com.weaver.seconddev.meishi.esb.action;

import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.common.form.dto.data.FormDataDetailDto;
import com.weaver.common.form.dto.data.FormDataDto;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.seconddev.meishi.constant.Constants;
import com.weaver.seconddev.meishi.esb.dao.PerformanceSubmitDao;
import com.weaver.seconddev.meishi.esb.util.PerformanceSubmitUtil;
import com.weaver.teams.domain.user.SimpleEmployee;
import com.weaver.workflow.core.api.rest.flow.entity.operate.WfcRequestOperateParamDataEntity;
import com.weaver.workflow.core.api.rest.flow.entity.operate.WfcRequestOperationResultDto;
import com.weaver.workflow.core.api.rest.publicapi.WfcRequestOperateRest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("Lamex_PerformanceSubmitCreateWorkflowAction")
public class PerformanceSubmitCreateWorkflowAction implements EsbServerlessRpcRemoteInterface {

    private final static Logger log = LoggerFactory.getLogger(PerformanceSubmitCreateWorkflowAction.class);

    @Autowired
    PerformanceSubmitUtil performanceSubmitUtil;

    @RpcReference
    WfcRequestOperateRest wfcRequestOperateRest;

    @Autowired
    PerformanceSubmitDao performanceSubmitDao;

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> params) {

        Map<String, Object> actionMap = new HashMap<>();

        String dt2_form_id = String.valueOf(params.get("dt2_form_id"));
        Long form_id = Long.valueOf(String.valueOf(params.get("form_id")));

        Long workflowid = Long.valueOf(String.valueOf(params.get("workflowid")));
        Long userid = Long.valueOf(String.valueOf(params.get("userid")));
        String form_data_id = String.valueOf(params.get("form_data_id"));

        log.error("PerformanceSubmitCreateWorkflowAction:dt2_form_id:"+dt2_form_id);
        log.error("PerformanceSubmitCreateWorkflowAction:form_id:"+form_id);
        log.error("PerformanceSubmitCreateWorkflowAction:workflowid:"+workflowid);
        log.error("PerformanceSubmitCreateWorkflowAction:userid:"+userid);
        log.error("PerformanceSubmitCreateWorkflowAction:form_data_id:"+form_data_id);

        String requestids = "";
        int errcount = 0;
        try{
            String sfzdcf = "0";
            List<Map<String,Object>> reslutList = new ArrayList<Map<String,Object>>();

            Map<String,Object> mainData = performanceSubmitDao.queryMainDataByFormDataId(Constants.TENANT_KEY,form_data_id);
            String bmlx = String.valueOf(mainData.get("bmlx"));
            log.error("PerformanceSubmitCreateWorkflowAction:bmlx:"+bmlx);
            if("0".equals(bmlx)){ //董事长
                String bmcj = "1";
                reslutList = performanceSubmitUtil.doCreateWorkflowByTopLeader(Constants.TENANT_KEY,form_id,mainData,form_data_id,workflowid,dt2_form_id,userid,bmcj,sfzdcf);
            }else if("1".equals(bmlx)) {
                String bmcj = "2";
                reslutList = performanceSubmitUtil.doCreateWorkflowByTopLeader(Constants.TENANT_KEY,form_id,mainData,form_data_id,workflowid,dt2_form_id,userid,bmcj,sfzdcf);
            }else{

                String bmcj = "";
                if("2".equals(bmlx)){ // 部长
                    bmcj = "3";
                }else if("3".equals(bmlx)){ // 科
                    bmcj = "4";
                }
                if(StringUtils.isNotBlank(bmcj)){
                    reslutList = performanceSubmitUtil.doCreateWorkflowByMiddleLeader(Constants.TENANT_KEY, form_id,mainData,form_data_id,workflowid,dt2_form_id,userid,bmcj,sfzdcf);
                }
            }

            log.error("PerformanceSubmitCreateWorkflowAction:reslutList:"+reslutList.size());
            for(int i=0;i<reslutList.size();i++) {
                Map<String, Object> reslutMap = reslutList.get(i);
                if (reslutMap.containsKey("code")) {
                    String code = String.valueOf(reslutMap.get("code"));
                    if ("200".equals(code)) {
                        String requestid = String.valueOf(reslutMap.get("requestid"));
                        requestids += StringUtils.isBlank(requestids) ? requestid : "," + requestid;
                    } else {
                        errcount++;
                    }
                }
            }

            log.error("PerformanceSubmitCreateWorkflowAction:errcount:"+errcount);

            if(errcount == 0){

                log.error("PerformanceSubmitCreateWorkflowAction:requestids:"+requestids);
                log.error("PerformanceSubmitCreateWorkflowAction:form_data_id:"+form_data_id);

                performanceSubmitDao.updateRequestid2FormTable(Constants.TENANT_KEY,requestids,form_data_id);
                actionMap.put("code",200);
                actionMap.put("msg","创建流程成功");
                actionMap.put("requestid",requestids);
            }else{
                performanceSubmitDao.updateRequestid2FormTable(Constants.TENANT_KEY,requestids,form_data_id);
                return WeaResult.fail(500,"部分流程创建失败");
            }

        }catch (Exception e){
            return WeaResult.fail(500,"创建子流程异常");
        }
        return WeaResult.success(actionMap);
    }



    public Map<String,Object> createWorkflow(Long formId,Long workflowId,SimpleEmployee cjrEmployee,List<FormDataDetailDto> formDataDetailDtos){

        Map<String,Object> requestMap = new HashMap<String,Object>();
        try{
            String username = cjrEmployee.getUsername();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String currentDate = sdf.format(new Date());

            WfcRequestOperateParamDataEntity wfcRequestOperateParamDataEntity = new WfcRequestOperateParamDataEntity();
            wfcRequestOperateParamDataEntity.setWorkflowId(workflowId);         //审批流id  必填
            wfcRequestOperateParamDataEntity.setIsNextFlow(1);
            wfcRequestOperateParamDataEntity.setRequestName("干部年度素质能力考核-"+username+"-"+currentDate);
            // 表单设计器页开发者工具 通过此接口获取字段id   /api/workflow/core/form/builder/getFormLayout

            //表单数据
            FormDataDto formDataDto = new FormDataDto();
            formDataDto.setFormId(formId);   //表单id 必填
            formDataDto.setDataDetails(formDataDetailDtos);

            //无法创建带有明细表的审批流
            WeaResult<WfcRequestOperationResultDto> flow = wfcRequestOperateRest.createFlow(wfcRequestOperateParamDataEntity, cjrEmployee, formDataDto);
            int code = flow.getCode();
            String msg = flow.getMsg();
            Long reuestid = flow.getData().getRequestId();

            requestMap.put("code",code);
            requestMap.put("msg",msg);
            requestMap.put("requestid",reuestid);

        }catch (Exception e){
            requestMap.put("code",500);
            requestMap.put("msg","创建流程接口异常");
            requestMap.put("requestid",-1);
        }
        return requestMap;
    }

}
