package org.hzhub.crm.controller;

import lombok.RequiredArgsConstructor;
import org.hzhub.common.core.domain.R;
import org.hzhub.common.mybatis.core.page.PageQuery;
import org.hzhub.common.mybatis.core.page.TableDataInfo;
import org.hzhub.crm.domain.vo.CrmDealerVo;
import org.hzhub.crm.domain.vo.CrmSyncAlertVo;
import org.hzhub.crm.domain.vo.InstantSyncResult;
import org.hzhub.crm.service.ICrmDealerService;
import org.hzhub.crm.service.CustomerSyncService;
import org.hzhub.crm.service.ErpIntegrationService;
import org.hzhub.crm.service.TenantCompanyService;
import org.hzhub.crm.domain.bo.CrmDealerBo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * CRM经销商管理 Controller
 * 员工门户版本（无需Sa-Token权限注解，权限由Gateway控制）
 *
 * 注意：Gateway已配置 /crm/** 路由并StripPrefix=1（去除/crm前缀）
 * 所以Controller使用 /dealer 路径，实际对外接口为 /crm/dealer/**
 *
 * @author hzhub
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/dealer")
public class CrmDealerController {

    private final ICrmDealerService dealerService;
    private final CustomerSyncService customerSyncService;
    private final ErpIntegrationService erpIntegrationService;
    private final TenantCompanyService tenantCompanyService;

    /**
     * 员工门户经销商选择器列表
     * 用于商机创建、商机分配等场景
     */
    @GetMapping("/portal/select")
    public R<List<CrmDealerVo>> portalSelect(@RequestParam(required = false) String keyword) {
        List<CrmDealerVo> dealerList = dealerService.selectDealerList(keyword);
        return R.ok(dealerList);
    }

    /**
     * CRM经销商分页列表
     */
    @GetMapping("/portal/list")
    public TableDataInfo<CrmDealerVo> portalList(CrmDealerBo dealer, PageQuery pageQuery) {
        return dealerService.selectPageDealerList(dealer, pageQuery);
    }

    /**
     * 获取经销商详情（含同步状态）
     */
    @GetMapping("/portal/detail/{dealerId}")
    public R<CrmDealerVo> portalDetail(@PathVariable Long dealerId) {
        CrmDealerVo dealer = dealerService.selectDealerById(dealerId);
        if (dealer != null) {
            // 检查是否有待处理预警
            List<CrmSyncAlertVo> alerts = customerSyncService.getPendingAlerts(dealerId);
            dealer.setHasPendingAlerts(!alerts.isEmpty());
        }
        return R.ok(dealer);
    }

    /**
     * ERP客户选择器数据（用于线索转化/经销商创建）
     * 只返回当前租户关联公司下的客户
     */
    @GetMapping("/portal/erp-select")
    public R<List<Map<String, Object>>> erpSelect(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {
        // 获取当前租户关联的ERP公司ID
        String companyIds = tenantCompanyService.getCompanyFilterForCurrentTenant();
        List<Map<String, Object>> customers = erpIntegrationService.getCustomerSelectList(keyword, companyIds);
        return R.ok(customers);
    }

    /**
     * 校验ERP客户编码是否存在
     */
    @GetMapping("/portal/validate-code")
    public R<Boolean> validateCustomerCode(@RequestParam String customerCode) {
        boolean valid = customerSyncService.validateCustomerCode(customerCode);
        return R.ok(valid);
    }

    /**
     * 手动同步经销商（获取ERP最新信息）
     */
    @PostMapping("/portal/sync/{dealerId}")
    public R<InstantSyncResult> manualSync(@PathVariable Long dealerId) {
        InstantSyncResult result = customerSyncService.instantSync(dealerId);
        return R.ok(result);
    }

    /**
     * 获取经销商的待处理预警列表
     */
    @GetMapping("/portal/alerts/{dealerId}")
    public R<List<CrmSyncAlertVo>> getAlerts(@PathVariable Long dealerId) {
        List<CrmSyncAlertVo> alerts = customerSyncService.getPendingAlerts(dealerId);
        return R.ok(alerts);
    }

    /**
     * 处理预警
     */
    @PutMapping("/portal/alerts/{alertId}")
    public R<Void> resolveAlert(@PathVariable Long alertId,
                                @RequestParam String action,
                                @RequestParam(required = false) String note) {
        customerSyncService.resolveAlert(alertId, action, note);
        return R.ok();
    }
}