package com.yunzhupaas.scheduletask.task;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.base.entity.DataInterfaceEntity;
import com.yunzhupaas.base.service.DataInterfaceService;
import com.yunzhupaas.base.service.DbLinkService;
import com.yunzhupaas.database.util.TenantDataSourceUtil;
import com.yunzhupaas.emnus.TemplateEnum;
import com.yunzhupaas.exception.TenantInvalidException;
import com.yunzhupaas.model.visualJson.TemplateJsonModel;
import com.yunzhupaas.scheduletask.entity.TimeTaskEntity;
import com.yunzhupaas.scheduletask.model.ContentNewModel;
import com.yunzhupaas.scheduletask.model.UpdateTaskModel;
import com.yunzhupaas.scheduletask.rest.RestScheduleTaskUtil;
import com.yunzhupaas.util.AuthUtil;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Api和数据接口使用
 *
 * @author ：云筑产品开发平台组
 * @version: V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date ：2022/3/23 9:25
 */
@Slf4j
@Component
public class ScheduleTaskHandler {

    @Autowired
    private DataInterfaceService dataInterfaceService;
    @Autowired
    private DbLinkService dbLinkService;

    @XxlJob("defaultHandler")
    public void defaultHandler() {
        // 获取参数
        String param = XxlJobHelper.getJobParam();
        // 转换成模型
        TimeTaskEntity entity = JsonUtil.getJsonToBean(param, TimeTaskEntity.class);
        ContentNewModel model = JsonUtil.getJsonToBean(param, ContentNewModel.class);
        String tenantId = StringUtil.isNotEmpty(model.getUserInfo().getTenantId()) ? model.getUserInfo().getTenantId() : "";
        String userId = StringUtil.isNotEmpty(model.getUserInfo().getUserId()) ? model.getUserInfo().getUserId() : "";
        String token = AuthUtil.loginTempUser(userId, tenantId, true);

        // 切换租户
        UserInfo userInfo = model.getUserInfo();
        // 切换数据源
        if (userInfo != null && StringUtil.isNotEmpty(userInfo.getTenantId())) {
            try {
                TenantDataSourceUtil.switchTenant(userInfo.getTenantId());
            }catch (TenantInvalidException e){
                // 租户无效 禁用任务
                log.error("ScheduleTaskHandler, 租户无效, 禁用任务：{}", userInfo.getTenantId());
                entity = RestScheduleTaskUtil.getInfo(entity.getId(), model.getUserInfo());
                entity.setEnabledMark(0);
                UpdateTaskModel updateTaskModel = new UpdateTaskModel();
                updateTaskModel.setEntity(entity);
                updateTaskModel.setUserInfo(model.getUserInfo());
                RestScheduleTaskUtil.updateTask(updateTaskModel);
            }
        }
        // 如果是http
        if ("1".equals(entity.getExecuteType())) {
            Boolean callHttp = callHttp(model, token);
//            if (callHttp) {
//                XxlJobHelper.handleResult(ReturnT.SUCCESS_CODE, "调用成功");
//            } else {
//                XxlJobHelper.handleResult(ReturnT.FAIL_CODE, "调用失败");
//            }
        } else if ("2".equals(entity.getExecuteType())) {
            boolean callSql = callSql(model, token);
//            if ( callSql) {
//                XxlJobHelper.handleResult(ReturnT.SUCCESS_CODE, "调用成功");
//            } else {
//                XxlJobHelper.handleResult(ReturnT.FAIL_CODE, "调用失败");
//            }
        }
    }

    // ---------------START callSQL

    /**
     * 调用SQL
     *
     * @param model 系统调度参数
     */
    private boolean callSql(ContentNewModel model, String token) {
        try {
            // 得到数据接口信息
            String tenantId = StringUtil.isNotEmpty(model.getUserInfo().getTenantId()) ? model.getUserInfo().getTenantId() : "0";
            DataInterfaceEntity entity = dataInterfaceService.getInfo(model.getInterfaceId());
            if (entity != null) {
                Map<String, String> map = null;
                if (model.getParameter() != null && model.getParameter().size() > 0) {
                    map = new HashMap<>(16);
                    for (TemplateJsonModel parameterModel : model.getParameter()) {
                        String value = Objects.equals(parameterModel.getSourceType(), TemplateEnum.Empty.getCode()) ? "" : parameterModel.getRelationField();
                        map.put(parameterModel.getField(), value);
                    }
                }
                dataInterfaceService.infoToId(entity.getId(), tenantId, map, token, null, null, null, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // ---------------START callHttp

    /**
     * HTTP调用
     *
     * @param model 系统调度参数
     * @return
     */
    private Boolean callHttp(ContentNewModel model, String token) {
        try {
            // 得到数据接口信息
            String tenantId = StringUtil.isNotEmpty(model.getUserInfo().getTenantId()) ? model.getUserInfo().getTenantId() : "0";
            DataInterfaceEntity entity = dataInterfaceService.getInfo(model.getInterfaceId());
            if (entity != null) {
                Map<String, String> map = null;
                if (model.getParameter() != null && model.getParameter().size() > 0) {
                    map = new HashMap<>(16);
                    for (TemplateJsonModel parameterModel : model.getParameter()) {
                        String value = Objects.equals(parameterModel.getSourceType(), TemplateEnum.Empty.getCode()) ? "" : parameterModel.getRelationField();
                        map.put(parameterModel.getField(), value);
                    }
                }
                dataInterfaceService.infoToId(entity.getId(), tenantId, map, token, null, null, null, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}

