package com.gxwebsoft.led.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.led.param.BmeNumberSourcesParam;
import com.gxwebsoft.led.param.BmeStopReplaceParam;
import com.gxwebsoft.led.service.LedScheduleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Optional;

@Tag(name = "LED-排班接口")
@RestController
@RequestMapping("/api/led/bme")
public class LedApiController extends BaseController {

  @Resource
  private LedScheduleService ledScheduleService;

  @Operation(summary = "查询一周内停替诊医生排班信息（10017）")
  @PostMapping("/stop-replace")
  public ApiResult<Object> searchStopAndReplace(@RequestBody BmeStopReplaceParam param) {
    return success(extractScheduleData(ledScheduleService.searchStopAndReplace(param)));
  }

  @Operation(summary = "查询医生排班信息当日剩余号源（10018）")
  @PostMapping("/number-sources")
  public ApiResult<Object> searchNumberSources(@RequestBody BmeNumberSourcesParam param) {
    return success(extractScheduleData(ledScheduleService.searchNumberSources(param)));
  }

  /**
   * 将中台层层嵌套的响应简化为单层：tid、resultCode/resultMsg、data（主要数据）。
   */
  private JSONObject flattenScheduleResponse(JSONObject raw) {
    JSONObject current = Optional.ofNullable(raw).orElseGet(JSONObject::new);
    String tid = current.getString("tid");

    // 下钻 data 层级
    while (current.getJSONObject("data") != null) {
      current = current.getJSONObject("data");
      if (current.containsKey("tid")) {
        tid = current.getString("tid");
      }
    }

    JSONObject result = new JSONObject();
    result.put("tid", tid);
    result.put("resultCode", firstNonEmpty(current.getString("resultCode"), current.getString("code")));
    result.put("resultMsg", firstNonEmpty(current.getString("resultMsg"), current.getString("msg")));

    // 主体数据：优先 dataList.data，其次 data
    if (current.containsKey("dataList") && current.getJSONObject("dataList") != null) {
      result.put("data", current.getJSONObject("dataList").get("data"));
    } else if (current.containsKey("data")) {
      result.put("data", current.get("data"));
    } else {
      result.put("data", current);
    }
    return result;
  }

  /**
   * 直接返回核心数据字段（即扁平化后的 result.data）。
   */
  private Object extractScheduleData(JSONObject raw) {
    JSONObject flattened = flattenScheduleResponse(raw);
    return flattened.get("data");
  }

  private String firstNonEmpty(String... values) {
    for (String v : values) {
      if (v != null && !v.isEmpty()) {
        return v;
      }
    }
    return "";
  }
}
