package com.weaver.seconddev.njwebservice;

import com.alibaba.fastjson.JSONObject;
import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.common.hrm.util.HrmCommonUtil;
import com.weaver.common.hrm.util.HrmContextUtil;
import com.weaver.common.hrm.util.Util;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.framework.rpc.context.impl.TenantRpcContext;
import com.weaver.mc.util.StringUtils;
import com.weaver.seconddev.njwebservice.entity.ToDoCountReq;
import com.weaver.seconddev.njwebservice.entity.ToDoRequestReq;
import com.weaver.seconddev.njwebservice.entity.ToDoRequestRes;
import com.weaver.seconddev.njwebservice.entity.ToDoWorkFlow;
import com.weaver.seconddev.njwebservice.prop.ConfigProp;
import com.weaver.teams.domain.user.SimpleEmployee;
import com.weaver.verupgrade.conn.CONN_TYPE;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.workflow.webservices.WorkflowBaseInfo;
import com.weaver.verupgrade.workflow.webservices.WorkflowRequestInfo;
import com.weaver.verupgrade.workflow.webservices.WorkflowService;
import com.weaver.workflow.common.entity.list.api.RequestListConditionApiEntity;
import com.weaver.workflow.common.entity.list.api.publicapi.RequestListInfoPAEntity;
import com.weaver.workflow.list.api.rest.publicapi.WflRequestListRest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *获取待办数量和待办信息
 */
@Service("outToDoWorkflowService")
public class OutToDoWorkflowService {

    @Autowired
    private WorkflowService workflowService;

    @Autowired
    private HrmCommonUtil hrmCommonUtil;

    @Autowired
    private HrmContextUtil hrmContextUtil;
    @Autowired
    private ConfigProp configProp;
    @RpcReference(group = "workflow")
    private WflRequestListRest wflRequestListRest;
    private final static Logger log = LoggerFactory.getLogger(OutToDoWorkflowService.class);


    public String outToDoWorkflowCount(ToDoCountReq param) {

        log.error("outToDoWorkflowCount入参:"+param);
//        ToDoCountReq param = JSON.parseObject(json, ToDoCountReq.class);
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.hrm.getType();
        String sql = "select ID from eteams.employee where status = 'normal' and job_num = '"+param.getWorkcode()+"'";
        rs.executeSql(sql,poolname);
        if (rs.next()){
            Long userId = Util.getLongValue(rs.getString("id"));
            log.error("outToDoWorkflowCount  userId:"+userId);
            int toDoWorkflowRequestCount = workflowService.getToDoWorkflowRequestCount(userId, param.getConditions());
            log.error("待办数量："+toDoWorkflowRequestCount);
            return String.valueOf(toDoWorkflowRequestCount);
        }else {
            return "未找到该用户";
        }
    }

