package com.cool.modules.dingtalk.controller.admin;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cool.core.annotation.CoolRestController;
import com.cool.core.base.BaseController;
import com.cool.core.request.R;
import com.cool.modules.dingtalk.entity.DingtalkSyncLogEntity;
import com.cool.modules.dingtalk.service.DingtalkSyncLogService;
import com.cool.modules.dingtalk.service.DingtalkSyncService;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import static com.cool.modules.dingtalk.entity.table.DingtalkSyncLogEntityTableDef.DINGTALK_SYNC_LOG_ENTITY;

/**
 * 钉钉同步管理Controller
 */
@Slf4j
@Tag(name = "钉钉同步", description = "钉钉同步管理")
@CoolRestController(api = {"page", "info"})
@RequiredArgsConstructor
public class AdminDingtalkSyncController extends BaseController<DingtalkSyncLogService, DingtalkSyncLogEntity> {

    private final DingtalkSyncService dingtalkSyncService;

    @Override
    protected void init(HttpServletRequest request, JSONObject requestParams) {
        log.info("【钉钉同步日志Controller】接收到分页请求参数: {}", requestParams);

        // 构建查询条件
        QueryWrapper qw = QueryWrapper.create()
                .orderBy(DINGTALK_SYNC_LOG_ENTITY.CREATE_TIME, false);

        // 手动处理筛选条件
        if (requestParams.containsKey("syncType")) {
            Integer syncType = requestParams.getInt("syncType");
            log.info("【钉钉同步日志Controller】添加syncType筛选条件: {}", syncType);
            qw.and(DINGTALK_SYNC_LOG_ENTITY.SYNC_TYPE.eq(syncType));
        }

        if (requestParams.containsKey("syncStatus")) {
            Integer syncStatus = requestParams.getInt("syncStatus");
            log.info("【钉钉同步日志Controller】添加syncStatus筛选条件: {}", syncStatus);
            qw.and(DINGTALK_SYNC_LOG_ENTITY.SYNC_STATUS.eq(syncStatus));
        }

        setPageOption(createOp().queryWrapper(qw));

        log.info("【钉钉同步日志Controller】查询条件构建完成");
    }

    @Operation(summary = "手动触发同步", description = "手动触发钉钉组织架构同步")
    @PostMapping("/trigger")
    public R triggerSync() {
        log.info("【钉钉同步Controller】手动触发同步");

        try {
            // 执行同步（类型为手动：0）异步执行
            dingtalkSyncService.syncAll(0);

            log.info("【钉钉同步Controller】同步任务已启动");
            return R.ok("同步任务已启动，请稍后查看同步日志");

        } catch (Exception e) {
            log.error("【钉钉同步Controller】触发同步失败", e);
            return R.error("触发同步失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取同步状态", description = "检查当前同步任务状态")
    @GetMapping("/status")
    public R getSyncStatus() {
        log.info("【钉钉同步Controller】获取同步状态");

        try {
            JSONObject status = dingtalkSyncService.checkSyncStatus();
            log.info("【钉钉同步Controller】同步状态: {}", status);
            return R.ok(status);
        } catch (Exception e) {
            log.error("【钉钉同步Controller】获取同步状态失败", e);
            return R.error("获取同步状态失败: " + e.getMessage());
        }
    }
}
