package com.zhyc.module.base.controller;

import com.zhyc.common.annotation.Log;
import com.zhyc.common.core.controller.BaseController;
import com.zhyc.common.core.domain.AjaxResult;
import com.zhyc.common.core.page.TableDataInfo;
import com.zhyc.common.enums.BusinessType;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.module.base.domain.BasSheep;
import com.zhyc.module.base.domain.DaSheepfold;
import com.zhyc.module.base.domain.DaSheepfoldSummaryExportVO;
import com.zhyc.module.base.service.IDaSheepfoldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.zhyc.common.utils.DictUtils;

/**
 * 羊舍管理Controller
 * 
 * @author wyt
 * @date 2025-07-11
 */
@RestController
@RequestMapping("/sheepfold_management/sheepfold_management")
public class DaSheepfoldController extends BaseController
{
    @Autowired
    private IDaSheepfoldService daSheepfoldService;

    /**
     * 查询羊舍管理列表
     */
    @PreAuthorize("@ss.hasPermi('sheepfold_management:sheepfold_management:list')")
    @GetMapping("/list")
    public TableDataInfo list(DaSheepfold daSheepfold)
    {
        startPage();
        List<DaSheepfold> list = daSheepfoldService.selectDaSheepfoldList(daSheepfold);
        return getDataTable(list);
    }


    /**
     * 主表格：羊舍级别汇总列表
     */
    @GetMapping("/summaryList")
    public TableDataInfo summaryList(DaSheepfold daSheepfold) {
        startPage();
        List<DaSheepfold> list = daSheepfoldService.selectDaSheepfoldSummaryList(daSheepfold);
        return getDataTable(list);
    }
    /*
    * 根据羊舍ids查询羊只id
    * */

    @GetMapping("/getSheepById")
    public AjaxResult getSheepfold(@RequestParam String id) {
        List<BasSheep> list = daSheepfoldService.sheepListById(id);
        return AjaxResult.success(list);
    }



