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.CreatePerformanceDao;
import com.weaver.seconddev.meishi.esb.util.CreatePerformanceUtil;
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_CreatePerformanceWorkflowAction")
public class CreatePerformanceWorkflowAction implements EsbServerlessRpcRemoteInterface {

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

    @Autowired
    CreatePerformanceUtil createPerformanceUtil;

    @RpcReference
    WfcRequestOperateRest wfcRequestOperateRest;

    @Autowired
    CreatePerformanceDao createPerformanceDao;

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

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

        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("CreatePerformanceWorkflowAction:form_id:"+form_id);
        log.error("CreatePerformanceWorkflowAction:workflowid:"+workflowid);
        log.error("CreatePerformanceWorkflowAction:userid:"+userid);
        log.error("CreatePerformanceWorkflowAction:form_data_id:"+form_data_id);
        String requestids = "";
        int count = 0;
        try{
            Map<String,Object> mainData = createPerformanceDao.queryMainDataByFormDataId(Constants.TENANT_KEY,form_data_id);
            List<Map<String,Object>> dt1List = createPerformanceDao.queryDt1DataByFormDataId(Constants.TENANT_KEY,form_data_id);
            log.error("CreatePerformanceWorkflowAction:dt1List:"+dt1List.size());

            for(int i=0;i<dt1List.size();i++){
                Map<String,Object> createrData = dt1List.get(i);
                String dt1id = String.valueOf(createrData.get("id"));
                log.error("CreatePerformanceWorkflowAction:dt1id:"+dt1id);

                Map<String,Object> reslutMap = createPerformanceUtil.doCreateWorkflowByUserData(Constants.TENANT_KEY,form_id,mainData,createrData,form_data_id,workflowid,userid);
                if (reslutMap.containsKey("code")) {
                    String code = String.valueOf(reslutMap.get("code"));
                    String msg = String.valueOf(reslutMap.get("msg"));
                    if ("200".equals(code)) {
                        String requestid = String.valueOf(reslutMap.get("requestid"));
                        requestids += StringUtils.isBlank(requestids) ? requestid : ","+requestid;

                        log.error("CreatePerformanceWorkflowAction:requestid:"+requestid);
                        log.error("CreatePerformanceWorkflowAction:dt1id:"+dt1id);
                        createPerformanceDao.updateRequestid2FormTable(Constants.TENANT_KEY,requestid,dt1id,"");
                    } else {
                        count++;
                        createPerformanceDao.updateRequestid2FormTable(Constants.TENANT_KEY,"",dt1id,msg);
                    }
                }
            }

            if(count >0){
                return WeaResult.fail(500,"部分流程创建失败");
            }else{
                actionMap.put("code",200);
                actionMap.put("msg","创建流程成功");
                actionMap.put("requestid",requestids);
            }
        }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;
    }

}
