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

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.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());
        }
    }

    /**
     * 导出产羔记录列表（多Sheet：Sheet1=产羔记录，Sheet2=羔羊详情）
     */
    @PreAuthorize("@ss.hasPermi('breed:lambing_records:export')")
    @Log(title = "产羔记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScLambingRecord scLambingRecord) throws IOException {
        // 不分页，查全量
        List<ScLambingRecord> list = scLambingRecordService.selectScLambingRecordList(scLambingRecord);

        // 为每条记录补充羔羊详情
        for (ScLambingRecord record : list) {
            List<ScLambDetail> details = scLambingRecordService.selectLambDetailByLambingRecordId(record.getId());
            record.setLambDetails(details);
        }

        // 构建多Sheet工作簿
        XSSFWorkbook workbook = buildExportWorkbook(list);

        // 写出响应
        String filename = java.net.URLEncoder.encode("产羔记录_" + new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date()), "UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    /**
     * 构建导出工作簿（两个Sheet）
     */
    private XSSFWorkbook buildExportWorkbook(List<ScLambingRecord> list) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd");

        // ==================== Sheet1：产羔记录 ====================
        Sheet sheet1 = workbook.createSheet("产羔记录");

        // 标题样式
        CellStyle headerStyle = createHeaderStyle(workbook);
        // 普通单元格样式
        CellStyle dataStyle = createDataStyle(workbook);

        // 产羔记录表头（与界面完全一致）
        String[] headers1 = {
                "母羊耳号", "母羊品种", "配种日期", "胎次", "公羊耳号", "公羊品种",
                "产羔数量", "活羔数量", "折损数", "技术员", "月龄", "产羔评分",
                "公羔数量", "母羔数量", "留养公羔数量", "留养母羔数量",
                "未留养公羔数量", "未留养母羔数量", "产羔时怀孕天数",
                "当前羊舍", "创建人", "创建日期", "所在牧场", "备注"
        };

        // 列宽（字符数 * 256）
        int[] colWidths1 = {
                14, 12, 13, 8, 14, 12,
                10, 10, 8, 10, 8, 10,
                10, 10, 14, 14,
                16, 16, 16,
                12, 10, 12, 12, 20
        };

        Row headerRow1 = sheet1.createRow(0);
        headerRow1.setHeightInPoints(22);
        for (int i = 0; i < headers1.length; i++) {
            sheet1.setColumnWidth(i, colWidths1[i] * 256);
            Cell cell = headerRow1.createCell(i);
            cell.setCellValue(headers1[i]);
            cell.setCellStyle(headerStyle);
        }

        // 产羔记录数据行
        int rowNum1 = 1;
        for (ScLambingRecord r : list) {
            Row row = sheet1.createRow(rowNum1++);
            row.setHeightInPoints(18);
            int col = 0;
            setCellValue(row, col++, r.getFemaleEarNumber(), dataStyle);
            setCellValue(row, col++, r.getFemaleBreed(), dataStyle);
            setCellValue(row, col++, r.getBreedingDate() != null ? dateFmt.format(r.getBreedingDate()) : "", dataStyle);
            setCellValue(row, col++, r.getParity(), dataStyle);
            setCellValue(row, col++, r.getMaleEarNumber(), dataStyle);
            setCellValue(row, col++, r.getMaleBreed(), dataStyle);
            setCellValue(row, col++, r.getLambsBorn(), dataStyle);
            setCellValue(row, col++, r.getSurvival(), dataStyle);
            // 折损数 = 产羔数 - 活羔数
            int loss = (int) ((r.getLambsBorn() != null ? r.getLambsBorn() : 0)
                                - (r.getSurvival() != null ? r.getSurvival() : 0));
            setCellValue(row, col++, loss, dataStyle);
            setCellValue(row, col++, r.getTechnician(), dataStyle);
            setCellValue(row, col++, r.getMonthAge(), dataStyle);
            setCellValue(row, col++, r.getScore(), dataStyle);
            setCellValue(row, col++, r.getMaleCount(), dataStyle);
            setCellValue(row, col++, r.getFemaleCount(), dataStyle);
            setCellValue(row, col++, r.getRetainedMaleCount(), dataStyle);
            setCellValue(row, col++, r.getRetainedFemaleCount(), dataStyle);
            setCellValue(row, col++, r.getUnretainedMaleCount(), dataStyle);
            setCellValue(row, col++, r.getUnretainedFemaleCount(), dataStyle);
            setCellValue(row, col++, r.getPregnancyDays(), dataStyle);
            setCellValue(row, col++, r.getCurrentShed(), dataStyle);
            setCellValue(row, col++, r.getCreateBy(), dataStyle);
            setCellValue(row, col++, r.getCreateTime() != null ? dateFmt.format(r.getCreateTime()) : "", dataStyle);
            setCellValue(row, col++, r.getFarm(), dataStyle);
            setCellValue(row, col++, r.getComment(), dataStyle);
        }

        // ==================== Sheet2：羔羊详情 ====================
        Sheet sheet2 = workbook.createSheet("羔羊详情");

        String[] headers2 = {
                "母羊耳号", "胎次", "羔羊耳号", "性别", "出生体重(kg)",
                "是否留养", "家系", "出生日期"
        };
        int[] colWidths2 = { 14, 8, 14, 8, 14, 10, 16, 13 };

        Row headerRow2 = sheet2.createRow(0);
        headerRow2.setHeightInPoints(22);
        for (int i = 0; i < headers2.length; i++) {
            sheet2.setColumnWidth(i, colWidths2[i] * 256);
            Cell cell = headerRow2.createCell(i);
            cell.setCellValue(headers2[i]);
            cell.setCellStyle(headerStyle);
        }

        int rowNum2 = 1;
        for (ScLambingRecord r : list) {
            if (r.getLambDetails() == null || r.getLambDetails().isEmpty()) {
                continue;
            }
            for (ScLambDetail d : r.getLambDetails()) {
                Row row = sheet2.createRow(rowNum2++);
                row.setHeightInPoints(18);
                int col = 0;
                setCellValue(row, col++, r.getFemaleEarNumber(), dataStyle);
                setCellValue(row, col++, r.getParity(), dataStyle);
                setCellValue(row, col++, d.getLambEarNumber(), dataStyle);
                // 性别：1=公，0=母，2=阉羊，3=兼性（参照后端校验逻辑）
                String genderLabel = "";
                if (d.getGender() != null) {
                    switch (d.getGender()) {
                        case 0: genderLabel = "母"; break;
                        case 1: genderLabel = "公"; break;
                        case 2: genderLabel = "阉羊"; break;
                        case 3: genderLabel = "兼性"; break;
                        default: genderLabel = String.valueOf(d.getGender());
                    }
                }
                setCellValue(row, col++, genderLabel, dataStyle);
                setCellValue(row, col++, d.getBirthWeight() != null ? d.getBirthWeight().toPlainString() : "", dataStyle);
                setCellValue(row, col++, Boolean.TRUE.equals(d.getIsRetained()) ? "是" : "否", dataStyle);
                setCellValue(row, col++, d.getLineage(), dataStyle);
                setCellValue(row, col++, d.getBirthday() != null ? dateFmt.format(d.getBirthday()) : "", dataStyle);
            }
        }

        return workbook;
    }

    /** 创建表头样式 */
    private CellStyle createHeaderStyle(XSSFWorkbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 11);
        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }

    /** 创建数据行样式 */
    private CellStyle createDataStyle(XSSFWorkbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }

    /** 统一设置单元格值 */
    private void setCellValue(Row row, int col, Object value, CellStyle style) {
        Cell cell = row.createCell(col);
        if (value == null) {
            cell.setCellValue("");
        } else if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Long) {
            cell.setCellValue((Long) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        } else {
            cell.setCellValue(value.toString());
        }
        cell.setCellStyle(style);
    }

    /**
     * 获取产羔记录详细信息
     */
    @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());
        }
    }
}