package com.zhyc.module.frozen.controller;

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

import com.zhyc.common.utils.SecurityUtils;
import com.zhyc.common.utils.StringUtils;
import com.zhyc.module.frozen.mapper.DdFeMapper;
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.frozen.domain.DdFe;
import com.zhyc.module.frozen.service.IDdFeService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

/**
 * 冻胚库存Controller
 *
 * @author ruoyi
 * @date 2025-11-29
 */
@RestController
@RequestMapping("/frozen/embryo")
public class DdFeController extends BaseController {
    @Autowired
    private IDdFeService ddFeService;
    @Autowired
    private DdFeMapper ddFeMapper;

    /**
     * 查询冻胚库存列表
     */
    @PreAuthorize("@ss.hasPermi('frozen:embryo:list')")
    @GetMapping("/list")
    public TableDataInfo list(DdFe ddFe) {
        startPage();
        List<DdFe> list = ddFeService.selectDdFeList(ddFe);
        return getDataTable(list);
    }

    /**
     * 导出冻胚库存列表
     */
    @PreAuthorize("@ss.hasPermi('frozen:embryo:export')")
    @Log(title = "冻胚库存", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DdFe ddFe) {
        List<DdFe> list = ddFeService.selectDdFeList(ddFe);
        ExcelUtil<DdFe> util = new ExcelUtil<DdFe>(DdFe.class);
        util.exportExcel(response, list, "冻胚库存数据");
    }

    /**
     * 获取冻胚库存详细信息
     */
    @PreAuthorize("@ss.hasPermi('frozen:embryo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ddFeService.selectDdFeById(id));
    }

    /**
     * 新增冻胚库存
     */
    @PreAuthorize("@ss.hasPermi('frozen:embryo:add')")
    @Log(title = "冻胚库存", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DdFe ddFe) {
        ddFe.setCreateBy(SecurityUtils.getUsername());
        return toAjax(ddFeService.insertDdFe(ddFe));
    }

    /**
     * 修改冻胚库存
     */
    @PreAuthorize("@ss.hasPermi('frozen:embryo:edit')")
    @Log(title = "冻胚库存", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DdFe ddFe) {
        return toAjax(ddFeService.updateDdFe(ddFe));
    }

    /**
     * 删除冻胚库存
     */
    @PreAuthorize("@ss.hasPermi('frozen:embryo:remove')")
    @Log(title = "冻胚库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ddFeService.deleteDdFeByIds(ids));
    }

    /**
     * 根据供体母羊耳号获取最近一次冲胚信息
     */
    @PreAuthorize("@ss.hasPermi('frozen:embryo:add')")
    @GetMapping("/getFlushInfoByEwe/{eweNo}")
    public AjaxResult getFlushInfoByEwe(@PathVariable("eweNo") String eweNo) {
        if (StringUtils.isBlank(eweNo)) {
            return error("耳号不能为空");
        }
        Map<String, Object> echo = ddFeService.getLastFlushInfoByEwe(eweNo.trim());
        return echo == null ? error("该母羊无冲胚记录，请先录入冲胚记录") : success(echo);
    }

    /**
     * 根据母羊耳号 + 胚胎等级 返回该等级数量
     * 无记录返回 0
     */
    @PreAuthorize("@ss.hasPermi('frozen:embryo:add')")
    @GetMapping("/getQtyByGrade")
    public AjaxResult getQtyByGrade(@RequestParam String eweNo,
                                    @RequestParam String grade) {
        Map<String, Object> flush = ddFeService.getLastFlushInfoByEwe(eweNo);
        if (flush == null) return success(0);

        Integer qty;
        switch (grade) {
            case "A":
                qty = (Integer) flush.getOrDefault("gradeA", 0);
                break;
            case "B":
                qty = (Integer) flush.getOrDefault("gradeB", 0);
                break;
            case "C":
                qty = (Integer) flush.getOrDefault("gradeC", 0);
                break;
            case "D":
                qty = (Integer) flush.getOrDefault("gradeD", 0);
                break;
            default:
                qty = 0;
        }
        return success(qty);
    }

    /**
     * 批量废弃
     */
    @PreAuthorize("@ss.hasPermi('frozen:embryo:discard')")
    @Log(title = "冻胚库存", businessType = BusinessType.UPDATE)
    @PutMapping("/batchDiscard")
    public AjaxResult batchDiscard(@RequestBody List<DdFe> list) {
        if (list == null || list.isEmpty()) {
            return error("请选择要废弃的记录");
        }
        list.forEach(dto -> {
            dto.setStatus("废弃");
            ddFeService.discard(dto);
        });
        return success();
    }

    //    唯一性校验
    @GetMapping("/checkCode")
    public AjaxResult exist(@RequestParam String code) {
        return success(ddFeMapper.existsByCode(code) > 0);
    }
}
