package org.stm.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysLog;
import org.jeecg.modules.system.entity.SysTenant;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.stm.audit.entity.AuditProject;
import org.stm.flow.entity.FlowCclist;
import org.stm.flow.entity.FlowGenerworkflow;
import org.stm.flow.entity.FlowRunlist;
import org.stm.flow.entity.FlowTask;
import org.stm.flow.service.IFlowCclistService;
import org.stm.flow.service.IFlowGenerworkflowService;
import org.stm.flow.service.IFlowRunlistService;
import org.stm.flow.service.IFlowTaskService;
import org.stm.metric.service.IMetricMonitorSetService;
import org.stm.metric.service.IMetricReportService;
import org.stm.my.entity.MyTask;
import org.stm.my.service.IMyTaskService;
import org.stm.page.service.IPageMonitorchartService;
import org.stm.page.service.IPageTitleconfigService;
import org.stm.plan.main.entity.StPlanMan;
import org.stm.plan.main.service.IStPlanManService;
import org.stm.rectify.approve.service.IStRectifyApproveService;
import org.stm.rectify.assin.service.IStProblemTaskAssinService;
import org.stm.rectify.exec.service.IStRectifyExecService;
import org.stm.rectify.plan.service.IStRectifyPlanService;

import java.net.InetAddress;
import java.util.*;

@Api(tags="工作流接口")
@RestController
@RequestMapping("/api/jflow")
@Slf4j
public class JFlowAPIController {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IPageTitleconfigService pageTitleconfigService;

    @Autowired
    private IStProblemTaskAssinService stProblemTaskAssinService;
    @Autowired
    private IStRectifyApproveService stRectifyApproveService;
    @Autowired
    private IStRectifyExecService stRectifyExecService;
    @Autowired
    private IStRectifyPlanService iStRectifyPlanService;
    @Autowired
    private IPageMonitorchartService pageMonitorchartService;
    @Autowired
    private IMetricReportService metricReportService;
    @Autowired
    private IMetricMonitorSetService metricMonitorSetService;

    @Autowired
    private IFlowTaskService flowTaskService;
    @Autowired
    private IMyTaskService myTaskService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ISysTenantService sysTenantService;
    @Autowired
    private IFlowCclistService flowCclistService;
    @Autowired
    private IFlowRunlistService flowRunlistService;
    @Autowired
    private ISysLogService sysLogService;
    @Autowired
    private IStPlanManService stPlanManService;
    @Autowired
    private IFlowGenerworkflowService flowGenerworkflowService;


    //@Value(value = "${ccflow.flowurl}")
    private String flowurl;

