package com.zhyc.module.base.controller;

import com.github.pagehelper.PageHelper;
import com.zhyc.common.annotation.Log;
import com.zhyc.common.core.controller.BaseController;
import com.zhyc.common.core.domain.AjaxResult;
import com.zhyc.common.core.page.TableDataInfo;
import com.zhyc.common.core.text.Convert;
import com.zhyc.common.enums.BusinessType;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.module.base.domain.SheepFile;
import com.zhyc.module.base.service.ISheepFileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 羊只档案Controller
 * * @author wyt
 * @date 2025-07-13
 */
@RestController
@RequestMapping("/sheep_file/sheep_file")
public class SheepFileController extends BaseController
{
    @Autowired
    private ISheepFileService sheepFileService;

    /**
     * 查询羊只档案列表
     */
    @PreAuthorize("@ss.hasPermi('sheep_file:sheep_file:list')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody(required = false) Map<String, Object> queryParams, HttpServletRequest request)
    {
        // 解析查询参数
        SheepFile sheepFile = new SheepFile();
        Map<String, Object> customParams = new HashMap<>();

        // 提取分页参数
        Integer pageNum = 1;
        Integer pageSize = 10;

        if (queryParams != null && !queryParams.isEmpty()) {
            // ------------------ 1. 处理分页参数 ------------------
            if (queryParams.containsKey("pageNum") && queryParams.get("pageNum") != null) {
                try {
                    pageNum = Integer.parseInt(queryParams.get("pageNum").toString());
                } catch (NumberFormatException e) {
                    // 使用默认值
                }
            } else if (queryParams.containsKey("page") && queryParams.get("page") != null) {
                try {
                    pageNum = Integer.parseInt(queryParams.get("page").toString());
                } catch (NumberFormatException e) {
                    // 使用默认值
                }
            }

            if (queryParams.containsKey("pageSize") && queryParams.get("pageSize") != null) {
                try {
                    pageSize = Integer.parseInt(queryParams.get("pageSize").toString());
                } catch (NumberFormatException e) {
                    // 使用默认值
                }
            } else if (queryParams.containsKey("limit") && queryParams.get("limit") != null) {
                try {
                    pageSize = Integer.parseInt(queryParams.get("limit").toString());
                } catch (NumberFormatException e) {
                    // 使用默认值
                }
            }

            // ------------------ 2. 核心修复：处理 List 多选参数 ------------------
            // 使用 parseList 方法兼容处理 List、Array、逗号分隔字符串
            sheepFile.setAllEarNumbers(parseList(queryParams.get("allEarNumbers")));
            sheepFile.setAllEleEarNumbers(parseList(queryParams.get("allEleEarNumbers")));
            sheepFile.setAllBreedingStatus(parseList(queryParams.get("allBreedingStatus")));
            sheepFile.setAllSheepTypes(parseList(queryParams.get("allSheepTypes")));

            // 性别处理 (需要将 String/Integer 转为 Long)
            List<String> genderStrs = parseList(queryParams.get("allGenders"));
            if (genderStrs != null && !genderStrs.isEmpty()) {
                List<Long> genderLongs = new ArrayList<>();
                for (String s : genderStrs) {
                    Long v = convertToLong(s);
                    if(v != null) genderLongs.add(v);
                }
                sheepFile.setAllGenders(genderLongs);
            }

            // ------------------ 3. 处理常规单值参数 ------------------
            if (queryParams.containsKey("bsManageTags") && queryParams.get("bsManageTags") != null) {
                sheepFile.setBsManageTags(queryParams.get("bsManageTags").toString());
            }
            if (queryParams.containsKey("electronicTags") && queryParams.get("electronicTags") != null) {
                sheepFile.setElectronicTags(queryParams.get("electronicTags").toString());
            }
            if (queryParams.containsKey("drRanch") && queryParams.get("drRanch") != null) {
                sheepFile.setDrRanch(queryParams.get("drRanch").toString());
            }
            if (queryParams.containsKey("variety") && queryParams.get("variety") != null) {
                sheepFile.setVariety(queryParams.get("variety").toString());
            }
            if (queryParams.containsKey("name") && queryParams.get("name") != null) {
                sheepFile.setName(queryParams.get("name").toString());
            }
            if (queryParams.containsKey("gender") && queryParams.get("gender") != null) {
                sheepFile.setGender(convertToLong(queryParams.get("gender")));
            }
            if (queryParams.containsKey("statusId") && queryParams.get("statusId") != null) {
                sheepFile.setStatusId(convertToLong(queryParams.get("statusId")));
            }
            if (queryParams.containsKey("breed") && queryParams.get("breed") != null) {
                sheepFile.setBreed(queryParams.get("breed").toString());
            }

            // ------------------ 4. 提取自定义参数 (排除已处理的键) ------------------
            // 定义需要跳过的key，防止重复处理
            Set<String> processedKeys = new HashSet<>(Arrays.asList(
                    "pageNum", "pageSize", "page", "limit",
                    "bsManageTags", "electronicTags", "drRanch", "variety", "name", "gender", "statusId", "breed",
                    "allEarNumbers", "allEleEarNumbers", "allGenders", "allBreedingStatus", "allSheepTypes"
            ));

            for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
                if (!processedKeys.contains(entry.getKey()) && entry.getValue() != null) {
                    customParams.put(entry.getKey(), entry.getValue());
                }
            }
        }

        // 使用自定义分页参数
        PageHelper.startPage(pageNum, pageSize);

        // 调用支持复杂查询的Service方法
        List<SheepFile> list = sheepFileService.selectSheepFileListByCondition(customParams, sheepFile);

        return getDataTable(list);
    }

