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.module.produce.breed.domain.ScDryMilk;
import com.zhyc.module.produce.breed.service.IScDryMilkService;
import com.zhyc.module.base.domain.DaSheepfold;
import com.zhyc.module.base.service.IDaSheepfoldService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

/**
 * 干奶记录Controller
 *
 * @author ruoyi
 * @date 2025-07-15
 */
@RestController
@RequestMapping("/drymilk/drymilk")
public class ScDryMilkController extends BaseController
{
    @Autowired
    private IScDryMilkService scDryMilkService;

    @Autowired
    private IDaSheepfoldService daSheepfoldService;

    /**
     * 查询干奶记录列表
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScDryMilk scDryMilk)
    {
        try {
            // 添加调试日志
            if (scDryMilk.getManageTags() != null && !scDryMilk.getManageTags().trim().isEmpty()) {
                logger.info("搜索耳号参数: [{}]", scDryMilk.getManageTags());
                scDryMilk.setManageTags(scDryMilk.getManageTags().trim());
            }

            startPage();
            List<ScDryMilk> list = scDryMilkService.selectScDryMilkList(scDryMilk);

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

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

    /**
     * 导出干奶记录列表
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:export')")
    @Log(title = "干奶记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScDryMilk scDryMilk)
    {
        try {
            if (scDryMilk.getManageTags() != null) {
                scDryMilk.setManageTags(scDryMilk.getManageTags().trim());
            }

            List<ScDryMilk> list = scDryMilkService.selectScDryMilkList(scDryMilk);
            ExcelUtil<ScDryMilk> util = new ExcelUtil<ScDryMilk>(ScDryMilk.class);
            util.exportExcel(response, list, "干奶记录数据");
        } catch (Exception e) {
            logger.error("导出干奶记录失败", e);
        }
    }

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

            ScDryMilk result = scDryMilkService.selectScDryMilkById(id);
            if (result == null) {
                return error("记录不存在");
            }

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

    /**
     * 根据耳号查询羊只ID - 新增耳号验证功能
     */
    @GetMapping("/validateEarTag")
    public AjaxResult validateEarTag(@RequestParam("manageTags") String manageTags)
    {
        try {
            if (manageTags == null || manageTags.trim().isEmpty()) {
                return error("耳号不能为空");
            }

            String cleanTag = manageTags.trim();
            logger.info("验证耳号: [{}]", cleanTag);

            Long sheepId = scDryMilkService.selectSheepIdByManageTags(cleanTag);
            if (sheepId == null) {
                logger.warn("耳号 [{}] 不存在", cleanTag);
                return error("该耳号不存在，请检查输入");
            }

            logger.info("验证耳号成功，羊只ID: {}", sheepId);
            return AjaxResult.success("耳号验证通过", sheepId);
        } catch (Exception e) {
            logger.error("验证耳号失败，耳号: " + manageTags, e);
            return error("验证耳号时出错: " + e.getMessage());
        }
    }

    /**
     * 根据耳号查询羊只ID
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:query')")
    @GetMapping(value = "/sheep/{manageTags}")
    public AjaxResult getSheepIdByManageTags(@PathVariable("manageTags") String manageTags)
    {
        Long sheepId = scDryMilkService.selectSheepIdByManageTags(manageTags);
        return success(sheepId);
    }

    /**
     * 获取羊舍列表 - 用于嵌套选择
     */
    @GetMapping("/sheepfoldList")
    public AjaxResult getSheepfoldList(@RequestParam(value = "ranchId", required = false) Long ranchId,
                                       @RequestParam(value = "sheepfoldTypeId", required = false) Long sheepfoldTypeId)
    {
        try {
            DaSheepfold query = new DaSheepfold();
            if (ranchId != null) {
                query.setRanchId(ranchId);
            }
            if (sheepfoldTypeId != null) {
                query.setSheepfoldTypeId(sheepfoldTypeId);
            }

            List<DaSheepfold> sheepfoldList = daSheepfoldService.selectDaSheepfoldList(query);
            logger.info("查询羊舍列表，牧场ID: {}, 类型ID: {}, 结果数量: {}", ranchId, sheepfoldTypeId, sheepfoldList.size());

            return success(sheepfoldList);
        } catch (Exception e) {
            logger.error("获取羊舍列表失败", e);
            return error("获取羊舍列表失败: " + e.getMessage());
        }
    }

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

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

            if (scDryMilk.getDatetime() == null) {
                return error("干奶日期不能为空");
            }

            if (scDryMilk.getStatus() == null) {
                return error("请选择是否使用乳头封闭剂");
            }

            // 清理输入参数
            scDryMilk.setManageTags(scDryMilk.getManageTags().trim());
            if (scDryMilk.getTecahnician() != null) {
                scDryMilk.setTecahnician(scDryMilk.getTecahnician().trim());
            }
            if (scDryMilk.getComment() != null) {
                scDryMilk.setComment(scDryMilk.getComment().trim());
            }

            logger.info("新增干奶记录，耳号: {}", scDryMilk.getManageTags());

            int result = scDryMilkService.insertScDryMilk(scDryMilk);
            if (result > 0) {
                // 重新查询插入的记录，包含自动生成的创建时间
                ScDryMilk insertedRecord = scDryMilkService.selectScDryMilkById(scDryMilk.getId());
                logger.info("新增干奶记录成功，记录ID: {}", scDryMilk.getId());
                return success(insertedRecord);
            } else {
                return error("新增失败");
            }
        } catch (Exception e) {
            logger.error("新增干奶记录失败", e);
            return error("新增失败: " + e.getMessage());
        }
    }

    /**
     * 修改干奶记录
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:edit')")
    @Log(title = "干奶记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScDryMilk scDryMilk)
    {
        try {
            if (scDryMilk == null) {
                return error("请求参数不能为空");
            }

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

            // 清理输入参数
            if (scDryMilk.getManageTags() != null) {
                scDryMilk.setManageTags(scDryMilk.getManageTags().trim());
            }
            if (scDryMilk.getTecahnician() != null) {
                scDryMilk.setTecahnician(scDryMilk.getTecahnician().trim());
            }
            if (scDryMilk.getComment() != null) {
                scDryMilk.setComment(scDryMilk.getComment().trim());
            }

            logger.info("修改干奶记录，ID: {}", scDryMilk.getId());

            int result = scDryMilkService.updateScDryMilk(scDryMilk);
            if (result > 0) {
                logger.info("修改干奶记录成功");
                return success("修改成功");
            } else {
                return error("修改失败，记录可能不存在");
            }
        } catch (Exception e) {
            logger.error("修改干奶记录失败", e);
            return error("修改失败: " + e.getMessage());
        }
    }

    /**
     * 删除干奶记录
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk: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 = scDryMilkService.deleteScDryMilkByIds(ids);
            if (result > 0) {
                logger.info("删除干奶记录成功，删除数量: {}", result);
                return success("删除成功");
            } else {
                return error("删除失败，记录可能不存在");
            }
        } catch (Exception e) {
            logger.error("删除干奶记录失败", e);
            return error("删除失败: " + e.getMessage());
        }
    }
}