    @GetMapping(value = "/queryById")
    public Result<AuditProject> queryById(@RequestParam(name="WorkID",required=true) String WorkID) {

        System.out.println("----------------WorkID"+WorkID);

        String url = flowurl+"/restful/DB_TodolistALL?token=";
        String getData = HttpClientUtil.doGet(url);
        //net.sf.json.JSONObject j2 = net.sf.json.JSONObject.fromObject(getData);



       // System.out.println("=============why buhuo SendWhen=================="+getData);

        JSONArray jsonArray = JSONArray.parseArray(getData);

// 可以遍历获取JSON数组对象中的每一个JSON对象，其实和普通数组的遍历方式类似
// 遍历方式1
        int size = jsonArray.size();
        flowTaskService.deleteflowtask();
        myTaskService.deleteMytaskByFlowtask();

        for (int i = 0; i < size; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println(i+" =============why buhuo SendWhen=================="+jsonObject);
            //{"FK_Flow":"093","TodoEmpDeptNo":"1668199659936739330","NodeName":"报送内容审批","FK_FlowSort":"101","PRI":1,"WorkID":1647815203,"Starter":"admin","IsRead":0,"ADT":"2025-05-14 14:44:05","BillNo":"","FK_Node":9302,"FK_Dept":"1678967416676200450","ListType":"0","DeptName":"风险合规部","SysType":"","SendDT":"2025-05-14 14:44","GuestName":"","FlowIdx":0,"GuestNo":"","FID":0,"SDTOfNode":"2025-05-14 14:44","AtPara":"@CreateRDT=2025-05-14 14:43:44@IsCanBatch=0@LastTruckID=577747951443509248@ThreadCount=0@ScripNodeID=0@ScripMsg=","StarterName":"admin","SDT":"无","RDT":"2025-05-14 14:43:44","PWorkID":0,"Auther":"","Title":"风险合规部 - admin 在 2025-05-14 14:43 发起","TodoEmps":"kxjia,kxjia;","OrgNo":"","TaskSta":"0","FK_Emp":"kxjia","FlowNote":"","TodoSta":"0","Sender":"admin,admin;","PFlowNo":"","FlowName":"报送内容审批","FlowSortIdx":0,"WFState":"2","TodoEmpsNum":1,"Domain":""}

            String WorkID_T = jsonObject.getString("WorkID");
            String FID = jsonObject.getString("FID");
            String FlowName = jsonObject.getString("FlowName");
            String WFState = jsonObject.getString("WFState");
            String Starter = jsonObject.getString("Starter");
            String StarterName = jsonObject.getString("StarterName");
            String Sender = jsonObject.getString("Sender");
            if(Sender.indexOf(",")>0){
                int fgf=Sender.indexOf(",");
                String sendrone=  Sender.substring(0,fgf);
                Sender=sendrone;

            }
            String Title = jsonObject.getString("Title");
            String FK_Flow = jsonObject.getString("FK_Flow");
            String ADT = jsonObject.getString("ADT");//发送时间
            String RDT = jsonObject.getString("RDT");//发起日期
            String NodeName = jsonObject.getString("NodeName");
            String FK_Emp = jsonObject.getString("FK_Emp");

           // System.out.println(i+" "+WorkID_T+" "+Title+" "+FK_Flow+" "+ADT+" "+NodeName+" "+Starter+" "+FK_Emp);
            SysUser sysUser = sysUserService.getUserByName(FK_Emp);
            if(sysUser==null){
                continue;
            }
            FlowTask flowTask = new FlowTask();
            flowTask.setWorkid(Integer.parseInt(WorkID_T));
            flowTask.setFid(Integer.parseInt(FID));
            flowTask.setFlowname(FlowName);
            flowTask.setWfstate(Integer.parseInt(WFState));
            flowTask.setStarter(Starter);
            flowTask.setStartername(StarterName);
            flowTask.setSender(Sender);
            flowTask.setTitle(Title);
            flowTask.setFkFlow(FK_Flow);
            flowTask.setAdt(ADT);
            flowTask.setRdt(RDT);
            flowTask.setNodename(NodeName);
            flowTask.setFkEmp(FK_Emp);
            flowTaskService.save(flowTask);

            MyTask myTask = new MyTask();
            myTask.setUid(sysUser.getId());
            myTask.setTp(5);
            myTask.setTarget(Title);
            myTask.setTargetId("0");
            myTask.setStTime(new Date());
            myTask.setTaskName("待审批");
            myTask.setName(Title);
            myTask.setSta(0);
            myTask.setPriority("M");
            myTask.setDes("");
            myTask.setLinkAddr("/workflow/base/todo");
            myTaskService.save(myTask);
        }
        return Result.OK("OK");
    }

