package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.ErpShop;
import com.haha.service.ErpShopService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

/**
 * ERP 店铺管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/erp-shops")
@RequiredArgsConstructor
public class ErpShopController {

    private final ErpShopService erpShopService;

    /**
     * 从 ERP 同步店铺数据
     */
    @RequirePermission("erp:shop:sync")
    @Log(module = "ERP店铺管理", operation = OperationType.SYNC, summary = "同步ERP店铺数据")
    @PostMapping("/sync")
    public Result<Void> syncFromErp() {
        erpShopService.syncFromErp();
        return Result.success("同步任务已启动，正在后台执行，请稍后刷新查看结果");
    }

    /**
     * 分页查询已缓存的 ERP 店铺列表
     */
    @RequirePermission("erp:shop:read")
    @GetMapping
    public Result<PageResult<ErpShop>> list(@RequestParam(required = false) String keyword,
                                             @RequestParam(required = false) Integer boundStatus,
                                             @RequestParam(required = false) Integer bindEnabled,
                                             @RequestParam(defaultValue = "1") int page,
                                             @RequestParam(defaultValue = "10") int pageSize) {
        IPage<ErpShop> pageResult = erpShopService.listAll(keyword, boundStatus, bindEnabled, page, pageSize);
        return Result.success("查询成功", PageResult.of(pageResult));
    }

    /**
     * 绑定设备与 ERP 店铺
     */
    @RequirePermission("erp:shop:bind")
    @Log(module = "ERP店铺管理", operation = OperationType.UPDATE, summary = "绑定ERP店铺")
    @PostMapping("/bind")
    public Result<Void> bind(@RequestBody Map<String, Object> params) {
        Long deviceId = toLong(params.get("deviceId"));
        Long erpShopId = toLong(params.get("erpShopId"));
        if (deviceId == null || erpShopId == null) {
            return Result.error("deviceId 和 erpShopId 不能为空");
        }
        erpShopService.bindDevice(deviceId, erpShopId);
        return Result.success("绑定成功");
    }

    /**
     * 解除绑定
     */
    @RequirePermission("erp:shop:bind")
    @Log(module = "ERP店铺管理", operation = OperationType.UPDATE, summary = "解绑ERP店铺")
    @PostMapping("/unbind")
    public Result<Void> unbind(@RequestBody Map<String, Object> params) {
        Long deviceId = toLong(params.get("deviceId"));
        if (deviceId == null) {
            return Result.error("deviceId 不能为空");
        }
        erpShopService.unbindDevice(deviceId);
        return Result.success("解绑成功");
    }

    /** Long 精度统一处理：前端可能传 Number 或 String */
    private Long toLong(Object val) {
        if (val == null) return null;
        if (val instanceof Number) return ((Number) val).longValue();
        return Long.parseLong(val.toString());
    }

    /**
     * 批量修改允许绑定标识
     */
    @RequirePermission("erp:shop:bind")
    @Log(module = "ERP店铺管理", operation = OperationType.UPDATE, summary = "批量修改允许绑定标识")
    @PostMapping("/batch-bind-enabled")
    public Result<Integer> batchUpdateBindEnabled(@RequestBody Map<String, Object> params) {
        // erpShopId 是 Long 类型，前端 JSON 可能以字符串传递（精度问题），统一转 Long
        @SuppressWarnings("unchecked")
        List<Long> erpShopIds = ((List<?>) params.get("erpShopIds")).stream()
                .map(o -> o instanceof Number ? ((Number) o).longValue() : Long.parseLong(o.toString()))
                .toList();
        Integer bindEnabled = (Integer) params.get("bindEnabled");
        if (erpShopIds == null || erpShopIds.isEmpty() || bindEnabled == null) {
            return Result.error("参数不能为空");
        }
        int count = erpShopService.batchUpdateBindEnabled(erpShopIds, bindEnabled);
        return Result.success("已更新 " + count + " 个店铺", count);
    }

    /**
     * 一键解绑所有设备：将所有设备的 ERP 店铺绑定全部清除
     */
    @RequirePermission("erp:shop:bind")
    @Log(module = "ERP店铺管理", operation = OperationType.UPDATE, summary = "一键解绑所有ERP店铺")
    @PostMapping("/unbind-all")
    public Result<Integer> unbindAll() {
        int count = erpShopService.unbindAll();
        return Result.success("已解绑 " + count + " 台设备", count);
    }

    /**
     * 一键自动绑定：按 shopCode 匹配设备 deviceId
     */
    @RequirePermission("erp:shop:bind")
    @Log(module = "ERP店铺管理", operation = OperationType.UPDATE, summary = "一键自动绑定ERP店铺")
    @PostMapping("/auto-bind")
    public Result<Map<String, Integer>> autoBind() {
        Map<String, Integer> result = erpShopService.autoBind();
        return Result.success(String.format("绑定 %d 台，跳过 %d 台",
                result.get("bound"), result.get("skipped")), result);
    }
}
