package com.huimv.employment.controller.mp;

import com.huimv.employment.common.exception.BizException;
import com.huimv.employment.common.exception.ErrorCode;
import com.huimv.employment.common.web.R;
import com.huimv.employment.security.LoginUser;
import com.huimv.employment.security.LoginUserHolder;
import com.huimv.employment.service.draft.DraftService;
import com.huimv.employment.service.draft.dto.DraftConfirmRequest;
import com.huimv.employment.service.draft.dto.DraftConfirmResponse;
import com.huimv.employment.service.draft.dto.DraftDetailResponse;
import com.huimv.employment.service.draft.dto.DraftUpdateRequest;
import com.huimv.employment.service.draft.dto.McpDraftCalculateResponse;
import com.huimv.employment.service.registration.RegistrationBatchService;
import com.huimv.employment.service.registration.dto.RegistrationBatchDetailResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用工草稿接口（小程序 JWT 鉴权）。
 * <p>
 * AI 生成草稿后，通过 {@code GET /drafts/{id}} 查看（用工明细来自 fe_draft_work_item）、
 * {@code PUT /drafts/{id}} 编辑（草稿可不绑企业）；
 * missingFields 为空后可 {@code GET .../cost-comparison} 测算，再 {@code POST .../confirm} 确认此方案；
 * 确认后可 {@code GET .../workflow-progress} 查看办理流程与当前进度。
 * 任务发布见 {@code POST /api/v1/mp/orders/{orderId}/publish-task}。
 * </p>
 */
@RestController
@RequestMapping("/api/v1/mp/drafts")
@Tag(name = "用工草稿", description = "草稿查看（明细取自 fe_draft_work_item）、编辑、成本测算、方案确认与办理进度；按用户归属。需 JWT 鉴权")
@SecurityRequirement(name = "Authorization")
public class DraftController {

    private static final String USER_TYPE_ENTERPRISE = "enterprise";

    private final DraftService draftService;
    private final RegistrationBatchService registrationBatchService;

    public DraftController(DraftService draftService,
                           RegistrationBatchService registrationBatchService) {
        this.draftService = draftService;
        this.registrationBatchService = registrationBatchService;
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询用工草稿详情",
            description = "返回草稿主表字段及 fe_draft_work_item 用工明细；"
                    + "确认方案后额外返回 order_id / order_no、batch_id / batch_no、qr_code_url / qr_token；"
                    + "无订单或批次时对应字段为 null。仅可查询本人草稿。")
    public R<DraftDetailResponse> getDetail(@PathVariable("id") Long draftId) {
        LoginUser loginUser = requireEnterprise();
        return R.ok(draftService.getDetail(loginUser.getUserId(), draftId));
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新用工草稿",
            description = "仅 pending 状态可编辑；传需修改的字段即可。用户修改的字段会同步更新 fe_draft_field 来源为 user_input。")
    public R<DraftDetailResponse> update(@PathVariable("id") Long draftId,
                                         @Validated @RequestBody DraftUpdateRequest request) {
        LoginUser loginUser = requireEnterprise();
        return R.ok(draftService.update(loginUser.getUserId(), draftId, request));
    }

    @GetMapping("/{id}/cost-comparison")
    @Operation(summary = "成本测算（方案对比）",
            description = "要求草稿 pending 且 missingFields 为空。"
                    + "按 fe_service_plan（status=active，排除 current）及 fe_service_plan_fee_rule 预置规则测算，"
                    + "每个方案返回成本合计（总成本/劳务费/服务费/保险/税费等），"
                    + "并按 settlement_cycle（daily/weekly/monthly）分类返回人均成本、工人到手、税前收入及分项费用；"
                    + "方案含 SCHEME_A/B/C，并落库 fe_draft_cost_snapshot。")
    public R<McpDraftCalculateResponse> costComparison(@PathVariable("id") Long draftId) {
        LoginUser loginUser = requireEnterprise();
        return R.ok(draftService.calculateCostComparison(loginUser.getUserId(), draftId));
    }

    @PostMapping("/{id}/confirm")
    @Operation(summary = "确认此方案",
            description = "草稿 pending 且 missingFields 为空后调用。传入 selected_scheme_code（如 SCHEME_A）："
                    + "1）生成正式订单；2）草稿置为 confirmed；"
                    + "3）创建 fe_registration_batch 并立刻生成小程序码写入 qr_code_url；"
                    + "若尚未测算会自动先测算。")
    public R<DraftConfirmResponse> confirm(@PathVariable("id") Long draftId,
                                           @Validated @RequestBody DraftConfirmRequest request) {
        LoginUser loginUser = requireEnterprise();
        return R.ok(draftService.confirmScheme(loginUser.getUserId(), draftId, request));
    }

    @GetMapping("/{id}/workflow-progress")
    @Operation(summary = "查询草稿办理流程与当前进度",
            description = "草稿确认方案后可调用。按草稿 ID 定位订单与登记批次，返回产品六步办理流程"
                    + "（有临时工：人员登记；无临时工：临时工招聘）、内部 current_step_code、登记进度条、人数统计、人员列表与二维码等。"
                    + "仅可查询本人草稿。")
    public R<RegistrationBatchDetailResponse> workflowProgress(@PathVariable("id") Long draftId) {
        LoginUser loginUser = requireEnterprise();
        return R.ok(registrationBatchService.getDetailByDraftId(loginUser.getUserId(), draftId));
    }

    private static LoginUser requireEnterprise() {
        LoginUser loginUser = LoginUserHolder.require();
        if (!USER_TYPE_ENTERPRISE.equals(loginUser.getUserType())) {
            throw new BizException(ErrorCode.ENTERPRISE_ONLY);
        }
        return loginUser;
    }
}
