 package com.huimv.management.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.management.entity.YearPigBaseEntity;
import com.huimv.management.service.YearPigBaseService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.huimv.management.entity.UnitEntity;
import com.huimv.management.service.UnitService;
import com.huimv.common.utils.PageUtils;
import com.huimv.common.utils.R;



/**
 * 单元信息表
 *
 * @author yinhao
 * @version 1.0
 * @date 2021-05-07 15:32:42
 */
@Api(tags = "单元信息表")
@RestController
@RequestMapping("management/unit")
public class UnitController {
    @Autowired
    private UnitService unitService;

    @Autowired
    private YearPigBaseService baseService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = unitService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
		UnitEntity unit = unitService.getById(id);

        return R.ok().put("unit", unit);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UnitEntity unit){
		unitService.save(unit);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UnitEntity unit){
        Integer currentPeriodId = unit.getCurrentPeriodId();

        Integer count = baseService.countByPeriodId(currentPeriodId);
        if (count > 0){
            return R.error("修改失败，栏期下面有未清理的小猪");
        }

        unitService.updateById(unit);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){

        for (Integer id : ids) {
            UnitEntity unit = unitService.getById(id);
            if (unit == null){
                return R.error("删除失败，栏期信息有误");
            }

            Integer currentPeriodId = unit.getCurrentPeriodId();
            Integer count = baseService.countByPeriodId(currentPeriodId);
            if (count > 0){
                return R.error("删除失败,栏期下有未清除的小猪");
            }
        }
		unitService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 查询全部
     */
    @RequestMapping("/findAll")
    public R findAll(@RequestParam("formFarmId") Integer formFarmId){
        List list = unitService.findAll(formFarmId);
        return R.ok().put("all",list);
    }

    @PostMapping("/findAllByPigstyId")
    public R findAllByFarmId(Integer id){
        List list = unitService.findAllByFarmId(id);

        return R.ok().put("all",list);
    }
}
