package com.weaver.seconddev.interfaces.workflow.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.weaver.common.authority.annotation.WeaPermission;
import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.common.distribution.genid.IdGenerator;
import com.weaver.common.distribution.lock.DistributionLockInterface;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.custom.configcenter.htsysjcmtConfig;
import com.weaver.ebuilder.datasource.api.entity.ExecuteSqlEntity;
import com.weaver.ecode.api.dto.FolderDto;
import com.weaver.ecode.api.rpc.EcodeService;
import com.weaver.framework.client.annotation.WeaverConfigCenter;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.framework.rpc.context.impl.TenantRpcContext;
import com.weaver.openapi.pojo.ApiResult;
import com.weaver.openapi.pojo.auth.params.AccessTokenParam;
import com.weaver.openapi.pojo.auth.params.CodeParam;
import com.weaver.openapi.pojo.auth.res.AccessToken;
import com.weaver.openapi.pojo.auth.res.Code;
import com.weaver.openapi.pojo.message.params.MessageVo;
import com.weaver.openapi.pojo.message.params.vo.MessageEntity;
import com.weaver.openapi.pojo.message.params.vo.MessageReciver;
import com.weaver.openapi.pojo.message.params.vo.MessageSender;
import com.weaver.openapi.service.AuthService;
import com.weaver.openapi.service.MessageService;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import com.weaver.teams.domain.user.SimpleEmployee;
import com.weaver.teams.security.context.UserContext;
import com.weaver.teams.security.user.User;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.workflow.common.entity.list.api.publicapi.RequestListInfoPAEntity;
import com.weaver.workflow.list.api.rest.publicapi.WflRequestListRest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

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

@Slf4j
@RestController
@RequestMapping({"/papi/secondev/workflow/demo" })
//@WeaPermission
public class ApiController {

    // api 需要用户会话，e10入口地址访问
    // papi 任何人都可以直接访问 public api，e10入口地址访问
    // sapi 服务内部通信的接口路由前缀 /sapi/secondev，e10入口地址访问不了
    // 二开服务新接口：/api/secondev，/papi/secondev

    @RpcReference(timeout = 10000)
    EcodeService ecodeService;
    @RpcReference(timeout = 2000, group = "workflow")
    WflRequestListRest wflRequestListRest;
    @Autowired
    private DistributionLockInterface distributionLock;
    @Autowired
    private ConfigProp configProp;
    @Autowired
    private htsysjcmtConfig htsysjcmtConfig;
//    @Value("${srmbacklisturl}")
//    private String srmbacklisturl;
//
    @Value("${weaver.swagger.basePackage}")
    private String basePackage;

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ApiController.class);
    @GetMapping("/hello")
    //@PostMapping("/post")
    public WeaResult<String> hello(@RequestParam("key") String key) {
        // todo api

        logger.error("ApiController info :  hello "  );
        logger.error("srmbacklisturl == " +1);
        logger.error("ApiController info :  basePackage "  + basePackage);


        String jtzhkey = "t6kj9c07jr";
//        String jtzhadmin = configProp.getJtzhadmin();
//        log.error("jtzhkey:"+jtzhkey+" jtzhadmin:"+itzhadmin);

        TenantRpcContext.setTargetTenantKey(jtzhkey);
//        TenantRpcContext.setTargetEmployeeId(jtzhadmin);
        Map<String ,String > map = new HashMap<>();
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);

        /**
         * 外部数据源 查询大数据
         */
//        String sql = "SELECT CASE  WHEN status = 1 THEN id ELSE activewfid END AS workflowid FROM e10_core_business.dbo.wfp_base WHERE id like '%00004537' AND  delete_type = 0 AND  tenant_key = 't6kj9c07jr'";
//        TenantRpcContext.setTargetTenantKey("t6kj9c07jr");
//        rs.setTenantKey("t6kj9c07jr");
//        String poolname ="E10JTZH";
//        logger.error("sql == " +sql);
//        logger.error("poolname == " +poolname);
//        rs.executeQuery(sql,poolname);
//        if(rs.next()){
//            map.put("workflowid" , rs.getString("workflowid"));
//        }
//        logger.error("map == " +map);


        /**
         * 外部数据源查询超时
         */
        String sql = "select count(1) as zs from atdpersoncardexview " +
                "where  extype = '未刷卡'  and shoulddate > '2024-12-01'  and shoulddate < '2025-02-24'";

        logger.error("sql  == " +sql);
        boolean b1 = rs.executeQuery(sql, "hr");

        logger.error("b1 == " +  b1);
        logger.error("getExecuteResult == " +rs.getExecuteResult());

        if(rs.next()){
            logger.error("zs  == " +rs.getString("zs"));
            map.put("zs", rs.getString("zs"));
        }


//        logger.error("ApiController info :  hello "  );
//        final User currentUser = UserContext.getCurrentUser();
//        //final Tenant currentTenant = TenantContext.getCurrentTenant();
//        final Long employeeId = currentUser.getEmployeeId();//用户
//
//
//        logger.error("ApiController info :  employeeId = " + employeeId );
//        logger.error("ApiController info :  employeeId = " + employeeId );
//        final String tenantKey = currentUser.getTenantKey();//租户
//
//        logger.error("ApiController info : tenantKey= " + tenantKey );
//        logger.error("ApiController info : tenantKey= " + tenantKey );


        return WeaResult.success(map.toString());
    }


    @GetMapping("/sendmes")
    public WeaResult<String> sendmes(@RequestParam("send") String send , @RequestParam("recive") String recive) {
        sendcusmes(send, recive);
        return WeaResult.success("消息已发送");
    }
    private static void sendcusmes(String send, String recive){

        String corpId = "9d18deb9bbeb98f7a2402808f8bb8ce8";
        String host = "http://10.6.24.64:20600";
        String appKey = "179a9854c471d161db69ec9f16c6e1e";
        String app_secret = "9aa17e9391d8fdf4be44f78e2a26be30";

        CodeParam codeParam = new CodeParam(corpId, "code", "xxx");
        Code code = AuthService.getAuthCode(codeParam, host, null);
        logger.error(" sendcusmes code == "+code.getCode());

        AccessTokenParam tokenParam = new AccessTokenParam(appKey, app_secret, "authorization_code", code.getCode());
        AccessToken token = AuthService.getAuthAccessToken(tokenParam, host, null);
        logger.error(" sendcusmes token == "+token.getAccessToken());

        MessageVo messageVo = new MessageVo();
        messageVo.setAccessToken(token.getAccessToken());
        messageVo.setText("sdk test msg send");
        messageVo.setTitle("sdk aaaaaa");

        // 定义消息发送者
        MessageSender messageSender = new MessageSender(send, "t6kj9c07jr", "sdk小助手");
        messageVo.setSender(messageSender);
        messageVo.setEventId(8);
        messageVo.setModuleId(111);

        // 定义消息接收者
        List<MessageReciver> reciverList = new ArrayList<>();
        MessageReciver messageReciver = new MessageReciver(recive, "t6kj9c07jr");
        reciverList.add(messageReciver);
        messageVo.setRecivers(reciverList);

        // 定义事项
        MessageEntity messageEntity = new MessageEntity("123", "third eneity name", "https://127.0.0.1:1000/aaaa", "https://127.0.0.1:1000/h5/aaa");
        messageVo.setEntity(messageEntity);

        ApiResult<String> normalRes = MessageService.sendMsg(messageVo, host, null);
        System.out.println(JSONObject.toJSONString(normalRes));
        System.out.println(normalRes.getData());
    }


}
