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.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);
    }
    /*
    * 根据羊舍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: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));
    }
    /**
     * 检查羊舍编号是否已存在
     */
    @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()));
    }
}
