package com.weather.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.weather.entity.CropName;
import com.weather.service.ICropNameService;
import com.weather.vo.ApiResult;
import com.weather.vo.res.CropNameRes;
import com.weather.vo.res.IdNameRes;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 农作物信息 前端控制器
 * </p>
 *
 * @author : fengyuhao
 * @since 2021-02-02
 */
@RestController
@RequestMapping("/crop/type")

public class CropNameController {

    @Autowired

    ICropNameService cropNameService;

    @GetMapping("list")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "农作物类型", response = CropNameRes.class)

    public ApiResult list() {
        QueryWrapper<CropName>wrapper=new QueryWrapper<>();

        wrapper.lambda().orderByAsc(CropName::getId);

        List<CropName> list = cropNameService.list();
        if (list==null||list.size()<=0){
            return ApiResult.error("暂无农作物类型");
        }

        List<CropNameRes>resList=new ArrayList<>();

        String lastName=null;
        for (CropName item : list) {
            if (StringUtils.isEmpty(lastName)||!lastName.equalsIgnoreCase(item.getTypeName())){
                lastName=item.getTypeName();
                resList.add(new CropNameRes(lastName,new ArrayList<>()));
            }
        }
        for (CropNameRes item : resList) {
            for (CropName entity : list) {
                if (item.getName().equalsIgnoreCase(entity.getTypeName())){
                    item.getChild().add(new IdNameRes(entity.getId().toString(),entity.getName()));
                }
            }
        }

        return ApiResult.success(resList);
    }
}
