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

import java.util.List;
import java.util.Map;
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.RequestParam;
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.exception.ServiceException;
import com.zhyc.module.produce.breed.domain.ScPregnancyRecord;
import com.zhyc.module.produce.breed.service.IScPregnancyRecordService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

/**
 * 孕检记录Controller
 *
 * @author zhyc
 * @date 2025-01-21
 */
@RestController
@RequestMapping("/Pregnancy_Test/Pregnancy_Test")
public class ScPregnancyRecordController extends BaseController
{
    @Autowired
    private IScPregnancyRecordService scPregnancyRecordService;

    /**
     * 查询孕检记录列表
     */
    @PreAuthorize("@ss.hasPermi('Pregnancy_Test:Pregnancy_Test:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScPregnancyRecord scPregnancyRecord)
    {
        try {
            // 添加调试日志
            if (scPregnancyRecord.getManageTags() != null && !scPregnancyRecord.getManageTags().trim().isEmpty()) {
                logger.info("搜索耳号参数: [{}]", scPregnancyRecord.getManageTags());
                // 清理输入参数
                scPregnancyRecord.setManageTags(scPregnancyRecord.getManageTags().trim());
            }
            if (scPregnancyRecord.getTechnician() != null && !scPregnancyRecord.getTechnician().trim().isEmpty()) {
                logger.info("搜索技术员参数: [{}]", scPregnancyRecord.getTechnician());
                scPregnancyRecord.setTechnician(scPregnancyRecord.getTechnician().trim());
            }

            startPage();
            List<ScPregnancyRecord> list = scPregnancyRecordService.selectScPregnancyRecordList(scPregnancyRecord);

            logger.info("查询到孕检记录数量: {}", list.size());

            return getDataTable(list);
        } catch (Exception e) {
            logger.error("查询孕检记录列表失败", e);
            return getDataTable(new java.util.ArrayList<>());
        }
    }

    /**
     * 导出孕检记录列表
     */
    @PreAuthorize("@ss.hasPermi('Pregnancy_Test:Pregnancy_Test:export')")
    @Log(title = "孕检记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScPregnancyRecord scPregnancyRecord)
    {
        try {
            // 清理导出参数
            if (scPregnancyRecord.getManageTags() != null) {
                scPregnancyRecord.setManageTags(scPregnancyRecord.getManageTags().trim());
            }
            if (scPregnancyRecord.getTechnician() != null) {
                scPregnancyRecord.setTechnician(scPregnancyRecord.getTechnician().trim());
            }

            List<ScPregnancyRecord> list = scPregnancyRecordService.selectScPregnancyRecordList(scPregnancyRecord);
            ExcelUtil<ScPregnancyRecord> util = new ExcelUtil<ScPregnancyRecord>(ScPregnancyRecord.class);
            util.exportExcel(response, list, "孕检记录数据");
        } catch (Exception e) {
            logger.error("导出孕检记录失败", e);
        }
    }

    /**
     * 获取孕检记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('Pregnancy_Test:Pregnancy_Test:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        try {
            if (id == null) {
                return error("记录ID不能为空");
            }

            ScPregnancyRecord result = scPregnancyRecordService.selectScPregnancyRecordById(id);
            if (result == null) {
                return error("记录不存在");
            }

            return success(result);
        } catch (Exception e) {
            logger.error("获取孕检记录详细信息失败，ID: " + id, e);
            return error("获取记录详细信息失败: " + e.getMessage());
        }
    }

    /**
     * 新增孕检记录
     */
    @PreAuthorize("@ss.hasPermi('Pregnancy_Test:Pregnancy_Test:add')")
    @Log(title = "孕检记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScPregnancyRecord scPregnancyRecord)
    {
        try {
            // 基础参数校验
            if (scPregnancyRecord == null) {
                return error("请求参数不能为空");
            }

            if (scPregnancyRecord.getManageTags() == null || scPregnancyRecord.getManageTags().trim().isEmpty()) {
                return error("管理耳号不能为空");
            }

            if (scPregnancyRecord.getDatetime() == null) {
                return error("孕检日期不能为空");
            }

            if (scPregnancyRecord.getResult() == null || scPregnancyRecord.getResult().trim().isEmpty()) {
                return error("孕检结果不能为空");
            }

            if (scPregnancyRecord.getTechnician() == null || scPregnancyRecord.getTechnician().trim().isEmpty()) {
                return error("技术员不能为空");
            }

            // 清理输入参数
            scPregnancyRecord.setManageTags(scPregnancyRecord.getManageTags().trim());
            scPregnancyRecord.setResult(scPregnancyRecord.getResult().trim());
            scPregnancyRecord.setTechnician(scPregnancyRecord.getTechnician().trim());

            if (scPregnancyRecord.getRemark() != null) {
                scPregnancyRecord.setRemark(scPregnancyRecord.getRemark().trim());
            }

            // 如果孕检方式为空，默认设置为B超
            if (scPregnancyRecord.getWay() == null || scPregnancyRecord.getWay().trim().isEmpty()) {
                scPregnancyRecord.setWay("B超");
            }

            logger.info("新增孕检记录，耳号: {}, 结果: {}", scPregnancyRecord.getManageTags(), scPregnancyRecord.getResult());

            int result = scPregnancyRecordService.insertScPregnancyRecord(scPregnancyRecord);
            if (result > 0) {
                logger.info("新增孕检记录成功，记录ID: {}", scPregnancyRecord.getId());
                return success("新增成功");
            } else {
                return error("新增失败");
            }
        } catch (ServiceException e) {
            logger.warn("新增孕检记录业务异常: " + e.getMessage());
            return error(e.getMessage());
        } catch (Exception e) {
            logger.error("新增孕检记录失败", e);
            return error("新增失败: " + e.getMessage());
        }
    }

    /**
     * 修改孕检记录
     */
    @PreAuthorize("@ss.hasPermi('Pregnancy_Test:Pregnancy_Test:edit')")
    @Log(title = "孕检记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScPregnancyRecord scPregnancyRecord)
    {
        try {
            // 基础参数校验
            if (scPregnancyRecord == null) {
                return error("请求参数不能为空");
            }

            if (scPregnancyRecord.getId() == null) {
                return error("记录ID不能为空");
            }

            if (scPregnancyRecord.getManageTags() == null || scPregnancyRecord.getManageTags().trim().isEmpty()) {
                return error("管理耳号不能为空");
            }

            if (scPregnancyRecord.getDatetime() == null) {
                return error("孕检日期不能为空");
            }

            if (scPregnancyRecord.getResult() == null || scPregnancyRecord.getResult().trim().isEmpty()) {
                return error("孕检结果不能为空");
            }

            if (scPregnancyRecord.getTechnician() == null || scPregnancyRecord.getTechnician().trim().isEmpty()) {
                return error("技术员不能为空");
            }

            // 清理输入参数
            scPregnancyRecord.setManageTags(scPregnancyRecord.getManageTags().trim());
            scPregnancyRecord.setResult(scPregnancyRecord.getResult().trim());
            scPregnancyRecord.setTechnician(scPregnancyRecord.getTechnician().trim());

            if (scPregnancyRecord.getRemark() != null) {
                scPregnancyRecord.setRemark(scPregnancyRecord.getRemark().trim());
            }

            logger.info("修改孕检记录，ID: {}, 耳号: {}", scPregnancyRecord.getId(), scPregnancyRecord.getManageTags());

            int result = scPregnancyRecordService.updateScPregnancyRecord(scPregnancyRecord);
            if (result > 0) {
                logger.info("修改孕检记录成功");
                return success("修改成功");
            } else {
                return error("修改失败，记录可能不存在");
            }
        } catch (ServiceException e) {
            logger.warn("修改孕检记录业务异常: " + e.getMessage());
            return error(e.getMessage());
        } catch (Exception e) {
            logger.error("修改孕检记录失败", e);
            return error("修改失败: " + e.getMessage());
        }
    }

    /**
     * 删除孕检记录
     */
    @PreAuthorize("@ss.hasPermi('Pregnancy_Test:Pregnancy_Test:remove')")
    @Log(title = "孕检记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        try {
            if (ids == null || ids.length == 0) {
                return error("删除的记录ID不能为空");
            }

            logger.info("删除孕检记录，IDs: {}", java.util.Arrays.toString(ids));

            int result = scPregnancyRecordService.deleteScPregnancyRecordByIds(ids);
            if (result > 0) {
                logger.info("删除孕检记录成功，删除数量: {}", result);
                return success("删除成功");
            } else {
                return error("删除失败，记录可能不存在");
            }
        } catch (ServiceException e) {
            logger.warn("删除孕检记录业务异常: " + e.getMessage());
            return error(e.getMessage());
        } catch (Exception e) {
            logger.error("删除孕检记录失败", e);
            return error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 根据耳号获取羊只信息
     */
    @GetMapping("/getSheepByManageTags")
    public AjaxResult getSheepByManageTags(@RequestParam("manageTags") String manageTags)
    {
        try {
            if (manageTags == null || manageTags.trim().isEmpty()) {
                return error("管理耳号不能为空");
            }

            String cleanTag = manageTags.trim();
            logger.info("查询羊只信息，耳号: [{}]", cleanTag);

            Map<String, Object> sheepInfo = scPregnancyRecordService.getSheepByManageTags(cleanTag);
            if (sheepInfo == null) {
                logger.warn("未找到耳号 [{}] 对应的羊只信息", cleanTag);
                return error("未找到该耳号的羊只信息");
            }

            logger.info("查询羊只信息成功，羊只ID: {}", sheepInfo.get("id"));
            return success(sheepInfo);
        } catch (ServiceException e) {
            return error(e.getMessage());
        } catch (Exception e) {
            logger.error("查询羊只信息失败，管理耳号: " + manageTags, e);
            return error("查询羊只信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据耳号获取配种信息
     */
    @GetMapping("/getBreedInfoByManageTags")
    public AjaxResult getBreedInfoByManageTags(@RequestParam("manageTags") String manageTags)
    {
        try {
            if (manageTags == null || manageTags.trim().isEmpty()) {
                return error("管理耳号不能为空");
            }

            String cleanTag = manageTags.trim();
            logger.info("查询配种信息，耳号: [{}]", cleanTag);

            Map<String, Object> breedInfo = scPregnancyRecordService.getBreedInfoByManageTags(cleanTag);
            if (breedInfo == null) {
                logger.info("未找到耳号 [{}] 对应的配种信息", cleanTag);
                return error("未找到该耳号的配种信息");
            }

            logger.info("查询配种信息成功");
            return success(breedInfo);
        } catch (ServiceException e) {
            return error(e.getMessage());
        } catch (Exception e) {
            logger.error("查询配种信息失败，管理耳号: " + manageTags, e);
            return error("查询配种信息失败: " + e.getMessage());
        }
    }

    /**
     * 调试接口：测试数据库连接和基础查询
     */
    @GetMapping("/debug/test")
    public AjaxResult debugTest()
    {
        try {
            // 测试基础查询
            ScPregnancyRecord testQuery = new ScPregnancyRecord();
            List<ScPregnancyRecord> list = scPregnancyRecordService.selectScPregnancyRecordList(testQuery);

            logger.info("调试测试 - 总记录数: {}", list.size());

            // 打印前几条记录的耳号信息
            for (int i = 0; i < Math.min(5, list.size()); i++) {
                ScPregnancyRecord record = list.get(i);
                logger.info("调试测试 - 记录{}：ID={}, 耳号={}", i+1, record.getId(), record.getManageTags());
            }

            return success("调试测试完成，总记录数: " + list.size());
        } catch (Exception e) {
            logger.error("调试测试失败", e);
            return error("调试测试失败: " + e.getMessage());
        }
    }
    /**
     * 模糊查询母羊耳号列表
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:query')") // 根据实际权限修改
    @GetMapping("/search_ear_numbers")
    public AjaxResult searchEarNumbers(@RequestParam("query") String query) {
        try {
            List<String> earNumbers = scPregnancyRecordService.searchEarNumbers(query);
            return success(earNumbers);
        } catch (Exception e) {
            logger.error("搜索耳号异常", e);
            return error("搜索耳号失败：" + e.getMessage());
        }
    }
}