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

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
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.ScDryMilk;
import com.zhyc.module.produce.breed.service.IScDryMilkService;
import com.zhyc.module.base.domain.DaSheepfold;
import com.zhyc.module.base.service.IDaSheepfoldService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

/**
 * 干奶记录Controller
 * * @author ruoyi
 * @date 2025-07-15
 */
@RestController
@RequestMapping("/drymilk/drymilk")
public class ScDryMilkController extends BaseController
{
    @Autowired
    private IScDryMilkService scDryMilkService;

    @Autowired
    private IDaSheepfoldService daSheepfoldService;

    /**
     * 查询干奶记录列表
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScDryMilk scDryMilk)
    {
        try {
            // 处理耳号多选：将逗号/空格分隔的字符串转为List
            if (scDryMilk.getManageTags() != null && !scDryMilk.getManageTags().trim().isEmpty()) {
                if (scDryMilk.getManageTagsList() == null) {
                    scDryMilk.setManageTagsList(new ArrayList<>());
                }
                String[] tags = scDryMilk.getManageTags().trim().split("[,，\\s]+");
                scDryMilk.getManageTagsList().addAll(Arrays.asList(tags));
            }

            // 处理技术员多选：将逗号分隔的字符串转为List
            if (scDryMilk.getTecahnician() != null && !scDryMilk.getTecahnician().trim().isEmpty()) {
                if (scDryMilk.getTechnicianList() == null) {
                    scDryMilk.setTechnicianList(new ArrayList<>());
                }
                String[] techs = scDryMilk.getTecahnician().trim().split("[,，\\s]+");
                scDryMilk.getTechnicianList().addAll(Arrays.asList(techs));
            }

            startPage();
            List<ScDryMilk> list = scDryMilkService.selectScDryMilkList(scDryMilk);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("查询干奶记录列表失败", e);
            return getDataTable(new ArrayList<>());
        }
    }

    /**
     * 远程搜索耳号列表
     */
    @GetMapping("/searchEarNumbers")
    public AjaxResult searchEarNumbers(@RequestParam(value = "query", required = false) String query)
    {
        if (query == null) query = "";
        List<String> list = scDryMilkService.selectSheepEarNumberList(query);
        return AjaxResult.success(list);
    }

    /**
     * 远程搜索技术员列表
     */
    @GetMapping("/searchTechnicians")
    public AjaxResult searchTechnicians(@RequestParam(value = "query", required = false) String query)
    {
        if (query == null) query = "";
        List<String> list = scDryMilkService.selectTechnicianList(query);
        return AjaxResult.success(list);
    }

    /**
     * 导出干奶记录列表
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:export')")
    @Log(title = "干奶记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScDryMilk scDryMilk)
    {
        try {
            // 导出也需要支持多选查询
            if (scDryMilk.getManageTags() != null) {
                String[] tags = scDryMilk.getManageTags().trim().split("[,，\\s]+");
                scDryMilk.setManageTagsList(Arrays.asList(tags));
            }
            if (scDryMilk.getTecahnician() != null) {
                String[] techs = scDryMilk.getTecahnician().trim().split("[,，\\s]+");
                scDryMilk.setTechnicianList(Arrays.asList(techs));
            }

            List<ScDryMilk> list = scDryMilkService.selectScDryMilkList(scDryMilk);
            ExcelUtil<ScDryMilk> util = new ExcelUtil<ScDryMilk>(ScDryMilk.class);
            util.exportExcel(response, list, "干奶记录数据");
        } catch (Exception e) {
            logger.error("导出干奶记录失败", e);
        }
    }

    /**
     * 获取干奶记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scDryMilkService.selectScDryMilkById(id));
    }

    /**
     * 获取羊舍列表
     */
    @GetMapping("/sheepfoldList")
    public AjaxResult getSheepfoldList(DaSheepfold daSheepfold)
    {
        List<DaSheepfold> list = daSheepfoldService.selectDaSheepfoldList(daSheepfold);
        return success(list);
    }

    /**
     * 新增干奶记录 (支持批量录入)
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:add')")
    @Log(title = "干奶记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScDryMilk scDryMilk)
    {
        try {
            if (scDryMilk == null || scDryMilk.getManageTags() == null) {
                return error("耳号不能为空");
            }

            // 批量解析耳号
            String[] tags = scDryMilk.getManageTags().trim().split("[\\s,，\n]+");
            int successCount = 0;
            StringBuilder errorMsg = new StringBuilder();

            for (String tag : tags) {
                if (tag.isEmpty()) continue;

                Long sheepId = scDryMilkService.selectSheepIdByManageTags(tag);
                if (sheepId == null) {
                    errorMsg.append(tag).append("不存在; ");
                    continue;
                }

                ScDryMilk newItem = new ScDryMilk();
                newItem.setSheepId(String.valueOf(sheepId));
                newItem.setDatetime(scDryMilk.getDatetime());
                newItem.setStatus(scDryMilk.getStatus());
                newItem.setSheepfold(scDryMilk.getSheepfold());
                newItem.setTecahnician(scDryMilk.getTecahnician());
                newItem.setComment(scDryMilk.getComment());
                newItem.setCreateBy(getUsername());

                scDryMilkService.insertScDryMilk(newItem);
                successCount++;
            }

            if (errorMsg.length() > 0) {
                return warn("成功录入 " + successCount + " 条。失败详情：" + errorMsg.toString());
            }
            return success("成功录入 " + successCount + " 条记录");
        } catch (Exception e) {
            logger.error("新增干奶记录失败", e);
            return error("新增失败: " + e.getMessage());
        }
    }

    /**
     * 修改干奶记录
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:edit')")
    @Log(title = "干奶记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScDryMilk scDryMilk)
    {
        return toAjax(scDryMilkService.updateScDryMilk(scDryMilk));
    }

    /**
     * 删除干奶记录
     */
    @PreAuthorize("@ss.hasPermi('drymilk:drymilk:remove')")
    @Log(title = "干奶记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scDryMilkService.deleteScDryMilkByIds(ids));
    }
}