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.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.ScBreedRecord;
import com.zhyc.module.produce.breed.service.IScBreedRecordService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

/**
 * 配种记录Controller
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@RestController
@RequestMapping("/Breeding_records/Breeding_records")
public class ScBreedRecordController extends BaseController
{
    @Autowired
    private IScBreedRecordService scBreedRecordService;

    /**
     * 查询配种记录列表
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScBreedRecord scBreedRecord)
    {
        startPage();
        List<ScBreedRecord> list = scBreedRecordService.selectScBreedRecordList(scBreedRecord);
        return getDataTable(list);
    }

    /**
     * 导出配种记录列表
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:export')")
    @Log(title = "配种记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScBreedRecord scBreedRecord)
    {
        List<ScBreedRecord> list = scBreedRecordService.selectScBreedRecordList(scBreedRecord);
        ExcelUtil<ScBreedRecord> util = new ExcelUtil<ScBreedRecord>(ScBreedRecord.class);
        util.exportExcel(response, list, "配种记录数据");
    }

    /**
     * 获取配种记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scBreedRecordService.selectScBreedRecordById(id));
    }

    /**
     * 根据耳号查询羊只信息
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:query')")
    @GetMapping(value = "/getSheepByTags/{manageTags}")
    public AjaxResult getSheepInfoByTags(@PathVariable("manageTags") String manageTags)
    {
        Map<String, Object> sheepInfo = scBreedRecordService.getSheepInfoByTags(manageTags);
        if (sheepInfo == null || sheepInfo.isEmpty()) {
            return error("未找到耳号为 " + manageTags + " 的羊只信息");
        }
        return success(sheepInfo);
    }

    /**
     * 根据母羊耳号获取配种计划信息
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:query')")
    @GetMapping(value = "/getBreedPlan/{manageTags}")
    public AjaxResult getBreedPlanByEweTags(@PathVariable("manageTags") String manageTags)
    {
        Map<String, Object> breedPlan = scBreedRecordService.getBreedPlanByEweTags(manageTags);
        if (breedPlan == null || breedPlan.isEmpty()) {
            return error("未找到耳号为 " + manageTags + " 的母羊配种计划");
        }
        return success(breedPlan);
    }

    /**
     * 根据母羊耳号获取最新配种计划信息(优先从配种计划生成表获取)
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:query')")
    @GetMapping(value = "/getLatestBreedPlan/{manageTags}")
    public AjaxResult getLatestBreedPlanByEweTags(@PathVariable("manageTags") String manageTags)
    {
        Map<String, Object> breedPlan = scBreedRecordService.getLatestBreedPlanByEweTags(manageTags);
        if (breedPlan == null || breedPlan.isEmpty()) {
            return error("未找到耳号为 " + manageTags + " 的母羊配种计划");
        }
        return success(breedPlan);
    }

    /**
     * 新增配种记录
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:add')")
    @Log(title = "配种记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScBreedRecord scBreedRecord)
    {
        // 处理母羊耳号转换
        if (scBreedRecord.getEweManageTags() != null && !scBreedRecord.getEweManageTags().isEmpty()) {
            Long eweId = scBreedRecordService.getSheepIdByTags(scBreedRecord.getEweManageTags());
            if (eweId == null) {
                return error("未找到母羊耳号 " + scBreedRecord.getEweManageTags() + " 对应的羊只信息");
            }
            scBreedRecord.setEweId(eweId.toString());
            scBreedRecord.setSheepId(eweId); // 设置羊只ID为母羊ID
        }

        // 处理公羊耳号转换
        if (scBreedRecord.getRamManageTags() != null && !scBreedRecord.getRamManageTags().isEmpty()) {
            Long ramId = scBreedRecordService.getRamIdByTags(scBreedRecord.getRamManageTags());
            if (ramId == null) {
                return error("未找到公羊耳号 " + scBreedRecord.getRamManageTags() + " 对应的羊只信息");
            }
            scBreedRecord.setRamId(ramId.toString());
        }

        // 修改：验证配种方式 - 增加3-冲胚 和 4-自然发情人工授精
        if (scBreedRecord.getBreedType() == null) {
            return error("配种方式不能为空");
        }
        if (scBreedRecord.getBreedType() < 1 || scBreedRecord.getBreedType() > 5) {
            return error("配种方式只能是：1-供体母羊配种、2-同期发情人工授精、3-本交、4-自然发情人工授精、5-胚胎移植");
        }

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

        int result = scBreedRecordService.insertScBreedRecord(scBreedRecord);
        if (result > 0) {
            return success("配种记录新增成功");
        }
        return error("配种记录新增失败");
    }

    /**
     * 修改配种记录
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:edit')")
    @Log(title = "配种记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScBreedRecord scBreedRecord)
    {
        // 处理母羊耳号转换
        if (scBreedRecord.getEweManageTags() != null && !scBreedRecord.getEweManageTags().isEmpty()) {
            Long eweId = scBreedRecordService.getSheepIdByTags(scBreedRecord.getEweManageTags());
            if (eweId == null) {
                return error("未找到母羊耳号 " + scBreedRecord.getEweManageTags() + " 对应的羊只信息");
            }
            scBreedRecord.setEweId(eweId.toString());
            scBreedRecord.setSheepId(eweId); // 设置羊只ID为母羊ID
        }

        // 处理公羊耳号转换
        if (scBreedRecord.getRamManageTags() != null && !scBreedRecord.getRamManageTags().isEmpty()) {
            Long ramId = scBreedRecordService.getRamIdByTags(scBreedRecord.getRamManageTags());
            if (ramId == null) {
                return error("未找到公羊耳号 " + scBreedRecord.getRamManageTags() + " 对应的羊只信息");
            }
            scBreedRecord.setRamId(ramId.toString());
        }

        // 修改：验证配种方式
        if (scBreedRecord.getBreedType() != null) {
            if (scBreedRecord.getBreedType() < 1 || scBreedRecord.getBreedType() > 4) {
                return error("配种方式只能是：1-同期发情、2-本交、3-冲胚、4-自然发情人工授精");
            }
        }

        return toAjax(scBreedRecordService.updateScBreedRecord(scBreedRecord));
    }

    /**
     * 删除配种记录
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:remove')")
    @Log(title = "配种记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scBreedRecordService.deleteScBreedRecordByIds(ids));
    }

    /**
     * 同步孕检结果到配种记录
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:edit')")
    @Log(title = "同步孕检结果", businessType = BusinessType.UPDATE)
    @PostMapping("/syncPregnancyResult")
    public AjaxResult syncPregnancyResult(@RequestBody Map<String, Object> params)
    {
        Long pregnancyRecordId = Long.valueOf(params.get("pregnancyRecordId").toString());
        Long sheepId = Long.valueOf(params.get("sheepId").toString());
        String pregnancyCheckDate = params.get("pregnancyCheckDate").toString();

        int result = scBreedRecordService.syncPregnancyResult(pregnancyRecordId, sheepId, pregnancyCheckDate);
        if (result > 0) {
            return success("孕检结果同步成功");
        } else {
            return error("孕检结果同步失败,可能未找到对应的配种记录");
        }
    }

    /**
     * 根据羊只ID和时间范围查询配种记录
     */
    @PreAuthorize("@ss.hasPermi('Breeding_records:Breeding_records:query')")
    @GetMapping("/getByTimeRange/{sheepId}/{startDate}/{endDate}")
    public AjaxResult getBreedRecordsByTimeRange(@PathVariable("sheepId") Long sheepId,
                                                 @PathVariable("startDate") String startDate,
                                                 @PathVariable("endDate") String endDate)
    {
        List<ScBreedRecord> records = scBreedRecordService.getBreedRecordsByTimeRange(sheepId, startDate, endDate);
        return success(records);
    }


}