package nckd.jxccl.base.common.plugins;

import com.alibaba.fastjson.JSONArray;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.param.CustomParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import kd.bos.workflow.engine.msg.AbstractMessageServiceHandler;
import kd.bos.workflow.engine.msg.ctx.MessageContext;
import kd.bos.workflow.engine.msg.info.ToDoInfo;
import nckd.jxccl.base.common.ApiClient;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SendMsgServiceHelper extends AbstractMessageServiceHandler
{

    public String getBaseURI() {
        CustomParam customParam = new CustomParam();
        customParam.getSearchKeySet().add("NOTICE_TASK_BASE_URI");
        Map<String, String> cusTomMap = SystemParamServiceHelper.loadCustomParameterFromCache(customParam);
        String noticeTaskBaseURL  = cusTomMap.get("NOTICE_TASK_BASE_URI");
        return noticeTaskBaseURL;
    }

    public Integer getSysId() {
        CustomParam customParam = new CustomParam();
        customParam.getSearchKeySet().add("NOTICE_TASK_SYSID");
        Map<String, String> cusTomMap = SystemParamServiceHelper.loadCustomParameterFromCache(customParam);
        String sysIdStr =  cusTomMap.get("NOTICE_TASK_SYSID");
        return Integer.parseInt(sysIdStr);
    }

    @Override
    public void createToDo(MessageContext messageContext, ToDoInfo toDoInfo)
    {//流程创建任务方法

        String content = toDoInfo.getContent();// 标题内容
        String billno = toDoInfo.getBillNo();//单据编码
        long taskId = toDoInfo.getTaskId();
        String fsurl = toDoInfo.getUrl();

        String selectProperties = "number";
        long fquserid = messageContext.getStartUserId();// 提交人id
        DynamicObjectCollection dynamicObject1 = QueryServiceHelper.query("bos_user", selectProperties, new QFilter("id", QCP.equals, fquserid).toArray());
        String fqnumber = "";
        for (DynamicObject object : dynamicObject1)
        {
            fqnumber = object.getString("number");
        }

        List<Long> userIds = toDoInfo.getUserIds();// 待办任务处理人主键id
        DynamicObject[] load = BusinessDataServiceHelper.load("bos_user", "id,phone",new QFilter("id", QCP.in, userIds).toArray());
        List<String> usergh = new ArrayList<>();
        for (DynamicObject user : load)
        {
            String number = user.getString("number");
            String name = user.getString("name");
            usergh.add(number);
        }

        String modelType = "exclusion";
        if (usergh.size()>1)
        {
            modelType = "countersign";
        }

        String apiPath = "/noticeTask/normalSaveTodo"; // 代办新增
        URI baseURI = URI.create(getBaseURI());
        URI full = baseURI.resolve(apiPath);
        String url = full.toString();

        HashMap bodyMap = new HashMap();

        bodyMap.put( "businessAppTodoUrl",fsurl);//移动端待办URL
        bodyMap.put( "sysId",getSysId());//系统ID
        bodyMap.put( "businessId", taskId);//业务主键id
        bodyMap.put( "businessDoneUrl",fsurl);//已办URL
        bodyMap.put( "isPushApp", 1);//7.是否推送app消息
        bodyMap.put( "businessBillType", "");//zyq会签0909 业务单据类型
        bodyMap.put( "businessTodoUrl", fsurl);//待办URL
        bodyMap.put( "modelType", modelType);//1.审批模式，单人审批(exclusion)/会签(countersign)
        bodyMap.put( "title", content);//标题
        //bodyMap.put( "startBy",fqnumber);//发起人ID
        //bodyMap.put( "createBy",fqnumber);//创建人id
        bodyMap.put( "startByUsername",fqnumber);//发起人ID
        //bodyMap.put( "createBy",fqnumber);//创建人id
        bodyMap.put( "businessParams","");//业务参数
        bodyMap.put( "businessBillCode",billno);//业务单据编码
        //bodyMap.put( "userIds",usergh);//当前待办人
        bodyMap.put( "businessType", billno);//3.业务类型  (业务主键+业务类型确定一条单据，同一个流程产生的待办这两个参数一致)
        bodyMap.put( "businessAppDoneUrl",fsurl);//移动端已办URL
        bodyMap.put( "userIdUsernames", usergh);//4.待办人id/用户名 集合(二选一)
        //bodyMap.put( "deleteUsernames", "");//5.删除待办人id/用户名 集合(二选一)
        //bodyMap.put( "taskUserUsername", "");//6.当前处理人id/用户名(二选一)
        bodyMap.put( "showInApp", 1);//是否展示在移动端

        String body = SerializationUtils.toJsonString (bodyMap);

        JSONArray fh = ApiClient.getData(url,body);
    }


    @Override
    public void dealToDo(MessageContext messageContext, ToDoInfo toDoInfo)
    {//流程处理任务方法

        String content = toDoInfo.getContent();// 标题内容
        String billno = toDoInfo.getBillNo();//单据编码
        long taskId = toDoInfo.getTaskId();

        List<Long> userIds = toDoInfo.getUserIds();// 待办任务处理人主键id
        DynamicObject[] load = BusinessDataServiceHelper.load("bos_user", "id,phone",new QFilter("id", QCP.in, userIds).toArray());
        List<String> usergh = new ArrayList<>();
        for (DynamicObject user : load)
        {
            String number = user.getString("number");
            usergh.add(number);
        }

        String taskUserUsername = "";
        if(!usergh.isEmpty())
        {
            taskUserUsername = usergh.get(0);
        }

        String modelType = "exclusion";
        if (usergh.size()>1)
        {
            modelType = "countersign";
        }

        String apiPath = "/noticeTask/updateTodoAsDone"; // 代办转已办
        URI baseURI = URI.create(getBaseURI());
        URI full = baseURI.resolve(apiPath);
        String url = full.toString();

        HashMap bodyMap = new HashMap();

        bodyMap.put( "businessId",taskId);//业务ID
        bodyMap.put( "businessType",billno);//业务类型
        bodyMap.put( "modelType", modelType);//流程模式（排他模式：exclusion；会签模式 countersign） 默认为排他模式
        bodyMap.put( "taskUserUsername",taskUserUsername);//当前待办人用户名
        bodyMap.put( "userIdUsernames", usergh);//当前待办人code

        String body = SerializationUtils.toJsonString (bodyMap);

        JSONArray fh = ApiClient.getData(url,body);
    }

    @Override
    public void deleteToDo(MessageContext messageContext, ToDoInfo toDoInfo)
    {//流程删除任务方法

        String billno = toDoInfo.getBillNo();//单据编码
        long taskId = toDoInfo.getTaskId();

        List<Long> userIds = toDoInfo.getUserIds();// 待办任务处理人主键id
        DynamicObject[] load = BusinessDataServiceHelper.load("bos_user", "id,phone",new QFilter("id", QCP.in, userIds).toArray());
        List<String> usergh = new ArrayList<>();
        for (DynamicObject user : load)
        {
            String number = user.getString("number");
            usergh.add(number);
        }

        String modelType = "exclusion";
        if (usergh.size()>1)
        {
            modelType = "countersign";
        }

        String apiPath = "/noticeTask/noticeTodoDeleteBatch"; //删除待办
        URI baseURI = URI.create(getBaseURI());
        URI full = baseURI.resolve(apiPath);
        String url = full.toString();

        HashMap bodyMap = new HashMap();

        bodyMap.put( "businessId",taskId);//业务ID
        bodyMap.put( "modelType", modelType);//流程模式（排他模式：exclusion；会签模式 countersign） 默认为排他模式
        bodyMap.put( "businessType",billno);//业务类型
        bodyMap.put( "deleteUsernames", usergh);//当前待办人code

        String body = SerializationUtils.toJsonString (bodyMap);

        JSONArray fh = ApiClient.getData(url,body);
    }





//    @Override
//    public void deleteProcessInstance(MessageContext ctx, Long proceInstanceId)
//    {//苍穹删除流程时触发该方法，用户可以在该方法中完成必要业务逻辑。
//        //String billno = ctx.getBillNo();//单据编码
//        //long taskId = ctx.getTaskId();
//        //long a = ctx.getStartUserId();
//    }



//    @Override
//    public void completeProcessInstance(MessageContext ctx, Long proceInstanceId)
//    {//苍穹流程结束时触发该方法，用户可以在该方法中完成必要业务逻辑。
//        //long taskId = ctx.getTaskId();//流程id
//        //String billno = ctx.getBillNo();//单据编码
//        //long a = ctx.getStartUserId();
//    }


}

