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

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

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

/**
 * 配种计划生成Controller
 *
 * @author ruoyi
 * @date 2025-07-16
 */
@RestController
@RequestMapping("/mating_plan/generate")
public class ScBreedPlanGenerateController extends BaseController
{
    @Autowired
    private IScBreedPlanGenerateService scBreedPlanGenerateService;

    /**
     * 查询配种计划生成列表
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScBreedPlanGenerate scBreedPlanGenerate)
    {
        startPage();
        List<ScBreedPlanGenerate> list = scBreedPlanGenerateService.selectScBreedPlanGenerateList(scBreedPlanGenerate);
        return getDataTable(list);
    }

    /**
     * 筛选符合条件的母羊
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:selectEwe')")
    @GetMapping("/selectEwe")
    public AjaxResult selectEligibleEwe(@RequestParam(value = "manageTags", required = false) String manageTags)
    {
        List<Map<String, Object>> eligibleEwe = scBreedPlanGenerateService.selectEligibleEwe(manageTags);
        return success(eligibleEwe);
    }

    /**
     * 筛选符合条件的公羊
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:selectRam')")
    @GetMapping("/selectRam")
    public AjaxResult selectEligibleRam(@RequestParam(value = "manageTags", required = false) String manageTags)
    {
        List<Map<String, Object>> eligibleRam = scBreedPlanGenerateService.selectEligibleRam(manageTags);
        return success(eligibleRam);
    }

    /**
     * 自动生成配种计划
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:auto')")
    @PostMapping("/auto")
    @Log(title = "自动生成配种计划", businessType = BusinessType.INSERT)
    public AjaxResult autoGenerateBreedPlan(@RequestBody Map<String, Object> params)
    {
        try {
            // 获取计划类型
            Integer planType = params.get("planType") != null ? (Integer) params.get("planType") : 1;

            // 计划名称由系统自动生成，不再从前端传入
            String planName = null;

            // 安全的类型转换
            List<?> eweIdsRaw = (List<?>) params.get("eweIds");
            List<?> ramIdsRaw = (List<?>) params.get("ramIds");

            if (eweIdsRaw == null || ramIdsRaw == null) {
                return error("参数不能为空");
            }

            List<Long> eweIds = eweIdsRaw.stream()
                    .map(obj -> {
                        if (obj instanceof Integer) {
                            return ((Integer) obj).longValue();
                        } else if (obj instanceof Long) {
                            return (Long) obj;
                        } else {
                            return Long.valueOf(obj.toString());
                        }
                    })
                    .collect(Collectors.toList());

            List<Long> ramIds = ramIdsRaw.stream()
                    .map(obj -> {
                        if (obj instanceof Integer) {
                            return ((Integer) obj).longValue();
                        } else if (obj instanceof Long) {
                            return (Long) obj;
                        } else {
                            return Long.valueOf(obj.toString());
                        }
                    })
                    .collect(Collectors.toList());

            ScBreedPlanGenerate planGenerate = scBreedPlanGenerateService.autoGenerateBreedPlan(planType, planName, eweIds, ramIds);
            return success(planGenerate);
        } catch (Exception e) {
            logger.error("自动生成配种计划失败", e);
            return error("自动生成配种计划失败：" + e.getMessage());
        }
    }

    /**
     * 获取配种计划生成详细信息
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scBreedPlanGenerateService.selectScBreedPlanGenerateById(id));
    }

    /**
     * 保存配种计划生成
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:add')")
    @Log(title = "配种计划生成", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScBreedPlanGenerate scBreedPlanGenerate)
    {
        return toAjax(scBreedPlanGenerateService.insertScBreedPlanGenerate(scBreedPlanGenerate));
    }

    /**
     * 修改配种计划生成
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:edit')")
    @Log(title = "配种计划生成", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScBreedPlanGenerate scBreedPlanGenerate)
    {
        return toAjax(scBreedPlanGenerateService.updateScBreedPlanGenerate(scBreedPlanGenerate));
    }

    /**
     * 获取审批配种计划详情
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:approve')")
    @GetMapping("/approve/{id}")
    public AjaxResult getApproveInfo(@PathVariable Long id)
    {
        Map<String, Object> approveDetails = scBreedPlanGenerateService.getApproveBreedPlanDetails(id);
        return success(approveDetails);
    }

    /**
     * 确认审批配种计划
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:approve')")
    @Log(title = "确认审批配种计划", businessType = BusinessType.UPDATE)
    @PutMapping("/approve/confirm")
    public AjaxResult confirmApprove(@RequestBody Map<String, Object> params)
    {
        try {
            Long planId = Long.valueOf(params.get("planId").toString());
            Integer status = Integer.valueOf(params.get("status").toString());
            String approveRemark = params.get("approveRemark") != null ? params.get("approveRemark").toString() : "";

            @SuppressWarnings("unchecked")
            List<Map<String, Object>> planDetails = (List<Map<String, Object>>) params.get("planDetails");

            int result = scBreedPlanGenerateService.confirmApproveBreedPlan(planId, planDetails, status, approveRemark);
            return toAjax(result);
        } catch (Exception e) {
            logger.error("确认审批配种计划失败", e);
            return error("确认审批配种计划失败：" + e.getMessage());
        }
    }

    /**
     * 获取配种计划详情
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:view')")
    @GetMapping("/view/{id}")
    public AjaxResult viewBreedPlan(@PathVariable Long id)
    {
        Map<String, Object> planDetails = scBreedPlanGenerateService.getBreedPlanDetails(id);
        return success(planDetails);
    }

    /**
     * 导出配种计划列表
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:export')")
    @Log(title = "导出配种计划列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScBreedPlanGenerate scBreedPlanGenerate)
    {
        List<ScBreedPlanGenerate> list = scBreedPlanGenerateService.selectScBreedPlanGenerateList(scBreedPlanGenerate);
        ExcelUtil<ScBreedPlanGenerate> util = new ExcelUtil<ScBreedPlanGenerate>(ScBreedPlanGenerate.class);
        util.exportExcel(response, list, "配种计划生成数据");
    }

    /**
     * 导出配种计划详情
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:export')")
    @Log(title = "导出配种计划详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export/{id}")
    public void exportBreedPlanDetails(HttpServletResponse response, @PathVariable Long id)
    {
        try {
            scBreedPlanGenerateService.exportBreedPlanDetails(response, id);
        } catch (Exception e) {
            logger.error("导出配种计划详情失败", e);
            // 在出错时返回错误信息给前端
            try {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("{\"code\":500,\"msg\":\"导出失败：" + e.getMessage() + "\"}");
            } catch (Exception ex) {
                logger.error("返回错误信息失败", ex);
            }
        }
    }

    /**
     * 删除配种计划生成
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:remove')")
    @Log(title = "配种计划生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scBreedPlanGenerateService.deleteScBreedPlanGenerateByIds(ids));
    }

    /**
     * 模糊查询母羊耳号列表
     */
    @PreAuthorize("@ss.hasPermi('mating_plan:generate:query')") // 根据实际权限修改
    @GetMapping("/search_ear_numbers")
    public AjaxResult searchEarNumbers(@RequestParam("query") String query) {
        try {
            List<String> earNumbers = scBreedPlanGenerateService.searchEarNumbers(query);
            return success(earNumbers);
        } catch (Exception e) {
            logger.error("搜索耳号异常", e);
            return error("搜索耳号失败：" + e.getMessage());
        }
    }
}