    public ToDoRequestRes outToDoWorkflowList(ToDoRequestReq param) {
//        String pc_url = Util.null2String(this.getPropValue("htportaloaUrl", "pc_url")).trim();
//        String mobile_url = Util.null2String(this.getPropValue("htportaloaUrl", "mobile_url")).trim();

        log.error("outToDoWorkflowList入参:"+param);
//        ToDoRequestReq param = JSON.parseObject(json, ToDoRequestReq.class);

        String jtzhkey = configProp.getJtzhkey();
        String jtzhadmin = configProp.getJtzhadmin();
        log.error("jtzhkey:"+jtzhkey+" jtzhadmin:"+jtzhadmin);

        TenantRpcContext.setTargetTenantKey(jtzhkey);
        TenantRpcContext.setTargetEmployeeId(jtzhadmin);
        // todo 访问ip 配置
        String pc_url = "";
        String mobile_url = "";
        ToDoRequestRes res = new ToDoRequestRes();
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.hrm.getType();
        String sql = "select id from eteams.employee where status = 'normal' and job_num = '"+param.getWorkcode()+"'";
        rs.executeSql(sql,poolname);
        if (!rs.next()) {
            res.setMsg("未找到该用户");
        } else {
            param.setWorkcode(Util.null2String(rs.getString("id")));
            Long userId = Util.getLongValue(rs.getString("id"));
            log.error("用户id:"+userId);

            OutToDoWorkflowService outToDoWorkflowService = I18nContextUtil.getBean(OutToDoWorkflowService.class);
            WorkflowRequestInfo[] info = outToDoWorkflowService.getWorkflowRequestListByType(Integer.parseInt(param.getPageNo()), Integer.parseInt(param.getPageSize()),
                    Integer.parseInt(param.getRecordCount()), userId, param.getConditions(),"todo",jtzhkey);
            log.error("info:"+info.length);

            res.setMsg("find:" + info.length);
            ToDoWorkFlow[] todo = new ToDoWorkFlow[info.length];

            for(int i = 0; i < info.length; ++i) {
                ToDoWorkFlow wftodo = new ToDoWorkFlow();
                wftodo.createTime = formatDate(Util.null2String(info[i].getCreateTime())) ;
                wftodo.creatorName = Util.null2String(info[i].getCreatorName());
                wftodo.currentNodeName = Util.null2String(info[i].getCurrentNodeName());
                wftodo.lastOperateTime = formatDate(Util.null2String(info[i].getLastOperateTime()));
                wftodo.lastOperatorName = Util.null2String(info[i].getLastOperatorName());
                wftodo.receiveTime = formatDate(Util.null2String(info[i].getReceiveTime()));
                wftodo.requestId = Util.null2String(info[i].getRequestId());
                wftodo.requestLevel = Util.null2String(info[i].getRequestLevel());
                wftodo.requestName = Util.null2String(info[i].getRequestName());
                wftodo.workflowId = Util.null2String(info[i].getWorkflowBaseInfo().getWorkflowId());
                wftodo.workflowName = Util.null2String(info[i].getWorkflowBaseInfo().getWorkflowName());
                wftodo.workflowTypeId = Util.null2String(info[i].getWorkflowBaseInfo().getWorkflowTypeId());
                wftodo.workflowTypeName = Util.null2String(info[i].getWorkflowBaseInfo().getWorkflowTypeName());
                wftodo.mobileurl = mobile_url + URLEncoder.encode("http://oateste10.hengtonggroup.com.cn:20600/papi/secondev/sso/custom/login?target=jt&redirectUrl=/sp/workflow/flowpage/fullView/" + wftodo.requestId);
                wftodo.pcurl = pc_url + URLEncoder.encode("http://oateste10.hengtonggroup.com.cn:20600/papi/secondev/sso/custom/login?target=jt&redirectUrl=/sp/workflow/flowpage/fullView/" + wftodo.requestId);
                todo[i] = wftodo;
            }
            res.setWorkFlow(todo);
        }
        return res;
    }

    public WorkflowRequestInfo[] getWorkflowRequestListByType(int pageNo, int pageSize, int recordCount, Long userId, String[] conditions,String type , String jtzhkey) {
        List wris = new ArrayList();
        RecordSet recordSet=new RecordSet();
        try {

            log.error("userId = " + userId +"   jtzhkey =  " +jtzhkey);
            log.error("pageNo =  " +pageNo );
            log.error("pageSize =  " +pageSize );
            SimpleEmployee employee = hrmContextUtil.build(userId,jtzhkey);
//            SimpleEmployee employee = hrmCommonUtil.getSimpleEmployee(userId);
            log.error("employee id=  " +employee.getId());
            log.error("employee =  " +employee);

            RequestListConditionApiEntity conditionEntity=new RequestListConditionApiEntity();

            log.error("conditionEntity =  " +conditionEntity.toString());
            log.error("wflRequestListRest =  " + JSONObject.toJSONString(wflRequestListRest));
            log.error("employee =  " +employee);
            log.error("pageNo =  " +pageNo);
            log.error("pageSize =  " +pageSize);
            WeaResult<List<RequestListInfoPAEntity>> weaResult=null;
            if("todo".equals(type)){//代办
                weaResult=wflRequestListRest.getToDoWorkflowRequestList(employee, conditionEntity,pageNo, pageSize);
            }else if("done".equals(type)){//已办
                weaResult=wflRequestListRest.getHandledWorkflowRequestList(employee, conditionEntity,pageNo, pageSize);
            } else if ("processed".equals(type)) {//办结
                weaResult=wflRequestListRest.getProcessedWorkflowRequestList(employee, conditionEntity,pageNo, pageSize);
            }
            if(weaResult!=null) {
                if (weaResult.isStatus()&&weaResult.getData().size()>0) {
                    List<RequestListInfoPAEntity> requestListInfoPAEntities = weaResult.getData();
                    for (RequestListInfoPAEntity requestListInfoPA : requestListInfoPAEntities) {
                        WorkflowRequestInfo wri = new WorkflowRequestInfo();
                        wri.setRequestId(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getRequestid()));
                        wri.setRequestName(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getRequestname()));
                        wri.setRequestLevel(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getRequestLevel()));
                        //设置工作流基本信息
                        WorkflowBaseInfo workflowBaseInfo = new WorkflowBaseInfo();
                        workflowBaseInfo.setWorkflowId(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getWorkflowid()));
                        workflowBaseInfo.setWorkflowName(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getWorkflowName()));
                        workflowBaseInfo.setWorkflowTypeId(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getWorkflowType()));
                        workflowBaseInfo.setWorkflowTypeName(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getWorkflowTypeName()));
                        wri.setWorkflowBaseInfo(workflowBaseInfo);
