package com.dcit.danger.controller;

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

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.authority.dto.UserRolesInfoDTO;
import com.dcit.authority.model.SysUser;
import com.dcit.authority.model.SysUserRoles;
import com.dcit.authority.service.SysUserService;
import com.dcit.common.enums.ResultEnum;
import com.dcit.common.utils.KeyUtil;
import com.dcit.common.utils.ResultVOUtil;
import com.dcit.common.vo.ResultVO;
import com.dcit.danger.config.ProjectPath;
import com.dcit.danger.dto.EnterpriseDangerNumDTO;
import com.dcit.danger.dto.EnterpriseRegDTO;
import com.dcit.danger.dto.form.CancelEnterpriseInfoForm;
import com.dcit.danger.dto.form.EnterpriseCheckInfoForm;
import com.dcit.danger.dto.query.EnterpriseInfoQuery;
import com.dcit.danger.exception.IOCException;
import com.dcit.danger.model.EnterpriseBasicInfo;
import com.dcit.danger.model.EnterpriseGoodsInfoExample;
import com.dcit.danger.service.EnterpriseGoodsService;
import com.dcit.danger.service.EnterpriseInfoService;
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("enterpriseInfo")
@Slf4j
public class EnterpriseInfoController {
	
	@Autowired
	private EnterpriseInfoService enterpriseInfoService;
	
	@Autowired
	private EnterpriseGoodsService enterpriseGoodsService;
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private ProjectPath projectPath;
	
