package com.zhyc.module.base.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.zhyc.common.core.domain.entity.SysDictData;
import com.zhyc.common.utils.StringUtils;
import com.zhyc.module.base.domain.BasGroupTreeVo;
import com.zhyc.module.base.domain.BasSheepGroupMapping;
import com.zhyc.module.base.domain.BasSheepGroupExportVo;
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.base.service.IBasSheepGroupMappingService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

// 1. 导入
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
// 1. 引入若依字典工具
import com.zhyc.common.utils.DictUtils;



/**
 * 羊只分组关联Controller
 * 
 * @author wyt
 * @date 2025-07-16
 */
@RestController
@RequestMapping("/sheep_grouping/sheep_grouping")
public class BasSheepGroupMappingController extends BaseController
{

    // 工具方法：LocalDateTime -> Date
    private Date toDate(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof Date) {
            return (Date) obj;
        }
        if (obj instanceof LocalDateTime) {
            return Date.from(((LocalDateTime) obj).atZone(ZoneId.systemDefault()).toInstant());
        }
        throw new IllegalArgumentException("不支持的日期类型:" + obj.getClass());
    }
    @Autowired
    private IBasSheepGroupMappingService basSheepGroupMappingService;

    /**
     * 查询羊只分组关联列表
     */
    @PreAuthorize("@ss.hasPermi('sheep_grouping:sheep_grouping:list')")
    @GetMapping("/list")
    public TableDataInfo list(BasSheepGroupMapping basSheepGroupMapping)
    {
        startPage();
        List<BasSheepGroupMapping> list = basSheepGroupMappingService.selectBasSheepGroupMappingList(basSheepGroupMapping);
        return getDataTable(list);
    }

    // 2. 声明（放在类内部、方法外部）
    private static final Logger log = LoggerFactory.getLogger(BasSheepGroupMappingController.class);


    @PreAuthorize("@ss.hasPermi('sheep_grouping:sheep_grouping:list')")
    @GetMapping("/listJoin")
    public TableDataInfo list(
            @RequestParam(required = false) Long sheepId,
            @RequestParam(required = false) Long groupId,
            @RequestParam(required = false) String bsManageTags) {

        List<String> earList = null;
        if (StringUtils.hasText(bsManageTags)) {
            earList = Arrays.asList(bsManageTags.split("[,，\\s]+"));
        }
        startPage();
        List<Map<String,Object>> list = basSheepGroupMappingService
                .selectBasSheepGroupMappingList(sheepId, groupId, earList);
        return getDataTable(list);
    }


    /**
     * 导出羊只分组关联列表
     */
