package org.hzhub.crm.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
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.CrmSyncAlertVo;
import org.hzhub.crm.domain.vo.CrmSyncLogVo;
import org.hzhub.crm.service.CustomerSyncService;
import org.hzhub.crm.task.CustomerSyncTask;
import org.hzhub.system.domain.SysTenantCompany;
import org.hzhub.system.domain.vo.SysTenantVo;
import org.hzhub.system.service.ISysTenantService;
import org.hzhub.crm.service.TenantCompanyService;
import org.hzhub.crm.service.ErpIntegrationService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * CRM同步管理 Controller
 * 管理后台版本（需要Sa-Token权限注解）
 *
 * @author hzhub
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/sync")
public class CrmSyncController {

    private final CustomerSyncService customerSyncService;
    private final CustomerSyncTask customerSyncTask;
    private final TenantCompanyService tenantCompanyService;
    private final ErpIntegrationService erpIntegrationService;
    private final ISysTenantService sysTenantService;

    /**
     * 获取同步配置
     */
    @SaCheckPermission("crm:sync:config")
    @GetMapping("/config")
    public R<Map<String, Object>> getConfig() {
        Map<String, Object> config = new java.util.HashMap<>();
        config.put("enabled", customerSyncTask.isRunning());
        config.put("cron", customerSyncTask.getCurrentCron());
        return R.ok(config);
    }

    /**
     * 启动定时任务
     */
    @SaCheckPermission("crm:sync:config")
    @PostMapping("/start")
    public R<Void> start() {
        customerSyncTask.start();
        return R.ok();
    }

    /**
     * 停止定时任务
     */
    @SaCheckPermission("crm:sync:config")
    @PostMapping("/stop")
    public R<Void> stop() {
        customerSyncTask.stop();
        return R.ok();
    }

    /**
     * 设置Cron表达式
     */
    @SaCheckPermission("crm:sync:config")
    @PutMapping("/cron")
    public R<Void> setCron(@RequestParam String cron) {
        customerSyncTask.setCron(cron);
        return R.ok();
    }

    /**
     * 手动触发全量同步
     */
    @SaCheckPermission("crm:sync:execute")
    @PostMapping("/execute")
    public R<CrmSyncLogVo> execute() {
        CrmSyncLogVo log = new CrmSyncLogVo();
        org.hzhub.crm.domain.CrmSyncLog syncLog = customerSyncTask.executeManualSync();
        if (syncLog != null) {
            log.setId(syncLog.getId());
            log.setStatus(syncLog.getStatus());
            log.setTotalCount(syncLog.getTotalCount());
            log.setSyncedCount(syncLog.getSyncedCount());
            log.setUpdatedCount(syncLog.getUpdatedCount());
            log.setAlertCount(syncLog.getAlertCount());
            log.setErrorCount(syncLog.getErrorCount());
            log.setStartTime(syncLog.getStartTime());
            log.setEndTime(syncLog.getEndTime());
            log.setDuration(syncLog.getDuration());
        }
        return R.ok(log);
    }

    /**
     * 同步日志列表
     */
    @SaCheckPermission("crm:sync:log")
    @GetMapping("/logs")
    public TableDataInfo<CrmSyncLogVo> getLogs(PageQuery pageQuery) {
        return customerSyncService.listSyncLogs(pageQuery);
    }

    /**
     * 预警列表（全局）
     */
    @SaCheckPermission("crm:sync:alert")
    @GetMapping("/alerts")
    public TableDataInfo<CrmSyncAlertVo> getAlerts(
            @RequestParam(required = false) String status,
            PageQuery pageQuery) {
        return customerSyncService.listAlerts(status, pageQuery);
    }

    /**
     * 处理预警
     */
    @SaCheckPermission("crm:sync:alert")
    @PutMapping("/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();
    }

    /**
     * 同步统计面板数据
     */
    @SaCheckPermission("crm:sync:stats")
    @GetMapping("/stats")
    public R<Map<String, Object>> getStats() {
        return R.ok(customerSyncService.getSyncStats());
    }

    // ========== 租户-公司映射管理（全局） ==========

    /**
     * 获取租户列表（用于选择器）
     */
    @SaCheckPermission("crm:sync:company")
    @GetMapping("/tenants")
    public R<List<SysTenantVo>> getTenants() {
        return R.ok(sysTenantService.queryList(new org.hzhub.system.domain.bo.SysTenantBo()));
    }

    /**
     * 获取所有租户的ERP公司映射列表（全局管理）
     */
    @SaCheckPermission("crm:sync:company")
    @GetMapping("/tenant-companies")
    public R<List<SysTenantCompany>> getAllTenantCompanies() {
        return R.ok(tenantCompanyService.getAllTenantCompanies());
    }

    /**
     * 绑定ERP公司到租户（全局管理）
     */
    @SaCheckPermission("crm:sync:company")
    @PostMapping("/tenant-companies/bind")
    public R<Void> bindCompany(@RequestParam String tenantId,
                               @RequestParam(required = false) String tenantName,
                               @RequestParam String erpCompanyId,
                               @RequestParam(required = false) String erpCompanyName) {
        tenantCompanyService.bindCompany(tenantId, tenantName, erpCompanyId, erpCompanyName);
        return R.ok();
    }

    /**
     * 解绑ERP公司
     */
    @SaCheckPermission("crm:sync:company")
    @PostMapping("/tenant-companies/unbind/{id}")
    public R<Void> unbindCompany(@PathVariable Long id) {
        tenantCompanyService.unbindCompany(id);
        return R.ok();
    }

    /**
     * 获取ERP所有公司列表（用于选择器）
     */
    @SaCheckPermission("crm:sync:company")
    @GetMapping("/erp-companies")
    public R<List<Map<String, Object>>> getErpCompanies() {
        return R.ok(erpIntegrationService.getCompanyList());
    }
}