	@ApiOperation(value = "查询信息列表")
	@PostMapping("/queryEnterpriseInfo")
	public ResultVO<Object> queryEnterpriseInfo(@RequestBody EnterpriseInfoQuery enterpriseInfoQuery){
		ModelMap modelMap = new ModelMap();
		try {
			PageHelper.offsetPage(enterpriseInfoQuery.getPage(), enterpriseInfoQuery.getSize());
			
			List<EnterpriseRegDTO> list = enterpriseInfoService.selectEnterpriseRegInfo(enterpriseInfoQuery);
			
			PageInfo<EnterpriseRegDTO> pageInfoList = new PageInfo<EnterpriseRegDTO>(list);
			
			modelMap.addAttribute("pageData", pageInfoList.getList());
			modelMap.addAttribute("total", pageInfoList.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【查询企业列表查询】操作出错,error={}",e.getMessage());
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success(modelMap);
	}
	
	@ApiOperation(value = "根据Id查询企业详情")
	@GetMapping("/queryEnterpriseInfoById/{enterpriseId}")
	public ResultVO<Object> queryEnterpriseInfoById(@PathVariable String enterpriseId){
			
		EnterpriseRegDTO dto = enterpriseInfoService.selectEnterpriseRegInfoById(enterpriseId);
		
		if(!StringUtils.isEmpty(dto.getOrgFilePath())){
			dto.setViewOrgFilePath(projectPath.getFileUrlPath() + dto.getOrgFilePath());
		}
		if(!StringUtils.isEmpty(dto.getAuthorizeFile())){
			dto.setViewAuthorizeFile(projectPath.getFileUrlPath() + dto.getAuthorizeFile());
		}
			
		return ResultVOUtil.success(dto);
	}
	
	@ApiOperation(value = "地图气泡企业详情")
	@GetMapping("/getMapEnterpriseInfoById/{enterpriseId}")
	public ResultVO<Object> getMapEnterpriseInfoById(@PathVariable String enterpriseId){
		
		ModelMap modelMap = new ModelMap();
		try {
			EnterpriseRegDTO dto = enterpriseInfoService.selectEnterpriseRegInfoById(enterpriseId);
			
			if(!StringUtils.isEmpty(dto.getOrgFilePath())){
				dto.setViewOrgFilePath(projectPath.getFileUrlPath() + dto.getOrgFilePath());
			}
			if(!StringUtils.isEmpty(dto.getAuthorizeFile())){
				dto.setViewAuthorizeFile(projectPath.getFileUrlPath() + dto.getAuthorizeFile());
			}
			EnterpriseGoodsInfoExample enterpriseGoodsInfoExample = new EnterpriseGoodsInfoExample();
			enterpriseGoodsInfoExample.createCriteria().andEnterpriseIdEqualTo(enterpriseId).andIsBigDangerEqualTo("1");
			long bigDangerNum = enterpriseGoodsService.countByExample(enterpriseGoodsInfoExample);
			
			List<EnterpriseDangerNumDTO> numDto = enterpriseInfoService.selectEnterpriseDangerNum(enterpriseId);
			
			modelMap.addAttribute("enterpriseInfo", dto);
			modelMap.addAttribute("bigDangerNum", bigDangerNum);
			modelMap.addAttribute("dangerNum", numDto);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【地图气泡企业详情】操作出错,error={}",e.getMessage());
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}
		
		
		return ResultVOUtil.success(modelMap);
	}
	
	@ApiOperation(value = "编辑企业审核状态")
	@PostMapping("/updateEnterpriseCheckStatusById/{enterpriseId}")
	public ResultVO<Object> updateEnterpriseInfoById(@PathVariable String enterpriseId,@RequestBody EnterpriseCheckInfoForm enterpriseCheckInfoForm,BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			log.error("【编辑企业审核状态】参数不正确,enterpriseCheckInfoForm={}",enterpriseCheckInfoForm);
			throw new IOCException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			EnterpriseRegDTO dto = enterpriseInfoService.selectEnterpriseRegInfoById(enterpriseId);
			if(null != dto && !StringUtils.isEmpty(dto.getUserId())){
				SysUser sysUser = sysUserService.selectByPrimaryKey(dto.getUserId());
				if(null != sysUser){
					sysUser.setAccountStatus(enterpriseCheckInfoForm.getAccountStatus());
					sysUser.setRemarks(enterpriseCheckInfoForm.getRemarks());
					sysUserService.updateByPrimaryKeySelective(sysUser);
					
					SysUserRoles sysUserRoles = new SysUserRoles();
					List<UserRolesInfoDTO> list = sysUserService.selectUserRolesInfoByUid(sysUser.getUid());
					if(list.size() == 0){
						sysUserRoles.setId(KeyUtil.getUUIDKey());
						sysUserRoles.setUserId(sysUser.getUid());
						sysUserRoles.setRoleId("73ab0733e6a24ed89cf91a06919d3637");
						sysUserService.addOrEditUserRoles(sysUserRoles);
					}
					
					EnterpriseBasicInfo enterpriseBasicInfo = new EnterpriseBasicInfo();
					enterpriseBasicInfo.setId(dto.getEnterpriseId());
					enterpriseBasicInfo.setLatitude(enterpriseCheckInfoForm.getLatitude());
					enterpriseBasicInfo.setLongitude(enterpriseCheckInfoForm.getLongitude());
					enterpriseBasicInfo.setBoundary(enterpriseCheckInfoForm.getBoundary());
					enterpriseBasicInfo.setRegulationBigType(enterpriseCheckInfoForm.getRegulationBigType());
					enterpriseBasicInfo.setUpdateTime(new Date());
					enterpriseBasicInfo.setUpdateUserId(null);
					enterpriseInfoService.updateEnterpriseInfoById(enterpriseBasicInfo);
				}else{
					log.error("【编辑企业审核状态】管理员不存在");
					throw new IOCException(ResultEnum.OPERATION_FAIL);
				}
			}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 = "企业注销")
	@PostMapping("/cancelEnterpriseInfoById/{enterpriseId}")
	public ResultVO<Object> cancelEnterpriseInfoById(@PathVariable String enterpriseId,@RequestBody CancelEnterpriseInfoForm cancelEnterpriseInfoForm){
		
		try {
			EnterpriseRegDTO dto = enterpriseInfoService.selectEnterpriseRegInfoById(enterpriseId);
			if(null != dto && !StringUtils.isEmpty(dto.getUserId())){
				SysUser sysUser = sysUserService.selectByPrimaryKey(dto.getUserId());
				if(null != sysUser){
					sysUser.setAccountStatus("2");
					sysUser.setRemarks(cancelEnterpriseInfoForm.getRemarks());
					sysUserService.updateByPrimaryKeySelective(sysUser);
					
					//删除用户角色
//					sysUserService.deleteUserRolesByUserId(sysUser.getUid());
					
					EnterpriseBasicInfo enterpriseBasicInfo = new EnterpriseBasicInfo();
					enterpriseBasicInfo.setId(dto.getEnterpriseId());
					enterpriseBasicInfo.setIsEnable("1");
					enterpriseInfoService.updateEnterpriseInfoById(enterpriseBasicInfo);
				}else{
					log.error("【企业注销】管理员不存在");
					throw new IOCException(ResultEnum.OPERATION_FAIL);
				}
			}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("/enableEnterpriseInfoById/{enterpriseId}")
	public ResultVO<Object> enableEnterpriseInfoById(@PathVariable String enterpriseId){

		try {
			EnterpriseRegDTO dto = enterpriseInfoService.selectEnterpriseRegInfoById(enterpriseId);
			if(null != dto && !StringUtils.isEmpty(dto.getUserId())){
				SysUser sysUser = sysUserService.selectByPrimaryKey(dto.getUserId());
				if(null != sysUser){
					sysUser.setAccountStatus("0");
					sysUserService.updateByPrimaryKeySelective(sysUser);

					EnterpriseBasicInfo enterpriseBasicInfo = new EnterpriseBasicInfo();
					enterpriseBasicInfo.setId(dto.getEnterpriseId());
					enterpriseBasicInfo.setIsEnable("0");
					enterpriseInfoService.updateEnterpriseInfoById(enterpriseBasicInfo);
				}else{
					log.error("【企业用户启用】管理员不存在");
					throw new IOCException(ResultEnum.OPERATION_FAIL);
				}
			}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("/getNumberByRegulation")
	public ResultVO<Object> getNumberByRegulation(){

		List<Map<Object, Object>> list = enterpriseInfoService.countByRegulation();
		ModelMap modelMap = new ModelMap();

		if(list.size() == 0){
			log.error("【按监管分类统计企业数量】出错");
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}

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

	@ApiOperation(value = "查询信息列表")
	@PostMapping("/queryEnterpriseListInfo")
	public ResultVO<Object> queryEnterpriseListInfo(@RequestBody EnterpriseInfoQuery enterpriseInfoQuery){
		List<EnterpriseRegDTO> list = new ArrayList<>();
		try {
			list = enterpriseInfoService.selectEnterpriseRegInfo(enterpriseInfoQuery);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【查询企业列表】操作出错,error={}",e.getMessage());
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}

		return ResultVOUtil.success(list);
	}
}