//    @PreAuthorize("@ss.hasPermi('sheep_grouping:sheep_grouping:export')")
//    @Log(title = "羊只分组关联", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, BasSheepGroupMapping basSheepGroupMapping)
//    {
//        List<BasSheepGroupMapping> list = basSheepGroupMappingService.selectBasSheepGroupMappingList(basSheepGroupMapping);
//        ExcelUtil<BasSheepGroupMapping> util = new ExcelUtil<BasSheepGroupMapping>(BasSheepGroupMapping.class);
//        util.exportExcel(response, list, "羊只分组关联数据");
//    }
    @PreAuthorize("@ss.hasPermi('sheep_grouping:sheep_grouping:export')")
    @Log(title = "羊只分组关联", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportJoin(HttpServletResponse response,
                           @RequestParam(required = false) Long sheepId,
                           @RequestParam(required = false) Long groupId,
                           @RequestParam(required = false) String bsManageTags) throws IOException {

        // 1. 把前端传来的耳号字符串转 List
        List<String> earList = null;
        if (StringUtils.hasText(bsManageTags)) {
            earList = Arrays.asList(bsManageTags.split("[,，\\s]+"));
        }

        // 2. 先查出来（这里返回 List<Map<String,Object>>）
        List<Map<String, Object>> list = basSheepGroupMappingService
                .selectBasSheepGroupMappingList(sheepId, groupId, earList);
        // 放在 stream 外面，避免每次都查缓存
        Map<String, String> genderMap = new HashMap<>();
        List<SysDictData> genderDict = DictUtils.getDictCache("sheep_gender");
        if (genderDict != null) {
            genderDict.forEach(d -> genderMap.put(d.getDictValue(), d.getDictLabel()));
        }
        // 3. Map → VO
        List<BasSheepGroupExportVo> voList = list.stream()
                .map(m -> {
                    BasSheepGroupExportVo vo = new BasSheepGroupExportVo();
                    vo.setGroupId(m.get("group_id") == null ? null : ((Number) m.get("group_id")).longValue());
                    vo.setGroupName((String) m.get("group_name"));
                    vo.setBsManageTags((String) m.get("bs_manage_tags"));
                    vo.setVariety((String) m.get("variety"));
                    vo.setFamily((String) m.get("family"));
                    vo.setName((String) m.get("name"));
                    vo.setGender(m.get("gender") == null ? null : ((Number) m.get("gender")).longValue());
                    Long genderCode = m.get("gender") == null ? null : ((Number) m.get("gender")).longValue();
                    vo.setGender(genderCode);
                    vo.setGenderText(genderMap.get(String.valueOf(genderCode)));
                    vo.setBirthday(toDate(m.get("birthday")));
                    vo.setMonthAge(m.get("month_age") == null ? null : ((Number) m.get("month_age")).longValue());
                    vo.setParity(m.get("parity") == null ? null : ((Number) m.get("parity")).longValue());
                    vo.setBirthWeight(m.get("birth_weight") == null ? null : ((Number) m.get("birth_weight")).longValue());

                    vo.setWeaningWeight(m.get("weaning_weight") == null ? null : ((Number) m.get("weaning_weight")).longValue());
                    vo.setCurrentWeight(m.get("current_weight") == null ? null : ((Number) m.get("current_weight")).longValue());
                    vo.setBreed((String) m.get("breed"));
                    vo.setFatherManageTags((String) m.get("father_manage_tags"));
                    vo.setMotherManageTags((String) m.get("mother_manage_tags"));
                    return vo;
                })
                .collect(Collectors.toList());

        // 4. 导出
        ExcelUtil<BasSheepGroupExportVo> util = new ExcelUtil<>(BasSheepGroupExportVo.class);
        util.exportExcel(response, voList, "羊只分组关联数据");
    }



    /**
     * 获取羊只分组关联详细信息
     */
    @PreAuthorize("@ss.hasPermi('sheep_grouping:sheep_grouping:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(basSheepGroupMappingService.selectBasSheepGroupMappingById(id));
    }

    /**
     * 新增羊只分组关联
     */
    @PreAuthorize("@ss.hasPermi('sheep_grouping:sheep_grouping:add')")
    @Log(title = "羊只分组关联", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BasSheepGroupMapping basSheepGroupMapping)
    {
        return toAjax(basSheepGroupMappingService.insertBasSheepGroupMapping(basSheepGroupMapping));
    }

    /**
     * 修改羊只分组关联
     */
    @PreAuthorize("@ss.hasPermi('sheep_grouping:sheep_grouping:edit')")
    @Log(title = "羊只分组关联", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BasSheepGroupMapping basSheepGroupMapping)
    {
        try {
            return toAjax(basSheepGroupMappingService.updateBasSheepGroupMapping(basSheepGroupMapping));
        } catch (RuntimeException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 删除羊只分组关联
     */
    @PreAuthorize("@ss.hasPermi('sheep_grouping:sheep_grouping:remove')")
    @Log(title = "羊只分组关联", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(basSheepGroupMappingService.deleteBasSheepGroupMappingByIds(ids));
    }


    @PostMapping("/addByEarTags")
    public AjaxResult addByEarTags(@RequestBody Map<String, Object> params) {
        List<String> earTags = (List<String>) params.get("earTags");
        Long groupId = Long.valueOf(params.get("groupId").toString());

        if (earTags == null || earTags.isEmpty()) {
            return error("耳号列表不能为空");
        }

        return basSheepGroupMappingService.addByEarTags(earTags, groupId);
    }


    /**
     * 树形分组下拉框
     */
    @GetMapping("/group/tree")
    public AjaxResult groupTree() {
        return success(basSheepGroupMappingService.selectGroupTree());
    }


}