    public void saveFlowCclist(String getData){
        try{
            JSONArray jsonArray = JSONArray.parseArray(getData);

// 可以遍历获取JSON数组对象中的每一个JSON对象，其实和普通数组的遍历方式类似
// 遍历方式1
//[{"MyPK":"1489685410_9703_test1","Title":"来自ccflow3的抄送","FK_Flow":"097","FlowName":"风险监测预警流程","WorkID":1489685410,"Doc":"","Rec":"ccflow3","RecName":"ccflow3","RDT":"2025-07-02 14:27","FID":0,"FK_Node":9703,"NodeName":"二级审核","Sta":0,"NodeIDCC":9703,"NodeIDCCName":"二级审核","ReadDT":"","CDT":"2025-07-02 13:37:09","WFState":3,"SendDT":"2025-07-03 09:56","CCTo":"test1","CCToName":"test1","DeptNo":"1645731983918174209","DeptName":"办公室"}]
            int size = jsonArray.size();

            //flowTaskService.deleteflowtask();


            for (int i = 0; i < size; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                System.out.println(i+" =============why buhuo SendWhen=================="+jsonObject);
                //{"FK_Flow":"093","TodoEmpDeptNo":"1668199659936739330","NodeName":"报送内容审批","FK_FlowSort":"101","PRI":1,"WorkID":1647815203,"Starter":"admin","IsRead":0,"ADT":"2025-05-14 14:44:05","BillNo":"","FK_Node":9302,"FK_Dept":"1678967416676200450","ListType":"0","DeptName":"风险合规部","SysType":"","SendDT":"2025-05-14 14:44","GuestName":"","FlowIdx":0,"GuestNo":"","FID":0,"SDTOfNode":"2025-05-14 14:44","AtPara":"@CreateRDT=2025-05-14 14:43:44@IsCanBatch=0@LastTruckID=577747951443509248@ThreadCount=0@ScripNodeID=0@ScripMsg=","StarterName":"admin","SDT":"无","RDT":"2025-05-14 14:43:44","PWorkID":0,"Auther":"","Title":"风险合规部 - admin 在 2025-05-14 14:43 发起","TodoEmps":"kxjia,kxjia;","OrgNo":"","TaskSta":"0","FK_Emp":"kxjia","FlowNote":"","TodoSta":"0","Sender":"admin,admin;","PFlowNo":"","FlowName":"报送内容审批","FlowSortIdx":0,"WFState":"2","TodoEmpsNum":1,"Domain":""}
                String FlowName = jsonObject.getString("FlowName");
                String WorkID_T = jsonObject.getString("WorkID");
                String MyPK = jsonObject.getString("MyPK");
                String FK_Flow = jsonObject.getString("FK_Flow");
                String FID = jsonObject.getString("FID");
                String Sta = jsonObject.getString("Sta");
                String FK_Node = jsonObject.getString("FK_Node");
                String NodeIDCC = jsonObject.getString("NodeIDCC");

                String WFState = jsonObject.getString("WFState");
                String Title = jsonObject.getString("Title");
                String Rec = jsonObject.getString("Rec");
                String NodeName = jsonObject.getString("NodeName");
                String RDT = jsonObject.getString("RDT");
                String CCTo = jsonObject.getString("CCTo");


                SysUser sysUser = sysUserService.getUserByName(Rec);
                if(sysUser==null){
                    continue;
                }

                FlowCclist FlowCclist = new FlowCclist();
                FlowCclist.setFlowname(FlowName);
                FlowCclist.setTitle(Title);
                FlowCclist.setRecempno(Rec);
                FlowCclist.setRecempname(Rec);
                FlowCclist.setNodename(NodeName);
                FlowCclist.setRdt(RDT);



                FlowCclist.setWorkid(Integer.parseInt(WorkID_T));
                FlowCclist.setMypk(MyPK);
                FlowCclist.setFkFlow(FK_Flow);
                FlowCclist.setFid(Integer.parseInt(FID));
                FlowCclist.setSta(Integer.parseInt(Sta));
                FlowCclist.setNodeidwork(Integer.parseInt(FK_Node));
                FlowCclist.setNodeidcc(Integer.parseInt(NodeIDCC));
                //WFState
                if(WFState!=null&&!WFState.equals("")){
                    FlowCclist.setWfstate(Integer.parseInt(WFState));
                }

                FlowCclist.setCcto(CCTo);

                flowCclistService.save(FlowCclist);


            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @GetMapping(value = "/ccList")
    public void ccList(@RequestParam(name="token",required=true) String token) {

        //同时清除 在途表信息
        flowCclistService.deleteflowcclistByRecEmpNo(null);
        String url = flowurl+"/WF/API/DB_CCListByIsRead_CC?isRead=0&token="+token;
        String getData = HttpClientUtil.doGet(url);
        saveFlowCclist(getData);
        String url1 = flowurl+"/restful/DB_RuningALL";
        String getData1 = HttpClientUtil.doGet(url1);
        saveFlowRunlist(getData1);

        //http://127.0.0.1:8180/WF/API/Flow_RecentWorkInit?token=df50f160d94e48c69ad1f0ecde009d02
        String gdurl = flowurl+"/WF/API/Flow_RecentWorkInit?token="+token;
        String gdgetData = HttpClientUtil.doGet(gdurl);
        saveFlowGenerworkflow(gdgetData);

        //return Result.OK("OK");
    }

    public void saveFlowRunlist(String getData){
        try{
            JSONArray jsonArray = JSONArray.parseArray(getData);

// 可以遍历获取JSON数组对象中的每一个JSON对象，其实和普通数组的遍历方式类似
// 遍历方式1
//[{"MyPK":"1489685410_9703_test1","Title":"来自ccflow3的抄送","FK_Flow":"097","FlowName":"风险监测预警流程","WorkID":1489685410,"Doc":"","Rec":"ccflow3","RecName":"ccflow3","RDT":"2025-07-02 14:27","FID":0,"FK_Node":9703,"NodeName":"二级审核","Sta":0,"NodeIDCC":9703,"NodeIDCCName":"二级审核","ReadDT":"","CDT":"2025-07-02 13:37:09","WFState":3,"SendDT":"2025-07-03 09:56","CCTo":"test1","CCToName":"test1","DeptNo":"1645731983918174209","DeptName":"办公室"}]
            int size = jsonArray.size();

            //flowTaskService.deleteflowtask();


            for (int i = 0; i < size; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                System.out.println(i+" =============why buhuo SendWhen=================="+jsonObject);
                //{"FK_Flow":"093","TodoEmpDeptNo":"1668199659936739330","NodeName":"报送内容审批","FK_FlowSort":"101","PRI":1,"WorkID":1647815203,"Starter":"admin","IsRead":0,"ADT":"2025-05-14 14:44:05","BillNo":"","FK_Node":9302,"FK_Dept":"1678967416676200450","ListType":"0","DeptName":"风险合规部","SysType":"","SendDT":"2025-05-14 14:44","GuestName":"","FlowIdx":0,"GuestNo":"","FID":0,"SDTOfNode":"2025-05-14 14:44","AtPara":"@CreateRDT=2025-05-14 14:43:44@IsCanBatch=0@LastTruckID=577747951443509248@ThreadCount=0@ScripNodeID=0@ScripMsg=","StarterName":"admin","SDT":"无","RDT":"2025-05-14 14:43:44","PWorkID":0,"Auther":"","Title":"风险合规部 - admin 在 2025-05-14 14:43 发起","TodoEmps":"kxjia,kxjia;","OrgNo":"","TaskSta":"0","FK_Emp":"kxjia","FlowNote":"","TodoSta":"0","Sender":"admin,admin;","PFlowNo":"","FlowName":"报送内容审批","FlowSortIdx":0,"WFState":"2","TodoEmpsNum":1,"Domain":""}
                String FlowName = jsonObject.getString("FlowName");
                String WorkID_T = jsonObject.getString("WorkID");
                String MyPK = jsonObject.getString("MyPK");
                String FK_Flow = jsonObject.getString("FK_Flow");
                String FID = jsonObject.getString("FID");
                String DeptName = jsonObject.getString("DeptName");

                String FK_Node = jsonObject.getString("FK_Node");
                String CurrNode = jsonObject.getString("CurrNode");

                String WFState = jsonObject.getString("WFState");
                String Title = jsonObject.getString("Title");
                String Starter = jsonObject.getString("Starter");
                String NodeName = jsonObject.getString("NodeName");
                String RDT = jsonObject.getString("RDT");


                String TodoEmps = jsonObject.getString("TodoEmps");
                if(TodoEmps.indexOf(",")>0){
                    int fgf=TodoEmps.indexOf(",");
                    String sendrone=  TodoEmps.substring(0,fgf);
                    TodoEmps=sendrone;

                }

                SysUser sysUser = sysUserService.getUserByName(Starter);
                if(sysUser==null){
                    continue;
                }

                FlowRunlist FlowCclist = new FlowRunlist();

                String RunType = jsonObject.getString("RunType");
                String WhoExeIt = jsonObject.getString("WhoExeIt");
                String PWorkID = jsonObject.getString("PWorkID");
                String PFlowNo = jsonObject.getString("PFlowNo");

                FlowCclist.setRuntype(Integer.parseInt(RunType));
                FlowCclist.setWhoexeit(Integer.parseInt(WhoExeIt));
                FlowCclist.setPworkid(Integer.parseInt(PWorkID));
                FlowCclist.setPflowno(PFlowNo);

                FlowCclist.setFlowname(FlowName);
                FlowCclist.setTitle(Title);
                FlowCclist.setStarter(Starter);
                FlowCclist.setStartername(Starter);
                FlowCclist.setNodename(NodeName);
                FlowCclist.setRdt(RDT);
                FlowCclist.setDeptname(DeptName);


                FlowCclist.setWorkid(Integer.parseInt(WorkID_T));
                //FlowCclist.setMypk(MyPK);
                FlowCclist.setFkFlow(FK_Flow);
                FlowCclist.setFid(Integer.parseInt(FID));

                FlowCclist.setFkNode(Integer.parseInt(FK_Node));
                FlowCclist.setCurrnode(Integer.parseInt(CurrNode));
                FlowCclist.setWfstate(Integer.parseInt(WFState));
                FlowCclist.setTodoemps(TodoEmps);


                flowRunlistService.save(FlowCclist);


            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @GetMapping(value = "/getUser")
    public  Result<?> getUser(@RequestParam(name="Token",required=true) String Token) {
        Object username = redisUtil.get(Token);
        if(username==null){
            return Result.OK("");
        }
        return Result.OK(username.toString());
    }


//    @GetMapping(value = "/setCCWorkId")
//    public Result<?> getCCWorkId(@RequestParam(name="WorkID",required=true) String WorkID,
//                                 @RequestParam(name="kjzlid",required=true) String kjzlid) {
//        redisUtil.set("WorkID" + WorkID, kjzlid);
//        return Result.OK("OK");
//    }

    @GetMapping(value = "/setCCWorkId")
    public void setCCWorkId(@RequestParam(name="targetKey",required=true) String targetKey,
                                 @RequestParam(name="targetId",required=true) String targetId,
                                 @RequestParam(name="token",required=true) String token) {
        Map<String,String> retMap = new HashMap<>();
        redisUtil.set("WorkID_" + targetKey, targetId);
        //redisUtil.set("WorkID_token", token);
        //return Result.OK("OK");
    }

    @GetMapping(value = "/getCCWorkTokenAndTid")
    public Result<?> getCCWorkTokenAndTid(
            @RequestParam(name="targetKey",required=true) String targetKey,
            @RequestParam(name="flowToken",required=true) String flowToken,
            @RequestParam(name="WorkID",required=false) String WorkID
     ) {
        Object targetId = redisUtil.get("WorkID_" + targetKey);
        Object username = redisUtil.get(flowToken);
        Object objToken = redisUtil.get( "pt_"+username.toString());

        Map<String,Object> retMap = new HashMap<>();
        retMap.put("tid",targetId);
        retMap.put("token",objToken);

        getCCFlowStatus(WorkID,flowToken,targetId.toString());
        int ss=0;

        return Result.OK(retMap);
    }

    @GetMapping(value = "/getkjzlidAndToken")
    public  Result<String> getkjzlidAndToken(@RequestParam(name="Token",required=true) String Token,
                                             @RequestParam(name="WorkID",required=true) String WorkID) {
        Result<String> result = new Result<>();
        Object kjzlid = redisUtil.get("WorkID" + WorkID);
        if(kjzlid==null){
            result.setSuccess(true);
            result.setResult("");
        }
        Object username = redisUtil.get(Token);
        if(username==null){
            result.setSuccess(true);
            result.setResult("");
        }
        Object tokenpt = redisUtil.get( "pt_"+username.toString());
        //System.out.println("getkjzlidAndToken "+kjzlid.toString()+"$"+tokenpt.toString());
        result.setSuccess(true);
        result.setResult(WorkID.toString()+"$"+tokenpt.toString());
        return result;
    }

    @GetMapping(value = "/getUserTokey")
    public  Result<?> getUserTokey(@RequestParam(name="Token",required=true) String Token) {
        Object username = redisUtil.get(Token);
        if(username==null){
            return Result.OK("");
        }
        Object tokenpt = redisUtil.get( "pt_"+username.toString());
        System.out.println("getUserTokey "+tokenpt.toString());
        redisUtil.set("TokenUser",username.toString());
/**
        Result<JSONObject> result = new Result<JSONObject>();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername,username.toString());
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        //update-end-author:wangshuai date:20200601 for: 登录代码验证用户是否注销bug，if条件永远为false
        result = sysUserService.checkUserIsEffective(sysUser);

        //用户登录信息
        userInfo(sysUser, result);
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(sysUser, loginUser);
        */

        return Result.OK(tokenpt);
    }

    @GetMapping(value = "/getFlow")
    public  Result<?> getFlow(@RequestParam(name="token",required=true) String token) {

        String url = flowurl+"/restful/DB_StarFlows?token="+token;
        String getData = HttpClientUtil.doGet(url);
        //net.sf.json.JSONObject j2 = net.sf.json.JSONObject.fromObject(getData);
        // System.out.println("=============why buhuo SendWhen=================="+getData);
        JSONArray jsonArray = JSONArray.parseArray(getData);
        return Result.OK(jsonArray);
    }
    /**
     * 用户信息
     *
     * @param sysUser
     * @param result
     * @return
     */
    private Result<JSONObject> userInfo(SysUser sysUser, Result<JSONObject> result) {
        String username = sysUser.getUsername();
        String syspassword = sysUser.getPassword();
        // 获取用户部门信息
        JSONObject obj = new JSONObject(new LinkedHashMap<>());

        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        obj.put("token", token);

        redisUtil.set("pt_"+username,token);

        // update-begin--Author:sunjianlei Date:20210802 for：获取用户租户信息
        String tenantIds = sysUser.getRelTenantIds();
        if (oConvertUtils.isNotEmpty(tenantIds)) {
            List<Integer> tenantIdList = new ArrayList<>();
            for(String id: tenantIds.split(SymbolConstant.COMMA)){
                tenantIdList.add(Integer.valueOf(id));
            }
            // 该方法仅查询有效的租户，如果返回0个就说明所有的租户均无效。
            List<SysTenant> tenantList = sysTenantService.queryEffectiveTenant(tenantIdList);
            if (tenantList.size() == 0) {
                result.error500("与该用户关联的租户均已被冻结，无法登录！");
                return result;
            } else {
                obj.put("tenantList", tenantList);
            }
        }
        // update-end--Author:sunjianlei Date:20210802 for：获取用户租户信息

        obj.put("userInfo", sysUser);

        List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
        obj.put("departs", departs);
        if (departs == null || departs.size() == 0) {
            obj.put("multi_depart", 0);
        } else if (departs.size() == 1) {
            //sysUserService.updateUserDepart(username, departs.get(0).getOrgCode());
            obj.put("multi_depart", 1);
        } else {
            //查询当前是否有登录部门
            // update-begin--Author:wangshuai Date:20200805 for：如果用戶为选择部门，数据库为存在上一次登录部门，则取一条存进去
            SysUser sysUserById = sysUserService.getById(sysUser.getId());
            if(oConvertUtils.isEmpty(sysUserById.getOrgCode())){
               // sysUserService.updateUserDepart(username, departs.get(0).getOrgCode());
            }
            // update-end--Author:wangshuai Date:20200805 for：如果用戶为选择部门，数据库为存在上一次登录部门，则取一条存进去
            obj.put("multi_depart", 2);
        }
        obj.put("sysAllDictItems", sysDictService.queryAllDictItems());
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }


    @GetMapping(value = "/saveLog")
    public void saveLog(@RequestParam(name="No",required=true) String No,
                        @RequestParam(name="NodeID",required=true) String NodeID,
                        @RequestParam(name="Name",required=true) String Name,
                        @RequestParam(name="WorkID",required=true) String WorkID,
                        @RequestParam(name="ExecerName",required=true) String ExecerName,
                        @RequestParam(name="flowName",required=true) String flowName
                        ) {

        try {
        String ip = InetAddress.getLocalHost().getHostAddress();
        SysLog log=new SysLog();
        log.setIp(ip);
        log.setCreateBy(ExecerName);
            log.setCreateTime(new Date());
            log.setLogContent(flowName+"-"+Name);
            log.setLogType(2);
            log.setOperateType(7);
            log.setUserid(ExecerName);
            log.setUsername(ExecerName);
        sysLogService.save(log);
        //return Result.OK("OK");

           // getCCFlowStatus(WorkID,null,ExecerName);


           // redisUtil.set("flowToken_" + username,flowToken);

        } catch (Exception e) {

        }
    }



    public String  getCCFlowStatus(String WorkID,String token,String targetId) {
        /**
        if(token==null&&ExecerName!=null){
            token=(String)redisUtil.get("flowToken_"+ExecerName);
            System.out.println(""+token);
        }
        */
        try {


        String url = flowurl+"/restful/CurrGenerWorkFlowInfo?workID="+WorkID+"&token="+token;
        String getData = HttpClientUtil.doGet(url);

       // System.out.println(" =============getData=================="+getData);

        JSONObject jsonObjectget=JSONObject.parseObject(getData);

      //  System.out.println(" =============jsonObjectget=================="+jsonObjectget);
        String WorkID_T = jsonObjectget.getString("WorkID");
        String WFState = jsonObjectget.getString("WFState");

        String FK_Flow = jsonObjectget.getString("FK_Flow");
        if(FK_Flow.equals("087")){
            StPlanMan stPlanMan=new StPlanMan();
            stPlanMan.setId(Integer.parseInt(targetId));
            //计划
            if(WFState.equals("3")){
                //流程结束
                stPlanMan.setPlanFlag("99");
            }else if(WFState.equals("2")){
                //流程审核中
                stPlanMan.setPlanFlag("11");
            }

            stPlanManService.updateByIdOne(stPlanMan);
        }


        System.out.println(" =============WFState=================="+WFState);
        } catch (Exception e) {

        }

        return "";
    }


    //归档保存
    public void saveFlowGenerworkflow(String getData){
        try{

            JSONObject postData =JSON.parseObject(getData);
            if (postData.containsKey("data")) {
                String dataStr = postData.getString("data");
                if (dataStr != null && !dataStr.isEmpty()) {


            JSONArray jsonArray = JSONArray.parseArray(dataStr);

         int size = jsonArray.size();

            //flowTaskService.deleteflowtask();


            for (int i = 0; i < size; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                System.out.println(i+" =============why buhuo 归档流程信息=================="+jsonObject);
                //{"FK_FlowSort":"101","NodeName":"连通审核","PRI":1,"WeekNum":0,"FK_Node":10102,"EDT":"2025-10-29 11:39:28","SysType":"","GuestName":"","AtPara":"@StopFlowType=0@EndFlowRDT=2025-10-29 11:39:29@ScripNodeID=0@LastTruckID=638582653305487360@ScripMsg=@ThreadCount=0@CreateRDT=2025-10-29 11:38:07@IsCanBatch=0","StarterName":"admin","SDT":"2025-10-29 11:38:49","GUID":"","TodoEmps":"admin,admin;","OrgNo":"","TaskSta":0,"FlowNote":"","Sender":"admin,admin;","SDTOfFlow":"","PFID":0,"LostTimeHH":0.0,"FlowName":"测试连通流程","WFSta":1,"TodoEmpsNum":1,"Domain":"","FK_Flow":"101","PrjName":"","GWLJson":"","DomainExt":"","WorkID":800354515,"Starter":"admin","BillNo":"CC2025-0004","FK_Dept":"5159cde220114246b045e574adceafe9","PNodeID":0,"DeptName":"研发部","SendDT":"2025-10-29 11:39","GuestNo":"","FID":0,"SDTOfNode":"2025-10-29 11:38","RDT":"2025-10-29 11:38:07","HungupTime":"","PWorkID":0,"SortPath":"","Title":"研发部 - admin 在 2025-10-29 11:38 发起","Emps":"@admin,admin@","TodoSta":0,"PFlowNo":"","PrjNo":"","FK_NY":"2025-10","TSpan":0,"WFState":3,"PEmp":"","SDTOfFlowWarning":""}

                String FlowName = jsonObject.getString("FlowName");
                String WorkID_T = jsonObject.getString("WorkID");

                String FK_Flow = jsonObject.getString("FK_Flow");
                String FID = jsonObject.getString("FID");
                String DeptName = jsonObject.getString("DeptName");

                String FK_Node = jsonObject.getString("FK_Node");

                String SendDT = jsonObject.getString("SendDT");




                String WFState = jsonObject.getString("WFState");
                String Title = jsonObject.getString("Title");
                String Starter = jsonObject.getString("Starter");
                String NodeName = jsonObject.getString("NodeName");
                String RDT = jsonObject.getString("RDT");


                String Sender = jsonObject.getString("Sender");
                if(Sender.indexOf(",")>0){
                    int fgf=Sender.indexOf(",");
                    String sendrone=  Sender.substring(0,fgf);
                    Sender=sendrone;

                }



                SysUser sysUser = sysUserService.getUserByName(Starter);
                if(sysUser==null){
                    continue;
                }

                FlowGenerworkflow FlowGenerworkflowlist = new FlowGenerworkflow();



                FlowGenerworkflowlist.setFlowname(FlowName);
                FlowGenerworkflowlist.setSenddt(SendDT);
                FlowGenerworkflowlist.setTitle(Title);
                FlowGenerworkflowlist.setStarter(Starter);
                FlowGenerworkflowlist.setStartername(Starter);
                FlowGenerworkflowlist.setNodename(NodeName);
                FlowGenerworkflowlist.setRdt(RDT);
                FlowGenerworkflowlist.setDeptname(DeptName);

                FlowGenerworkflowlist.setSender(Sender);


                FlowGenerworkflowlist.setWorkid(Integer.parseInt(WorkID_T));
                //FlowCclist.setMypk(MyPK);
                FlowGenerworkflowlist.setFkFlow(FK_Flow);
                FlowGenerworkflowlist.setFid(Integer.parseInt(FID));

                FlowGenerworkflowlist.setFkNode(Integer.parseInt(FK_Node));

                FlowGenerworkflowlist.setWfstate(Integer.parseInt(WFState));



                flowGenerworkflowService.save(FlowGenerworkflowlist);


            }

                } else {


                }
            } else {


            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @GetMapping(value = "/getUsertest")
    public  Result<?> getUsertest(){

        return Result.OK("why is ok");
    }



}