    /**
     * 导出羊舍管理列表
     */
    @PreAuthorize("@ss.hasPermi('sheepfold_management:sheepfold_management:export')")
    @Log(title = "羊舍管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DaSheepfold daSheepfold)
    {
        List<DaSheepfold> list = daSheepfoldService.selectDaSheepfoldList(daSheepfold);
        ExcelUtil<DaSheepfold> util = new ExcelUtil<DaSheepfold>(DaSheepfold.class);
        util.exportExcel(response, list, "羊舍管理数据");
    }


    /**
     * 导出羊舍管理汇总列表（主表格数据）- 新增方法
     */
    @PreAuthorize("@ss.hasPermi('sheepfold_management:sheepfold_management:export')")
    @Log(title = "羊舍管理汇总导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSummary")
    public void exportSummary(HttpServletResponse response, DaSheepfold daSheepfold) {
        // 1. 查询汇总数据
        List<DaSheepfold> list = daSheepfoldService.selectDaSheepfoldSummaryList(daSheepfold);

        // 2. 转换为导出VO
        List<DaSheepfoldSummaryExportVO> exportList = convertToExportVO(list);

        // 3. 使用VO类导出Excel
        ExcelUtil<DaSheepfoldSummaryExportVO> util = new ExcelUtil<>(DaSheepfoldSummaryExportVO.class);
        util.exportExcel(response, exportList, "羊舍管理汇总数据");
    }


    /**
     * 将DaSheepfold列表转换为导出VO列表
     */
    private List<DaSheepfoldSummaryExportVO> convertToExportVO(List<DaSheepfold> daSheepfoldList) {
        List<DaSheepfoldSummaryExportVO> voList = new ArrayList<>();

        for (DaSheepfold entity : daSheepfoldList) {
            DaSheepfoldSummaryExportVO vo = new DaSheepfoldSummaryExportVO();

            // 字典翻译：牧场ID -> 牧场名称
            if (entity.getRanchId() != null) {
                String ranchName = DictUtils.getDictLabel("da_ranch", entity.getRanchId().toString());
                vo.setRanchName(ranchName != null ? ranchName : entity.getRanchId().toString());
            } else {
                vo.setRanchName("");
            }

            // 使用汇总查询中的羊舍名称
            vo.setSheepfoldName(entity.getSheepfoldName() != null ? entity.getSheepfoldName() : "");

            // 字典翻译：羊舍类型ID -> 羊舍类型名称
            if (entity.getSheepfoldTypeId() != null) {
                String typeName = DictUtils.getDictLabel("bas_sheepfold_type", entity.getSheepfoldTypeId().toString());
                vo.setSheepfoldTypeName(typeName != null ? typeName : entity.getSheepfoldTypeId().toString());
            } else {
                vo.setSheepfoldTypeName("");
            }

            // 羊舍编号
            vo.setSheepfoldNo(entity.getSheepfoldNo() != null ? entity.getSheepfoldNo() : "");

            // 羊数（确保不为空）
            vo.setTotalSheepCount(entity.getTotalSheepCount() != null ? entity.getTotalSheepCount() : 0);

            // 备注
            vo.setComment(entity.getComment() != null ? entity.getComment() : "");

            voList.add(vo);
        }

        return voList;
    }





    /**
     * 获取羊舍管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('sheepfold_management:sheepfold_management:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(daSheepfoldService.selectDaSheepfoldById(id));
    }

    /**
     * 新增羊舍管理
     */
    @PreAuthorize("@ss.hasPermi('sheepfold_management:sheepfold_management:add')")
    @Log(title = "羊舍管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DaSheepfold daSheepfold)
    {
        return toAjax(daSheepfoldService.insertDaSheepfold(daSheepfold));
    }

    /**
     * 修改羊舍管理
     */
    @PreAuthorize("@ss.hasPermi('sheepfold_management:sheepfold_management:edit')")
    @Log(title = "羊舍管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DaSheepfold daSheepfold)
    {
        return toAjax(daSheepfoldService.updateDaSheepfold(daSheepfold));
    }

//    /**
//     * 删除羊舍管理
//     */
//    @PreAuthorize("@ss.hasPermi('sheepfold_management:sheepfold_management:remove')")
//    @Log(title = "羊舍管理", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids)
//    {
//        return toAjax(daSheepfoldService.deleteDaSheepfoldByIds(ids));
//    }

    /**
     * 修改后：根据组合条件删除羊圈信息（单条）
     * 接收ranch_id/sheepfold_no/sheepfold_type_id/sheepfold_name组合条件
     */
    @PreAuthorize("@ss.hasPermi('sheep:sheepfold:remove')")
    @DeleteMapping("/deleteByCondition")
    public AjaxResult removeByCondition(@RequestBody DaSheepfold sheepfold) {
        // 1. 校验核心条件非空（避免条件缺失导致误删）
        if (sheepfold.getRanchId() == null
                || sheepfold.getSheepfoldNo() == null || sheepfold.getSheepfoldNo().isEmpty()
                || sheepfold.getSheepfoldTypeId() == null) {
            return AjaxResult.error("删除失败：核心条件（牧场ID/羊圈编号/羊圈类型ID）不能为空");
        }
        // 2. 调用Service执行组合条件删除
        boolean deleteResult = daSheepfoldService.deleteSheepfoldByCondition(sheepfold);
        if (deleteResult) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败：未找到匹配条件的记录");
        }
    }

    /**
     * 【扩展】批量删除：接收多条组合条件数据，循环删除
     */
    @PreAuthorize("@ss.hasPermi('sheep:sheepfold:remove')")
    @DeleteMapping("/batchDeleteByCondition")
    public AjaxResult batchRemoveByCondition(@RequestBody List<DaSheepfold> sheepfoldList) {
        if (sheepfoldList == null || sheepfoldList.isEmpty()) {
            return AjaxResult.error("删除失败：请选择要删除的羊圈数据");
        }
        // 统计成功删除的数量
        int successCount = 0;
        for (DaSheepfold sheepfold : sheepfoldList) {
            // 跳过条件不全的记录
            if (sheepfold.getRanchId() == null
                    || sheepfold.getSheepfoldNo() == null || sheepfold.getSheepfoldNo().isEmpty()
                    || sheepfold.getSheepfoldTypeId() == null) {
                continue;
            }
            if (daSheepfoldService.deleteSheepfoldByCondition(sheepfold)) {
                successCount++;
            }
        }
        if (successCount == 0) {
            return AjaxResult.error("批量删除失败：无符合条件的记录可删除");
        } else {
            return AjaxResult.success("批量删除成功，共删除" + successCount + "条记录");
        }
    }







    /**
     * 检查羊舍编号是否已存在
     */
    @GetMapping("/checkSheepfoldNoExist")
    public AjaxResult checkSheepfoldNoExist(
            @RequestParam Long ranchId,
            @RequestParam Long sheepfoldTypeId,
            @RequestParam String sheepfoldNo
    ) {
        boolean exist = daSheepfoldService.checkSheepfoldNoExist(ranchId, sheepfoldTypeId, sheepfoldNo);
        return AjaxResult.success(exist);
    }

    @PreAuthorize("@ss.hasPermi('sheepfold_management:sheepfold_management:list')")
    @GetMapping("/seatMap")
    public AjaxResult seatMap() {
        List<DaSheepfold> flat = daSheepfoldService.selectDaSheepfoldList(new DaSheepfold());
        Map<Long, Map<String, Object>> tree = new LinkedHashMap<>();

        for (DaSheepfold s : flat) {
            Long ranchId   = s.getRanchId();
            Long typeId    = s.getSheepfoldTypeId();
            String foldNo  = s.getSheepfoldNo();
            String rowNo   = s.getRowNo();
            String columns = s.getColumns();

            // 翻译字典
            String ranchName = DictUtils.getDictLabel("da_ranch", String.valueOf(ranchId));
            String typeName  = DictUtils.getDictLabel("bas_sheepfold_type", String.valueOf(typeId));

            // 牧场
            Map<String, Object> ranch = tree.computeIfAbsent(ranchId, k -> {
                Map<String, Object> r = new LinkedHashMap<>();
                r.put("ranchId", k);
                r.put("ranchName", ranchName);
                r.put("types", new ArrayList<>());
                return r;
            });

            // 类型
            Map<String, Object> type = ((List<Map<String, Object>>) ranch.get("types")).stream()
                    .filter(t -> typeId.equals(t.get("typeId")))
                    .findFirst()
                    .orElseGet(() -> {
                        Map<String, Object> t = new LinkedHashMap<>();
                        t.put("typeId", typeId);
                        t.put("typeName", typeName);
                        t.put("folds", new ArrayList<>());
                        ((List<Map<String, Object>>) ranch.get("types")).add(t);
                        return t;
                    });

            // 羊舍
            Map<String, Object> fold = ((List<Map<String, Object>>) type.get("folds")).stream()
                    .filter(f -> foldNo.equals(f.get("foldNo")))
                    .findFirst()
                    .orElseGet(() -> {
                        Map<String, Object> f = new LinkedHashMap<>();
                        f.put("foldNo", foldNo);
                        f.put("rows", new ArrayList<>());
                        ((List<Map<String, Object>>) type.get("folds")).add(f);
                        return f;
                    });

            // 排
            Map<String, Object> row = ((List<Map<String, Object>>) fold.get("rows")).stream()
                    .filter(r -> rowNo.equals(r.get("rowNo")))
                    .findFirst()
                    .orElseGet(() -> {
                        Map<String, Object> newRow = new LinkedHashMap<>();
                        newRow.put("rowNo", rowNo);
                        newRow.put("columns", new ArrayList<>());
                        ((List<Map<String, Object>>) fold.get("rows")).add(newRow);
                        return newRow;
                    });

            // 将列号添加到对应的行
            ((List<String>) row.get("columns")).add(columns);
        }
        return success(new ArrayList<>(tree.values()));
    }
}