    /**
     * 辅助方法：统一解析各种格式的数组参数
     * 支持：List, String[] (数组), Object[] (数组), "A,B" (逗号分隔字符串)
     */
    private List<String> parseList(Object obj) {
        if (obj == null) return null;
        List<String> result = new ArrayList<>();

        if (obj instanceof List) {
            // JSON 传来的通常是 List
            for (Object o : (List<?>) obj) {
                if (o != null) result.add(o.toString());
            }
        } else if (obj.getClass().isArray()) {
            // 如果是数组
            if (obj instanceof Object[]) {
                for (Object o : (Object[]) obj) {
                    if (o != null) result.add(o.toString());
                }
            } else if (obj instanceof String[]) {
                Collections.addAll(result, (String[]) obj);
            }
        } else if (obj instanceof String) {
            // 如果是逗号分隔字符串
            String s = (String) obj;
            if (StringUtils.isNotBlank(s)) {
                String[] split = s.split(",");
                Collections.addAll(result, split);
            }
        }

        return result.isEmpty() ? null : result;
    }

    /**
     * 转换对象为Long类型
     */
    private Long convertToLong(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof Long) {
            return (Long) obj;
        }
        if (obj instanceof Integer) {
            return ((Integer) obj).longValue();
        }
        if (obj instanceof String) {
            try {
                return Long.parseLong((String) obj);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 导出羊只档案列表
     */
    @PreAuthorize("@ss.hasPermi('sheep_file:sheep_file:export')")
    @Log(title = "羊只档案", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HttpServletRequest request)
    {
        // 构建查询条件对象
        SheepFile sheepFile = new SheepFile();
        Map<String, Object> customParams = new HashMap<>();

        // 解析所有请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();

        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();

            if (values != null && values.length > 0 && StringUtils.isNotBlank(values[0])) {
                String value = values[0];

                // 使用若依框架的工具方法处理参数
                switch (key) {
                    // --- 单值参数 ---
                    case "bsManageTags":
                        sheepFile.setBsManageTags(convertToString(value));
                        break;
                    case "electronicTags":
                        sheepFile.setElectronicTags(convertToString(value));
                        break;
                    case "drRanch":
                        sheepFile.setDrRanch(convertToString(value));
                        break;
                    case "variety":
                        sheepFile.setVariety(convertToString(value));
                        break;
                    case "name":
                        sheepFile.setName(convertToString(value));
                        break;
                    case "gender":
                        sheepFile.setGender(Convert.toLong(value));
                        break;
                    case "statusId":
                        sheepFile.setStatusId(Convert.toLong(value));
                        break;
                    case "breed":
                        sheepFile.setBreed(convertToString(value));
                        break;

                    // --- 新增：处理多选数组参数 ---
                    // request.getParameterMap 中的值本身就是 String[]，可以直接使用
                    case "allEarNumbers":
                        sheepFile.setAllEarNumbers(new ArrayList<>(Arrays.asList(values)));
                        break;
                    case "allEleEarNumbers":
                        sheepFile.setAllEleEarNumbers(new ArrayList<>(Arrays.asList(values)));
                        break;
                    case "allBreedingStatus":
                        sheepFile.setAllBreedingStatus(new ArrayList<>(Arrays.asList(values)));
                        break;
                    case "allSheepTypes":
                        sheepFile.setAllSheepTypes(new ArrayList<>(Arrays.asList(values)));
                        break;
                    case "allGenders":
                        List<Long> genderList = new ArrayList<>();
                        for(String v : values){
                            Long l = Convert.toLong(v);
                            if(l != null) genderList.add(l);
                        }
                        sheepFile.setAllGenders(genderList);
                        break;

                    case "pageNum":
                    case "pageSize":
                        // 忽略分页参数
                        break;
                    default:
                        // 自定义参数
                        customParams.put(key, value);
                        break;
                }
            }
        }

        // 调用Service获取数据
        List<SheepFile> list = sheepFileService.selectSheepFileListByCondition(customParams, sheepFile);

        // 使用若依框架的Excel工具类导出
        ExcelUtil<SheepFile> util = new ExcelUtil<>(SheepFile.class);
        util.exportExcel(response, list, "羊只档案数据");
    }

    /**
     * 新增：模糊搜索耳号接口 (用于前端下拉框远程搜索)
     */
    @GetMapping("/searchEarNumbers")
    public AjaxResult searchEarNumbers(@RequestParam("query") String query)
    {
        return success(sheepFileService.searchEarNumbers(query));
    }

    /**
     * 字符串转换工具方法
     */
    private String convertToString(Object value) {
        if (value == null) {
            return null;
        }
        return value.toString().trim();
    }

    /**
     * 获取羊只档案详细信息
     */
    @PreAuthorize("@ss.hasPermi('sheep_file:sheep_file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sheepFileService.selectSheepFileById(id));
    }

    /*
     * 根据耳号查询是否存在羊舍
     * */
    @GetMapping("/byNo/{manageTags}")
    public AjaxResult byManageTags(@PathVariable String manageTags){
        SheepFile sheep=sheepFileService.selectBasSheepByManageTags(manageTags.trim());
        return success(sheep);
    }

    @GetMapping("/stat/sheepType")
    public AjaxResult statSheepType() {
        return success(sheepFileService.countBySheepType());
    }

    @GetMapping("/stat/breedStatus")
    public AjaxResult statBreedStatus() {
        return success(sheepFileService.countByBreedStatus());
    }

    @GetMapping("/stat/variety")
    public AjaxResult statVariety() {
        return success(sheepFileService.countByVariety());
    }

    @GetMapping("/stat/lactationParity")
    public AjaxResult statLactationParity() {
        return success(sheepFileService.countParityOfLactation());
    }

    // 在群总数
    @GetMapping("/stat/inGroupCount")
    public AjaxResult inGroupCount() {
        return success(sheepFileService.countInGroup());
    }

    /**
     * 新增API：获取字段的唯一值列表
     */
    @GetMapping("/field/{fieldName}")
    public AjaxResult getFieldValues(@PathVariable String fieldName) {
        try {
            // 调用Service层获取字段唯一值
            List<String> fieldValues = sheepFileService.getFieldValues(fieldName);
            return AjaxResult.success("获取字段值成功", fieldValues);
        } catch (IllegalArgumentException e) {
            return AjaxResult.error("请求的字段名不合法: " + e.getMessage());
        } catch (Exception e) {
            logger.error("获取字段值失败，字段名: " + fieldName, e);
            return AjaxResult.error("系统错误，获取字段值失败");
        }
    }
}