package com.dcit.danger.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dcit.authority.model.SysUser;
import com.dcit.authority.service.SysUserService;
import com.dcit.danger.dto.node.DeviceTreeNode;
import com.dcit.authority.exception.AuthException;
import com.dcit.danger.model.EnterpriseBasicInfo;
import com.dcit.danger.model.EnterpriseBasicInfoExample;
import com.dcit.danger.service.EnterpriseInfoService;
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.KeyUtil;
import com.dcit.common.utils.ResultVOUtil;
import com.dcit.common.vo.ResultVO;
import com.dcit.danger.dto.SafetyDeviceInfoDTO;
import com.dcit.danger.dto.form.SafetyDeviceInfoForm;
import com.dcit.danger.dto.query.SafetyDeviceInfoQuery;
import com.dcit.danger.exception.IOCException;
import com.dcit.danger.model.SafetyDeviceInfo;
import com.dcit.danger.model.SafetyDeviceInfoExample;
import com.dcit.danger.model.SafetyDeviceInfoExample.Criteria;
import com.dcit.danger.service.SafetyDeviceInfoService;
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("safetyDeviceInfo")
@Slf4j
public class SafetyDeviceInfoController {
	
	@Autowired
	private SafetyDeviceInfoService safetyDeviceInfoService;
	@Autowired
	private EnterpriseInfoService enterpriseInfoService;
	@Autowired
	private SysUserService sysUserService;

	@ApiOperation(value = "获取企业视频监控树")
	@GetMapping("/getDeviceTree")
	public ResultVO<Object> getDeviceTree(){

		EnterpriseBasicInfoExample enterpriseBasicInfoExample = new EnterpriseBasicInfoExample();
		enterpriseBasicInfoExample.createCriteria().andIsEnableEqualTo("0");
		List<EnterpriseBasicInfo> enterpriseBasicInfoList = enterpriseInfoService.selectEnterpriseInfoByExample(enterpriseBasicInfoExample);

		List<DeviceTreeNode> treeNodeList = new ArrayList<DeviceTreeNode>();

		try {
			DeviceTreeNode treeNode = null;
			DeviceTreeNode childNode = null;

			for(EnterpriseBasicInfo enterpriseBasicInfo : enterpriseBasicInfoList){

				if(null != enterpriseBasicInfo && !StringUtils.isEmpty(enterpriseBasicInfo.getCreateUserId())) {
					SysUser sysUser = sysUserService.selectByPrimaryKey(enterpriseBasicInfo.getCreateUserId());

					if (null != sysUser && "0".equals(sysUser.getAccountStatus())) {
						treeNode = new DeviceTreeNode();
						treeNode.setEnterpriseId(enterpriseBasicInfo.getId());
						treeNode.setName(enterpriseBasicInfo.getUnitName());
						treeNode.setLevel("1");

						SafetyDeviceInfoExample safetyDeviceInfoExample = new SafetyDeviceInfoExample();
						safetyDeviceInfoExample.createCriteria().andIsDelEqualTo("0").andDataTypeEqualTo("1").andEnterpriseIdEqualTo(enterpriseBasicInfo.getId());
						List<SafetyDeviceInfo> safetyDeviceInfoList = safetyDeviceInfoService.selectByExample(safetyDeviceInfoExample);

						List<DeviceTreeNode> childNodeList = new ArrayList<DeviceTreeNode>();
						for(SafetyDeviceInfo safetyDeviceInfo : safetyDeviceInfoList){
							childNode = new DeviceTreeNode();
							childNode.setEnterpriseId(safetyDeviceInfo.getEnterpriseId());
							childNode.setName(safetyDeviceInfo.getDeviceName());
							childNode.setDeviceNumber(safetyDeviceInfo.getDeviceNumber());
							childNode.setLevel("2");

							childNodeList.add(childNode);
						}

						treeNode.setChildList(childNodeList);
						treeNodeList.add(treeNode);
					}
				}
			}

		} catch (Exception e) {
			log.error("【获取组织机构树】操作失败,e={}",e.getMessage());
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}

		return ResultVOUtil.success(treeNodeList);
	}
	
