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.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.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;

/**
 * 羊只档案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()) {
            // 提取分页参数
            if (queryParams.containsKey("pageNum") && queryParams.get("pageNum") != null) {
                try {
                    pageNum = Integer.parseInt(queryParams.get("pageNum").toString());
                } catch (NumberFormatException e) {
                    // 使用默认值
                }
            }
            if (queryParams.containsKey("pageSize") && queryParams.get("pageSize") != null) {
                try {
                    pageSize = Integer.parseInt(queryParams.get("pageSize").toString());
                } catch (NumberFormatException e) {
                    // 使用默认值
                }
            }

            // 提取常规查询参数到 SheepFile 对象
            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());
            }

            // 移除已经处理的参数，剩下的作为自定义筛选参数
            for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();

                // 跳过常规参数和分页参数
                if ("bsManageTags".equals(key) || "electronicTags".equals(key) ||
                        "drRanch".equals(key) || "variety".equals(key) ||
                        "name".equals(key) || "gender".equals(key) ||
                        "statusId".equals(key) || "breed".equals(key) ||
                        "pageNum".equals(key) || "pageSize".equals(key)) {
                    continue;
                }

                // 添加到自定义参数中
                if (value != null) {
                    customParams.put(key, value);
                }
            }
        }

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

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

        return getDataTable(list);
    }
    /**
     * 转换对象为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;
                    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, "羊只档案数据");
    }


    /**
     * 字符串转换工具方法
     */
    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：获取字段的唯一值列表
     *
     * 这个API为前端自定义筛选功能提供数据支持
     * 当用户选择某个字段进行筛选时，前端调用此接口获取该字段的所有可能值
     *
     * @param fieldName 字段名（数据库列名）
     * @return AjaxResult 包含字段值列表的响应结果
     *
     * 接口地址：GET /sheep_file/sheep_file/field/{fieldName}
     *
     * 使用示例：
     * 前端请求：GET /sheep_file/sheep_file/field/bs_manage_tags
     * 后端返回：{ "code": 200, "msg": "操作成功", "data": ["AF00001", "AF00002", "AF00003"] }
     *
     * 安全说明：
     * - 使用白名单机制防止SQL注入
     * - 只有预定义的字段名可以被查询
     */
    @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("系统错误，获取字段值失败");
        }
    }

}
