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

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.zhyc.common.utils.DateUtils;
import com.zhyc.common.utils.SecurityUtils;
import com.zhyc.common.utils.StringUtils;
import com.zhyc.module.base.domain.BasSheep;
import com.zhyc.module.base.service.IBasSheepService;
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.bodyManage.domain.ScBodyMeasure;
import com.zhyc.module.produce.bodyManage.service.IScBodyMeasureService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 体尺测量Controller
 *
 * @author ruoyi
 * @date 2025-07-27
 */
@RestController
@RequestMapping("/body_measure/body_measure")
public class ScBodyMeasureController extends BaseController {
    @Autowired
    private IScBodyMeasureService scBodyMeasureService;
    @Autowired
    private IBasSheepService basSheepService;

    /**
     * 查询体尺测量列表
     */
    @PreAuthorize("@ss.hasPermi('body_measure:body_measure:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScBodyMeasure scBodyMeasure) {
        startPage();
        List<ScBodyMeasure> list = scBodyMeasureService.selectScBodyMeasureList(scBodyMeasure);
        return getDataTable(list);
    }

    /**
     * 导出体尺测量列表
     */
    @PreAuthorize("@ss.hasPermi('body_measure:body_measure:export')")
    @Log(title = "体尺测量", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScBodyMeasure scBodyMeasure) {
        List<ScBodyMeasure> list = scBodyMeasureService.selectScBodyMeasureList(scBodyMeasure);
        ExcelUtil<ScBodyMeasure> util = new ExcelUtil<ScBodyMeasure>(ScBodyMeasure.class);
        util.exportExcel(response, list, "体尺测量数据");
    }

    /**
     * 获取体尺测量详细信息
     */
    @PreAuthorize("@ss.hasPermi('body_measure:body_measure:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(scBodyMeasureService.selectScBodyMeasureById(id));
    }

    /**
     * 新增体尺测量
     */
    @PreAuthorize("@ss.hasPermi('body_measure:body_measure:add')")
    @Log(title = "体尺测量", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScBodyMeasure scBodyMeasure) {
        scBodyMeasure.setUserId(getUserId());
        scBodyMeasure.setDeptId(getDeptId());
        return toAjax(scBodyMeasureService.insertScBodyMeasure(scBodyMeasure));
    }

    /**
     * 修改体尺测量
     */
    @PreAuthorize("@ss.hasPermi('body_measure:body_measure:edit')")
    @Log(title = "体尺测量", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScBodyMeasure scBodyMeasure) {
        return toAjax(scBodyMeasureService.updateScBodyMeasure(scBodyMeasure));
    }

    /**
     * 删除体尺测量
     */
    @PreAuthorize("@ss.hasPermi('body_measure:body_measure:remove')")
    @Log(title = "体尺测量", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(scBodyMeasureService.deleteScBodyMeasureByIds(ids));
    }

    @GetMapping("/search_ear_numbers")
    public AjaxResult searchEarNumbers(@RequestParam("query") String query) {
        return success(scBodyMeasureService.searchEarNumbers(query.trim()));
    }

    /**
     * 导入体尺测量数据
     */
    @PreAuthorize("@ss.hasPermi('body_measure:body_measure:import')")
    @Log(title = "体尺测量", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws Exception {
        ExcelUtil<ScBodyMeasure> util = new ExcelUtil<>(ScBodyMeasure.class);
        List<ScBodyMeasure> list = util.importExcel(file.getInputStream());

        // 数据校验和处理
        StringBuilder errorMsg = new StringBuilder();
        int successCount = 0;
        int failCount = 0;

        for (int i = 0; i < list.size(); i++) {
            ScBodyMeasure measure = list.get(i);
            try {
                // 根据耳号查询羊只ID
                if (StringUtils.isNotBlank(measure.getManageTags())) {
                    BasSheep sheep = basSheepService.selectBasSheepByManageTags(measure.getManageTags().trim());
                    if (sheep == null) {
                        failCount++;
                        errorMsg.append("第").append(i + 2).append("行：耳号【")
                                .append(measure.getManageTags()).append("】不存在；");
                        continue;
                    }
                    measure.setSheepId(sheep.getId());
                } else {
                    failCount++;
                    errorMsg.append("第").append(i + 2).append("行：耳号不能为空；");
                    continue;
                }

                // 设置默认值
                measure.setCreateTime(DateUtils.getNowDate());
                measure.setCreateBy(SecurityUtils.getUsername());

                // 数据分离：自动填充当前用户和部门
                measure.setUserId(getUserId());
                measure.setDeptId(getDeptId());
                scBodyMeasureService.insertScBodyMeasure(measure);
                successCount++;

                // 更新羊只当前体重
                if (measure.getCurrentWeight() != null) {
                    BasSheep updateSheep = new BasSheep();
                    updateSheep.setId(measure.getSheepId());
                    updateSheep.setCurrentWeight(measure.getCurrentWeight());
                    basSheepService.updateBasSheep(updateSheep);
                }
            } catch (Exception e) {
                failCount++;
                errorMsg.append("第").append(i + 2).append("行：").append(e.getMessage()).append("；");
            }
        }

        String msg = String.format("导入完成：成功%d条，失败%d条", successCount, failCount);
        if (failCount > 0) {
            msg += "；失败原因：" + errorMsg.toString();
        }
        return success(msg);
    }

    /**
     * 获取繁殖状态列表（用于下拉选择）
     */
    @GetMapping("/breedStatus")
    public AjaxResult listBreedStatus() {
        return success(scBodyMeasureService.selectBreedStatusList());
    }
}