	@ApiOperation(value = "查询企业安全设备列表")
	@PostMapping("/selectSafetyDeviceInfoList/{enterpriseId}")
	public ResultVO<Object> selectSafetyDeviceInfoList(@PathVariable String enterpriseId, @RequestBody SafetyDeviceInfoQuery safetyDeviceInfoQuery){
		
		ModelMap modelMap = new ModelMap();
		
		try {
			PageHelper.offsetPage(safetyDeviceInfoQuery.getPage(), safetyDeviceInfoQuery.getSize());
			
			SafetyDeviceInfoExample safetyDeviceInfoExample = new SafetyDeviceInfoExample();
			
			Criteria criteria = safetyDeviceInfoExample.createCriteria();
			if(!"all".equals(enterpriseId)&&!"".equals(enterpriseId)){
				criteria.andEnterpriseIdEqualTo(enterpriseId);
			}
			criteria.andIsDelEqualTo("0");
			if(!StringUtils.isEmpty(safetyDeviceInfoQuery.getDataType())){
				criteria.andDataTypeEqualTo(safetyDeviceInfoQuery.getDataType());
			}
			if(!StringUtils.isEmpty(safetyDeviceInfoQuery.getDeviceName())){
				criteria.andDeviceNameLike("%"+ safetyDeviceInfoQuery.getDeviceName() +"%");
			}
			
			List<SafetyDeviceInfo> safetyDeviceList = safetyDeviceInfoService.selectByExample(safetyDeviceInfoExample);
			
			PageInfo<SafetyDeviceInfo> pageList = new PageInfo<SafetyDeviceInfo>(safetyDeviceList);
			
			List<SafetyDeviceInfoDTO> dtoList = new ArrayList<SafetyDeviceInfoDTO>();
			SafetyDeviceInfoDTO dto = null;
			for(SafetyDeviceInfo safetyDeviceInfo : pageList.getList()){
				dto = new SafetyDeviceInfoDTO();
				BeanUtils.copyProperties(safetyDeviceInfo, dto, BeanCopyUtil.getNullOrIgnorePropertyNames(safetyDeviceInfo, 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("/addOrEditSafetyDeviceInfo")
	public ResultVO<Object> addOrEditSafetyDeviceInfo(@RequestBody SafetyDeviceInfoForm safetyDeviceInfoForm, BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			log.error("【新增编辑企业安全设备】参数不正确, safetyDeviceInfoForm={}",safetyDeviceInfoForm);
			throw new IOCException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
		}
		
		SafetyDeviceInfoDTO dto = new SafetyDeviceInfoDTO();
		
		SafetyDeviceInfo safetyDeviceInfo = null;
		
		try {
			if(StringUtils.isEmpty(safetyDeviceInfoForm.getId())){
				safetyDeviceInfo = new SafetyDeviceInfo();
				BeanUtils.copyProperties(safetyDeviceInfoForm, safetyDeviceInfo, BeanCopyUtil.getNullOrIgnorePropertyNames(safetyDeviceInfoForm, null));
				safetyDeviceInfo.setId(KeyUtil.getUUIDKey());
				//safetyDeviceInfo.setEnterpriseId(enterpriseId);
				
				safetyDeviceInfoService.insertSelective(safetyDeviceInfo);
			}else{
				safetyDeviceInfo = safetyDeviceInfoService.selectByPrimaryKey(safetyDeviceInfoForm.getId());
				if(null != safetyDeviceInfo){
					BeanUtils.copyProperties(safetyDeviceInfoForm, safetyDeviceInfo, BeanCopyUtil.getNullOrIgnorePropertyNames(safetyDeviceInfoForm, null));
					safetyDeviceInfo.setUpdateTime(new Date());
					
					safetyDeviceInfoService.updateByPrimaryKeySelective(safetyDeviceInfo);
				}else{
					log.error("【编辑企业安全设备】操作出错,企业安全设备不存在");
					throw new IOCException(ResultEnum.OPERATION_FAIL);
				}
			}
			
			BeanUtils.copyProperties(safetyDeviceInfo, dto, BeanCopyUtil.getNullOrIgnorePropertyNames(safetyDeviceInfo, null));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【新增编辑企业安全设备】操作出错,error={}",e.getMessage());
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success(dto);
	}

	@ApiOperation(value = "删除企业安全设备")
	@GetMapping("/deleteSafetyDeviceInfoById/{deviceId}")
	public ResultVO<Object> deleteSafetyDeviceInfoById(@PathVariable String deviceId){
		try {
			SafetyDeviceInfo safetyDeviceInfo = safetyDeviceInfoService.selectByPrimaryKey(deviceId);
			if(null != safetyDeviceInfo){
				safetyDeviceInfo.setIsDel("1");
				safetyDeviceInfo.setUpdateTime(new Date());
				
				safetyDeviceInfoService.updateByPrimaryKeySelective(safetyDeviceInfo);
			}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("/getSafetyDeviceInfoById/{id}")
	public ResultVO<Object> getSafetyDeviceInfoById(@PathVariable String id){
		SafetyDeviceInfo safetyDeviceInfo = safetyDeviceInfoService.selectByPrimaryKey(id);

		SafetyDeviceInfoDTO dto = new SafetyDeviceInfoDTO();
		BeanUtils.copyProperties(safetyDeviceInfo, dto, BeanCopyUtil.getNullOrIgnorePropertyNames(safetyDeviceInfo, null));

		return ResultVOUtil.success(dto);
	}

}
