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.*;
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.ScLambingRecord;
import com.zhyc.module.produce.breed.domain.ScLambDetail;
import com.zhyc.module.produce.breed.service.IScLambingRecordService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

/**
 * 产羔记录Controller
 */
@RestController
@RequestMapping("/breed/lambing_records")
public class ScLambingRecordController extends BaseController {

    @Autowired
    private IScLambingRecordService scLambingRecordService;

    /**
     * 查询产羔记录列表
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScLambingRecord scLambingRecord) {
        startPage();
        List<ScLambingRecord> list = scLambingRecordService.selectScLambingRecordList(scLambingRecord);
        return getDataTable(list);
    }

    /**
     * 根据母羊耳号查询最新配种记录
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:query')")
    @GetMapping("/breeding_info/{earNumber}")
    public AjaxResult getBreedingInfo(@PathVariable("earNumber") String earNumber) {
        try {
            Map<String, Object> breedingInfo = scLambingRecordService.getLatestBreedingByEarNumber(earNumber);
            if (breedingInfo != null && !breedingInfo.isEmpty()) {
                return success(breedingInfo);
            } else {
                return error("未找到该母羊的配种记录，请检查耳号是否正确");
            }
        } 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 = scLambingRecordService.searchEarNumbers(query);
            return success(earNumbers);
        } catch (Exception e) {
            logger.error("搜索耳号异常", e);
            return error("搜索耳号失败：" + e.getMessage());
        }
    }
    /**
     * 导出产羔记录列表
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:export')")
    @Log(title = "产羔记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScLambingRecord scLambingRecord) {
        List<ScLambingRecord> list = scLambingRecordService.selectScLambingRecordList(scLambingRecord);
        ExcelUtil<ScLambingRecord> util = new ExcelUtil<ScLambingRecord>(ScLambingRecord.class);
        util.exportExcel(response, list, "产羔记录数据");
    }

    /**
     * 获取产羔记录详细信息（修改：改为获取包含关联信息的详细数据）
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        // 修改：改为调用详细查询方法，获取包含母羊耳号、公羊耳号等关联信息
        return success(scLambingRecordService.selectScLambingRecordDetailById(id));
    }

    /**
     * 新增产羔记录（包含羔羊详情）
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:add')")
    @Log(title = "产羔记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScLambingRecord scLambingRecord) {
        try {
            // 设置创建人
            scLambingRecord.setCreateBy(getUsername());

            // 如果没有设置创建时间，使用当前时间
            if (scLambingRecord.getCreateTime() == null) {
                scLambingRecord.setCreateTime(new java.util.Date());
            }

            int result = scLambingRecordService.insertScLambingRecord(scLambingRecord);

            if (result > 0) {
                String message = "新增产羔记录成功";
                if (scLambingRecord.getLambDetails() != null && !scLambingRecord.getLambDetails().isEmpty()) {
                    message += "，同时录入了 " + scLambingRecord.getLambDetails().size() + " 只羔羊详情";
                }
                return success(message);
            } else {
                return error("新增产羔记录失败");
            }
        } catch (Exception e) {
            logger.error("新增产羔记录异常", e);
            return error("新增产羔记录失败：" + e.getMessage());
        }
    }

    /**
     * 修改产羔记录
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:edit')")
    @Log(title = "产羔记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScLambingRecord scLambingRecord) {
        try {
            scLambingRecord.setUpdateBy(getUsername());
            scLambingRecord.setUpdateTime(new java.util.Date());
            return toAjax(scLambingRecordService.updateScLambingRecord(scLambingRecord));
        } catch (Exception e) {
            logger.error("修改产羔记录异常", e);
            return error("修改产羔记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除产羔记录
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:remove')")
    @Log(title = "产羔记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        try {
            return toAjax(scLambingRecordService.deleteScLambingRecordByIds(ids));
        } catch (Exception e) {
            logger.error("删除产羔记录异常", e);
            return error("删除产羔记录失败：" + e.getMessage());
        }
    }

    /**
     * 查询羔羊详情
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:query')")
    @GetMapping("/lamb_detail/{lambingRecordId}")
    public AjaxResult getLambDetail(@PathVariable("lambingRecordId") Long lambingRecordId) {
        try {
            List<ScLambDetail> lambDetails = scLambingRecordService.selectLambDetailByLambingRecordId(lambingRecordId);
            return success(lambDetails);
        } catch (Exception e) {
            logger.error("查询羔羊详情异常", e);
            return error("查询羔羊详情失败：" + e.getMessage());
        }
    }
}