package com.dcit.danger.controller;

import java.util.*;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dcit.common.enums.ResultEnum;
import com.dcit.common.utils.BeanCopyUtil;
import com.dcit.common.utils.DateUtil;
import com.dcit.common.utils.KeyUtil;
import com.dcit.common.utils.ResultVOUtil;
import com.dcit.common.vo.ResultVO;
import com.dcit.danger.dto.EnterpriseGoodsDTO;
import com.dcit.danger.dto.form.EnterpriseGoodsForm;
import com.dcit.danger.dto.query.EnterpriseGoodsQuery;
import com.dcit.danger.exception.IOCException;
import com.dcit.danger.model.EnterpriseGoodsInfo;
import com.dcit.danger.model.EnterpriseGoodsInfoExample;
import com.dcit.danger.model.EnterpriseGoodsInfoExample.Criteria;
import com.dcit.danger.service.EnterpriseGoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(value="企业物品API")
@RestController
@RequestMapping("enterpriseGoods")
@Slf4j
public class EnterpriseGoodsController {
	
	@Autowired
	private EnterpriseGoodsService enterpriseGoodsService;
	
	@ApiOperation(value = "查询企业物品列表")
	@PostMapping("/selectEnterpriseGoodsList/{enterpriseId}")
	public ResultVO<Object> selectEnterpriseGoodsList(@PathVariable String enterpriseId, @RequestBody EnterpriseGoodsQuery enterpriseGoodsQuery){
		
		ModelMap modelMap = new ModelMap();
		
		try {
			PageHelper.offsetPage(enterpriseGoodsQuery.getPage(), enterpriseGoodsQuery.getSize());
			
			EnterpriseGoodsInfoExample example = new EnterpriseGoodsInfoExample();
			Criteria criteria = example.createCriteria();
			criteria.andEnterpriseIdEqualTo(enterpriseId).andIsDelEqualTo("0");
			if(!StringUtils.isEmpty(enterpriseGoodsQuery.getDataType())){
				criteria.andDataTypeEqualTo(enterpriseGoodsQuery.getDataType());
			}
			if(!StringUtils.isEmpty(enterpriseGoodsQuery.getGoodsName())){
				criteria.andGoodsInfoLike("%"+ enterpriseGoodsQuery.getGoodsName() +"%");
			}
			
			List<EnterpriseGoodsInfo> list = enterpriseGoodsService.selectByExample(example);
			
			PageInfo<EnterpriseGoodsInfo> pageList = new PageInfo<EnterpriseGoodsInfo>(list);
			
			List<EnterpriseGoodsDTO> dtoList = new ArrayList<EnterpriseGoodsDTO>();
			EnterpriseGoodsDTO dto = null;
			
			for(EnterpriseGoodsInfo enterpriseGoodsInfo : pageList.getList()){
				dto = new EnterpriseGoodsDTO();
				BeanUtils.copyProperties(enterpriseGoodsInfo, dto, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseGoodsInfo, null));
				
				dtoList.add(dto);
			}
			
			modelMap.addAttribute("pageData", dtoList);
			modelMap.addAttribute("total", pageList.getTotal());
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【查询企业物品列表】操作出错,error={}",e.getMessage());
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success(modelMap);
		
	}
	
	@ApiOperation(value = "新增编辑企业物品")
	@PostMapping("/addOrEditEnterpriseGoods")
	public ResultVO<Object> addOrEditEnterpriseGoods(@RequestBody EnterpriseGoodsForm enterpriseGoodsForm, BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			log.error("【新增编辑企业物品】参数不正确,enterpriseGoodsForm={}",enterpriseGoodsForm);
			throw new IOCException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
		}
		
		EnterpriseGoodsDTO dto = new EnterpriseGoodsDTO();
		
