package com.zhyc.module.produce.breed.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhyc.common.annotation.Log;
import com.zhyc.common.core.controller.BaseController;
import com.zhyc.common.core.domain.AjaxResult;
import com.zhyc.common.enums.BusinessType;
import com.zhyc.common.utils.StringUtils;
import com.zhyc.module.produce.breed.domain.RawSpermRecord;
import com.zhyc.module.produce.breed.service.IRawSpermRecordService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

/**
 * 采精记录Controller
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@RestController
@RequestMapping("/Sperm/Sperm")
public class RawSpermRecordController extends BaseController
{
    @Autowired
    private IRawSpermRecordService rawSpermRecordService;

    /**
     * 查询采精记录列表
     */
    @PreAuthorize("@ss.hasPermi('Sperm:Sperm:list')")
    @GetMapping("/list")
    public TableDataInfo list(RawSpermRecord rawSpermRecord)
    {
        startPage();
        List<RawSpermRecord> list = rawSpermRecordService.selectRawSpermRecordList(rawSpermRecord);
        return getDataTable(list);
    }

    /**
     * 导出采精记录列表
     */
    @PreAuthorize("@ss.hasPermi('Sperm:Sperm:export')")
    @Log(title = "采精记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RawSpermRecord rawSpermRecord)
    {
        List<RawSpermRecord> list = rawSpermRecordService.selectRawSpermRecordList(rawSpermRecord);
        ExcelUtil<RawSpermRecord> util = new ExcelUtil<RawSpermRecord>(RawSpermRecord.class);
        util.exportExcel(response, list, "采精记录数据");
    }

    /**
     * 获取采精记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('Sperm:Sperm:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(rawSpermRecordService.selectRawSpermRecordById(id));
    }

    /**
     * 新增采精记录
     */
    @PreAuthorize("@ss.hasPermi('Sperm:Sperm:add')")
    @Log(title = "采精记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RawSpermRecord rawSpermRecord)
    {
        try {
            // 验证必填字段
            if (StringUtils.isEmpty(rawSpermRecord.getManageTags())) {
                return error("耳号不能为空");
            }
            if (rawSpermRecord.getPickDate() == null) {
                return error("采精日期不能为空");
            }
            if (rawSpermRecord.getAmount() == null) {
                return error("采精量不能为空");
            }

            // 验证耳号对应的羊只是否为公羊
            Map<String, Object> sheepInfo = rawSpermRecordService.getSheepInfoByManageTags(rawSpermRecord.getManageTags());
            if (sheepInfo == null) {
                return error("未找到耳号为[" + rawSpermRecord.getManageTags() + "]的羊只信息，请检查耳号是否正确");
            }

            // 安全的类型转换
            Integer gender = convertToInteger(sheepInfo.get("gender"));
            if (gender == null || gender != 2) {
                return error("采精记录只能针对公羊，耳号[" + rawSpermRecord.getManageTags() + "]对应的羊只不是公羊");
            }

            return toAjax(rawSpermRecordService.insertRawSpermRecord(rawSpermRecord));
        } catch (Exception e) {
            logger.error("新增采精记录失败", e);
            return error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改采精记录
     */
    @PreAuthorize("@ss.hasPermi('Sperm:Sperm:edit')")
    @Log(title = "采精记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RawSpermRecord rawSpermRecord)
    {
        try {
            // 如果修改了耳号，需要重新验证
            if (StringUtils.isNotEmpty(rawSpermRecord.getManageTags())) {
                Map<String, Object> sheepInfo = rawSpermRecordService.getSheepInfoByManageTags(rawSpermRecord.getManageTags());
                if (sheepInfo == null) {
                    return error("未找到耳号为[" + rawSpermRecord.getManageTags() + "]的羊只信息，请检查耳号是否正确");
                }

                // 安全的类型转换
                Integer gender = convertToInteger(sheepInfo.get("gender"));
                if (gender == null || gender != 2) {
                    return error("采精记录只能针对公羊，耳号[" + rawSpermRecord.getManageTags() + "]对应的羊只不是公羊");
                }
            }

            return toAjax(rawSpermRecordService.updateRawSpermRecord(rawSpermRecord));
        } catch (Exception e) {
            logger.error("修改采精记录失败", e);
            return error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除采精记录
     */
    @PreAuthorize("@ss.hasPermi('Sperm:Sperm:remove')")
    @Log(title = "采精记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(rawSpermRecordService.deleteRawSpermRecordByIds(ids));
    }

    /**
     * 根据耳号查询羊只信息（带性别验证）
     */
    @GetMapping("/getSheepByManageTags/{manageTags}")
    public AjaxResult getSheepByManageTags(@PathVariable("manageTags") String manageTags)
    {
        try {
            Map<String, Object> sheepInfo = rawSpermRecordService.getSheepInfoByManageTags(manageTags);
            if (sheepInfo != null) {
                // 安全的类型转换
                Integer gender = convertToInteger(sheepInfo.get("gender"));
                // 验证是否为公羊
                if (gender == null || gender != 2) {
                    return error("该耳号[" + manageTags + "]对应的羊只不是公羊，无法进行采精记录");
                }

                // 构造包含消息和数据的返回结果
                Map<String, Object> resultData = new HashMap<>();
                resultData.put("sheepInfo", sheepInfo);
                resultData.put("message", "验证通过，该羊只为公羊");
                return success(resultData);
            } else {
                return error("未找到耳号为[" + manageTags + "]的羊只信息");
            }
        } catch (Exception e) {
            logger.error("查询羊只信息失败", e);
            return error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 验证羊只是否为公羊
     */
    @GetMapping("/validateRam/{manageTags}")
    public AjaxResult validateRam(@PathVariable("manageTags") String manageTags)
    {
        try {
            boolean isRam = rawSpermRecordService.validateRamGender(manageTags);
            if (isRam) {
                return success("该羊只为公羊，可以进行采精记录");
            } else {
                return error("该羊只不是公羊，无法进行采精记录");
            }
        } catch (Exception e) {
            logger.error("验证羊只性别失败", e);
            return error("验证失败：" + e.getMessage());
        }
    }

    /**
     * 根据耳号查询羊只ID（兼容原有接口）
     */
    @GetMapping("/getSheepIdByManageTags/{manageTags}")
    public AjaxResult getSheepIdByManageTags(@PathVariable("manageTags") String manageTags)
    {
        try {
            Long sheepId = rawSpermRecordService.getSheepIdByManageTags(manageTags);
            if (sheepId != null) {
                return success(sheepId);
            } else {
                return error("未找到对应耳号的羊只信息");
            }
        } catch (Exception e) {
            logger.error("查询羊只ID失败", e);
            return error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 安全的类型转换：将Object转换为Integer
     *
     * @param obj 要转换的对象
     * @return Integer值，如果转换失败返回null
     */
    private Integer convertToInteger(Object obj) {
        if (obj == null) {
            return null;
        }

        if (obj instanceof Integer) {
            return (Integer) obj;
        } else if (obj instanceof Long) {
            Long longValue = (Long) obj;
            // 检查Long值是否在Integer范围内
            if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) {
                return longValue.intValue();
            } else {
                logger.warn("数值超出Integer范围：" + longValue);
                return null;
            }
        } else if (obj instanceof String) {
            try {
                return Integer.parseInt((String) obj);
            } catch (NumberFormatException e) {
                logger.warn("无法将字符串转换为Integer：" + obj);
                return null;
            }
        } else {
            logger.warn("无法将 " + obj.getClass().getSimpleName() + " 类型转换为Integer");
            return null;
        }
    }
}