package com.yeejoin.equipmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.entity.Equipment;
import com.yeejoin.equipmanage.common.entity.Unit;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.NameUtils;
import com.yeejoin.equipmanage.service.IEquipmentIndexService;
import com.yeejoin.equipmanage.service.IEquipmentService;
import com.yeejoin.equipmanage.service.IUnitService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 计量单位
 *
 * @author wujiang
 * @date 2020-07-07
 */
@RestController
@Api(tags = "计量单位Api")
@RequestMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class UnitController {

  @Autowired
  IUnitService iUnitService;
  
  @Autowired
  IEquipmentService iEquipmentService;
  
  @Autowired
  IEquipmentIndexService equipmentIndexService;


    /**
	 * <pre>
	 * 获取计量单位层级关系
	 * </pre>
	 *
	 * @return
	 * 	    CommonResponse
	 * @throws
	 * @version: 1.0
	 */
	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取计量单位层级关系(<font color='blue'>release</font>)", notes = "获取计量单位层级关系")
	@RequestMapping(value = "/get-unitClassification", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public ResponseModel getUnitClassification() {
		List<Map<String, Object>> results = iUnitService.getUnitClassification();
		return CommonResponseUtil.success(results);
	}
	
    /**
    * 新增计量单位
    * @return
    */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "新增计量单位", notes = "新增计量单位")
    public ResponseModel saveUnit(HttpServletRequest request, @RequestBody Unit unit){
	 	this.iUnitService.saveUnit(unit);
	 	return CommonResponseUtil.success();
    }


    /**
     * 根据id删除
     * @param ids
     * @return
     */
     @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
     @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
     public ResponseModel deleteById(@ApiParam(value = "装备分类id数组", required = true) @RequestParam("ids") String... ids){
     	List<String> idList = new ArrayList<String>(Arrays.asList(ids));
     	QueryWrapper<Unit> queryWrapper = new QueryWrapper<Unit>();
     	queryWrapper.lambda().in(Unit::getParentId, idList);
 		int count = this.iUnitService.count(queryWrapper);
 		if(count>0){
 			return CommonResponseUtil.failure("此计量单位下存在子单位，请先删除子节点！");
 		}
 		
 		QueryWrapper<Equipment> equipQueryWrapper = new QueryWrapper<Equipment>();
 		equipQueryWrapper.lambda().in(Equipment::getUnitId, idList);
 		int equipCount = this.iEquipmentService.count(equipQueryWrapper);
		if(equipCount>0){
			return CommonResponseUtil.failure("此计量单位已经使用，不能删除。");
		}
		
        List<Unit> list = iUnitService.getUnitListsById(idList);
		List<String> lists = list.stream().map(Unit::getName).collect(Collectors.toList());
 		int perfQuotaCount = equipmentIndexService.checkUnit(lists);
		if(perfQuotaCount>0){
			return CommonResponseUtil.failure("此计量单位已经使用，不能删除。");
		}
     	return CommonResponseUtil.success(this.iUnitService.removeByIds(idList));
     }

    /**
    * 修改计量单位
    * @return
    */
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "修改计量单位", notes = "修改计量单位")
    public boolean updateByIdUnit(HttpServletRequest request, @RequestBody Unit unit){
    return iUnitService.updateById(unit);
    }



    /**
   * 根据id查询
   * @param id
   * @return
   */
   @RequestMapping(value = "/{id}", method = RequestMethod.GET)
       @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
   public Unit selectById(HttpServletRequest request, @PathVariable Long id){
      return iUnitService.getById(id);
   }




  /**
  * 列表分页查询
  * @return
  */
  @RequestMapping(value = "/list", method = RequestMethod.GET)
      @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
  public IPage<Unit> listPage(String pageNum,String pageSize,
    Unit unit){

    Page<Unit> pageBean;
    QueryWrapper<Unit> unitQueryWrapper = new QueryWrapper<>();
    Class<? extends Unit> aClass = unit.getClass();
    Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
        try {
            field.setAccessible(true);
            Object o = field.get(unit);
            if (o != null) {
                Class<?> type = field.getType();
                String name = NameUtils.camel2Underline(field.getName());
                if (type.equals(Integer.class)) {
                Integer fileValue = (Integer) field.get(unit);
                unitQueryWrapper.eq(name, fileValue);
                } else if (type.equals(Long.class)) {
                Long fileValue = (Long) field.get(unit);
                unitQueryWrapper.eq(name, fileValue);
                } else if (type.equals(String.class)) {
                String fileValue = (String) field.get(unit);
                unitQueryWrapper.eq(name, fileValue);
                } else {
                String fileValue = (String) field.get(unit);
                unitQueryWrapper.eq(name, fileValue);
            }
          }
        }catch (Exception e) {
        }
    });
    IPage<Unit> page;
    if (StringUtils.isBlank(pageNum)  ||StringUtils.isBlank(pageSize)) {
        pageBean = new Page<>(0, Long.MAX_VALUE);
    }else{
        pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
    }
    page = iUnitService.page(pageBean, unitQueryWrapper);
    return page;
  }
  
  /**
   * 全量数据树形结构返回
   * @return
   */
   @RequestMapping(value = "/list-tree", method = RequestMethod.GET)
       @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "全量数据树形结构返回", notes = "全量数据树形结构返回")
   public ResponseModel list(Unit unit){
       QueryWrapper<Unit> unitQueryWrapper = new QueryWrapper<>();
       if(!ObjectUtils.isEmpty(unit.getName())){
           unitQueryWrapper.lambda().like(Unit::getName, unit.getName());
       }
       List<Unit> units = this.iUnitService.getUnitList(unit);
       List<Unit> newUnits = units.stream().distinct().collect(Collectors.toList());
       List<Unit> list = new ArrayList<>();
       Map <String,List<Unit>> tmpMap = new HashMap<String,List<Unit>>();
       newUnits.forEach(action->{
           // 获得是父节点的所有对象
           if(ObjectUtils.isEmpty(action.getParentId())){
               list.add(action);
           }else{
               // 添加子节点信息，如果暂存Map里没有则添加
               if(tmpMap.get(action.getParentId().toString())==null){
                   ArrayList<Unit> tmplist = new ArrayList<Unit>();
                   tmplist.add(action);
                   tmpMap.put(action.getParentId().toString(), tmplist);
               }else {
                       // 暂存Map里有子节点信息，但是不包含兄弟节点信息则添加兄弟节点信息
                   if(!tmpMap.get(action.getParentId().toString()).contains(action)){
                       tmpMap.get(action.getParentId().toString()).add(action);
                   }
               }

           }
       });
       // list包含所有父节点信息，tmpMap包含所有子节点信息，通过parentId进行关联
       getChildren(list,tmpMap);
       return CommonResponseUtil.success(list);
   }
   
   private void getChildren(List<Unit> list, Map <String,List<Unit>> tmpMap)
	{
		for(Unit unit:list){
			if(!ObjectUtils.isEmpty(tmpMap.get(unit.getId().toString()))){
				List<Unit> unitList = tmpMap.get(unit.getId().toString());
				unit.setHasLowerClassification(true);
				unit.setChildren(unitList);
			}
		}
	}
}


