package com.ruoyi.tjfx.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.tjfx.common.ApiResponse;
import com.ruoyi.tjfx.common.PageResponse;
import com.ruoyi.tjfx.entity.ShopCustomer;
import com.ruoyi.tjfx.service.ShopCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SaIgnore
@Slf4j
@RestController
@RequestMapping("/shop-customer")
public class ShopCustomerController {

    @Autowired
    private ShopCustomerService shopCustomerService;

/*    @GetMapping
    public ApiResponse<List<ShopCustomer>> listAll() {
        return ApiResponse.success(shopCustomerService.listAll(), "获取成功");
    }*/

    /**
     * 分页查询店铺客户
     */
    @GetMapping()
    public ApiResponse<PageResponse<ShopCustomer>> getPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String shopName,
            @RequestParam(required = false) String customerName) {
        try {
            PageResponse<ShopCustomer> result = shopCustomerService.getPage(page, pageSize, shopName, customerName);
            return ApiResponse.success(result, "获取成功");
        } catch (Exception e) {
            log.error("获取店铺客户列表失败", e);
            return ApiResponse.error("获取店铺客户列表失败");
        }
    }

    @GetMapping("/{id}")
    public ApiResponse<ShopCustomer> getById(@PathVariable Long id) {
        ShopCustomer data = shopCustomerService.getById(id);
        if (data == null) return ApiResponse.error(404, "数据不存在");
        return ApiResponse.success(data, "获取成功");
    }

    @PostMapping
    public ApiResponse<Void> add(@RequestBody ShopCustomer shopCustomer) {
        shopCustomerService.add(shopCustomer);
        return ApiResponse.success(null, "新增成功");
    }

    @PutMapping("/{id}")
    public ApiResponse<Void> update(@PathVariable Long id, @RequestBody ShopCustomer shopCustomer) {
        shopCustomerService.update(id, shopCustomer);
        return ApiResponse.success(null, "更新成功");
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        shopCustomerService.delete(id);
        return ApiResponse.success(null, "删除成功");
    }

    @DeleteMapping("/batch/{ids}")
    public ApiResponse<Void> deleteBatch(@PathVariable String ids) {
        List<Long> idList = Arrays.stream(ids.split(","))
            .map(String::trim)
            .filter(s -> !s.isEmpty())
            .map(Long::valueOf)
            .collect(Collectors.toList());

        shopCustomerService.deleteBatch(idList);
        return ApiResponse.success(null, "批量删除成功");
    }

    @PostMapping("/import")
    public ApiResponse<?> importExcel(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ApiResponse.validationError("请选择Excel文件");
            }
            Map<String, Object> result = shopCustomerService.importExcel(file);
            int imported = (int) result.getOrDefault("imported", 0);
            int total = (int) result.getOrDefault("total", 0);
            int errors = (int) result.getOrDefault("errors", 0);
            String msg = "Excel导入完成，共处理" + total + "行，成功导入" + imported + "条";
            if (errors > 0) msg += "，跳过" + errors + "条";
            return ApiResponse.success(result, msg);
        } catch (RuntimeException e) {
            return ApiResponse.validationError(e.getMessage());
        } catch (Exception e) {
            log.error("Excel导入失败", e);
            return ApiResponse.error("Excel导入失败");
        }
    }
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        try {
            shopCustomerService.exportExcel(response);
        } catch (Exception e) {
            log.error("Excel导出失败", e);
            // 不建议再写响应体了，可能已经写入了一部分内容，会报 IllegalStateException
        }
    }
/*    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        try {
            shopCustomerService.exportExcel(response);
        } catch (RuntimeException e) {
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
            } catch (Exception ex) {
                log.error("写入错误响应失败", ex);
            }
        } catch (Exception e) {
            log.error("Excel导出失败", e);
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"Excel导出失败\"}");
            } catch (Exception ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }*/
}