//                        if(requestListInfoPA.getCurrentNodeInfo().size()>0){
//                            wri.setCurrentNodeName(Util.null2String(requestListInfoPA.getCurrentNodeInfo().get(0).getNodeName()));
//                            wri.setCurrentNodeId(requestListInfoPA.getCurrentNodeInfo().get(0).getId() + "");
//                        }
                        //列表不会有当前节点信息，需要单独走下接口 com.weaver.workflow.core.api.rest.seconddev.WfcRequestGetDataRpc4SecondDev#getCurrentNodeByRequestID
//                        List<Long> requestIds=new ArrayList<>();
//                        requestIds.add(requestListInfoPA.getRequestid());
//                        WeaUser user = OrgUtil.getIn18User(userId);
//                        Map<Long, SecDevWfcSimpleNodeEntity> map= wfcRequestGetDataRpc4SecondDev.getCurrentNodeByRequestID(requestIds,user);
//                        SecDevWfcSimpleNodeEntity secDevWfcSimpleNodeEntity=map.get(requestListInfoPA.getRequestid());
//                        if(secDevWfcSimpleNodeEntity!=null){
//                            wri.setCurrentNodeName(Util.null2String(secDevWfcSimpleNodeEntity.getNodeName()));
//                            wri.setCurrentNodeId( Util.null2String( secDevWfcSimpleNodeEntity.getId()));
//                        }

                        String sql="select wc.nodeid,wp.nodename as nodename1,wpf.nodename as nodename2  from wfc_currentnode wc left join wfp_node wp on wc.nodeid=wp.id left join wfpf_node wpf on wc.nodeid=wpf.id where wc.tenant_key=? and wc.requestid=? and wc.delete_type=0  order by wc.create_time desc" ;
                        recordSet.executeForWf(sql, employee.getTenantKey(), requestListInfoPA.getRequestid()+"");
                        if(recordSet.next()){
                            String nodeid= com.weaver.verupgrade.general.Util.null2String(recordSet.getString("nodeid"));
                            String nodename1= com.weaver.verupgrade.general.Util.null2String(recordSet.getString("nodename1"));
                            String nodename2= com.weaver.verupgrade.general.Util.null2String(recordSet.getString("nodename2"));

                            wri.setCurrentNodeName(nodename1);
                            if("".equals(nodename1)){
                                wri.setCurrentNodeName(nodename2);
                            }
                            wri.setCurrentNodeId(nodeid);
                        }




                        wri.setCreatorId(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getCreatorId()));
                        wri.setCreatorName(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getCreatorName()));
                        wri.setCreateTime(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getCreateTime()));
                        wri.setLastOperatorName(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getLastOperatorName()));
                        wri.setLastOperateTime(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getLastOperateTime()));
                        wri.setReceiveTime(com.weaver.verupgrade.general.Util.null2String(requestListInfoPA.getReceiveTime()));
                        wris.add(wri);
                    }
                }
            }
        } catch (Exception e) {
            log.error("getWorkflowRequestListByType>>>>error",e);
        }
        WorkflowRequestInfo[] wriarrays = new WorkflowRequestInfo[wris.size()];
        for (int i = 0; i < wris.size(); i++)
            wriarrays[i] = (WorkflowRequestInfo) wris.get(i);
        return wriarrays;
    }


    private String formatDate (String timeStr){

        log.error("outToDoWorkflowCount formatDate :"+ timeStr);
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String output = "";
        try {
            // 将输入字符串解析为 Date 对象
            if(StringUtils.isNotEmpty(timeStr)){
                Date date = inputFormat.parse(timeStr);
                // 将 Date 对象格式化为目标字符串
                output = outputFormat.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("output :"+ output);
        return output;
    }
}