		EnterpriseGoodsInfo enterpriseGoodsInfo = null;
		try {
			if(StringUtils.isEmpty(enterpriseGoodsForm.getId())){
				enterpriseGoodsInfo = new EnterpriseGoodsInfo();
				
				BeanUtils.copyProperties(enterpriseGoodsForm, enterpriseGoodsInfo, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseGoodsForm, null));
				
				enterpriseGoodsInfo.setId(KeyUtil.getUUIDKey());
				if(!StringUtils.isEmpty(enterpriseGoodsForm.getAddTime())){
					enterpriseGoodsInfo.setAddTime(DateUtil.parseDate(DateUtil.C_TIME_PATTON_DEFAULT, enterpriseGoodsForm.getAddTime()));
				}
				if(!StringUtils.isEmpty(enterpriseGoodsForm.getOutTime())){
					enterpriseGoodsInfo.setOutTime(DateUtil.parseDate(DateUtil.C_TIME_PATTON_DEFAULT, enterpriseGoodsForm.getOutTime()));
				}
				enterpriseGoodsService.insertSelective(enterpriseGoodsInfo);
			}else{
				enterpriseGoodsInfo = enterpriseGoodsService.selectByPrimaryKey(enterpriseGoodsForm.getId());
				if(null != enterpriseGoodsInfo){
					BeanUtils.copyProperties(enterpriseGoodsForm, enterpriseGoodsInfo, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseGoodsForm, null));
					if(!StringUtils.isEmpty(enterpriseGoodsForm.getAddTime())){
						enterpriseGoodsInfo.setAddTime(DateUtil.parseDate(DateUtil.C_TIME_PATTON_DEFAULT, enterpriseGoodsForm.getAddTime()));
					}
					if(!StringUtils.isEmpty(enterpriseGoodsForm.getOutTime())){
						enterpriseGoodsInfo.setOutTime(DateUtil.parseDate(DateUtil.C_TIME_PATTON_DEFAULT, enterpriseGoodsForm.getOutTime()));
					}
					enterpriseGoodsInfo.setUpdateTime(new Date());
					enterpriseGoodsService.updateByPrimaryKeySelective(enterpriseGoodsInfo);
				}else{
					log.error("【编辑企业物品信息】操作出错,企业物品不存在");
					throw new IOCException(ResultEnum.OPERATION_FAIL);
				}
			}
			
			BeanUtils.copyProperties(enterpriseGoodsInfo, dto, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseGoodsInfo, null));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【新增编辑企业物品信息】操作出错,error={}",e.getMessage());
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}
		return ResultVOUtil.success(dto);
	}
	
	@ApiOperation(value = "删除企业物品")
	@GetMapping("/deleteEnterpriseGoodsById/{enterpriseId}")
	public ResultVO<Object> deleteEnterpriseGoodsById(@PathVariable String enterpriseId){
		try {
			EnterpriseGoodsInfo enterpriseGoodsInfo = enterpriseGoodsService.selectByPrimaryKey(enterpriseId);
			if(null != enterpriseGoodsInfo){
				enterpriseGoodsInfo.setIsDel("1");
				enterpriseGoodsInfo.setUpdateTime(new Date());
				enterpriseGoodsService.updateByPrimaryKeySelective(enterpriseGoodsInfo);
			}else{
				log.error("【删除企业物品】操作出错,企业物品不存在");
				throw new IOCException(ResultEnum.OPERATION_FAIL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【删除企业物品】操作出错,error={}",e.getMessage());
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}
		return ResultVOUtil.success();
	}

	@ApiOperation(value = "按企业统计危险源数量")
	@GetMapping("/getNumberByEnterprise")
	public ResultVO<Object> getNumberByEnterprise(){

		ModelMap modelMap = new ModelMap();
		List<Map<Object, Object>> newList = new ArrayList<>();

		List<Map<Object, Object>> list = enterpriseGoodsService.countByEnterprise();
		if(list.size() == 0){
			log.error("【按企业统计危险源数量】出错");
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}

		//显示危险源数量最多的前5个企业，其余显示为其他
		if(list.size() > 6) {
			Integer count = 0,x = 0;

			for (Map<Object, Object> map : list) {

				if(x < 5){
					newList.add(map);
				}else{
					count += Integer.valueOf(map.get("number").toString());
				}

				x++;
			}

			Map<Object, Object> map = new HashMap<>();
			map.put("name", "其他");
			map.put("number", count);
			newList.add(map);
		}else{
			newList.addAll(list);
		}

		modelMap.addAttribute("result", newList);
		return ResultVOUtil.success(modelMap);
	}

	@ApiOperation(value = "查询危险源信息")
	@GetMapping("/getMapEnterpriseGoodsById/{id}")
	public ResultVO<Object> getMapEnterpriseGoodsById(@PathVariable String id){
		EnterpriseGoodsInfo enterpriseGoodsInfo = enterpriseGoodsService.selectByPrimaryKey(id);

		EnterpriseGoodsDTO dto = new EnterpriseGoodsDTO();
		BeanUtils.copyProperties(enterpriseGoodsInfo, dto, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseGoodsInfo, null));

		return ResultVOUtil.success(dto);
	}

	@ApiOperation(value = "修改危险源信息")
	@PostMapping("/editMapEnterpriseGoods")
	public ResultVO<Object> editMapEnterpriseGoods(@RequestBody EnterpriseGoodsForm enterpriseGoodsForm){
		EnterpriseGoodsInfo enterpriseGoodsInfo = enterpriseGoodsService.selectByPrimaryKey(enterpriseGoodsForm.getId());

		if(enterpriseGoodsInfo != null){
			BeanUtils.copyProperties(enterpriseGoodsForm, enterpriseGoodsInfo,BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseGoodsForm, null));
			enterpriseGoodsService.updateByPrimaryKey(enterpriseGoodsInfo);
		}
		return ResultVOUtil.success(enterpriseGoodsInfo);
	}
}
