package com.dcit.danger.controller;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.constant.Const;
import com.dcit.authority.model.SysUser;
import com.dcit.authority.service.SysUserService;
import com.dcit.common.enums.ResultEnum;
import com.dcit.common.utils.BeanCopyUtil;
import com.dcit.common.utils.KeyUtil;
import com.dcit.common.utils.RandomValidateCode;
import com.dcit.common.utils.ResultVOUtil;
import com.dcit.common.utils.StrEncryptUtil;
import com.dcit.common.vo.ResultVO;
import com.dcit.danger.config.ProjectPath;
import com.dcit.danger.dto.EnterpriseRegDTO;
import com.dcit.danger.dto.form.EnterpriseRegForm;
import com.dcit.danger.exception.IOCException;
import com.dcit.danger.model.EnterpriseBasicInfo;
import com.dcit.danger.model.EnterpriseBasicInfoExample;
import com.dcit.danger.service.EnterpriseInfoService;

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

@Api(value="企业注册相关接口")
@RestController
@RequestMapping("reg")
@Slf4j
public class RegController {
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private EnterpriseInfoService enterpriseInfoService;
	
	@Autowired
	private ProjectPath projectPath;
	
	@ApiOperation(value = "企业注册")
    @PostMapping("/enterpriseReg")
	@Transactional
	public ResultVO<Object> enterpriseReg(@RequestBody EnterpriseRegForm enterpriseRegForm, BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			log.error("【企业注册】参数不正确,enterpriseRegForm={}",enterpriseRegForm);
			throw new IOCException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
		}
		
		try {
			
			if(StringUtils.isEmpty(enterpriseRegForm.getUserId()) && StringUtils.isEmpty(enterpriseRegForm.getEnterPriseId())){
				SysUser sysUser = new SysUser();
				EnterpriseBasicInfo enterpriseBasicInfo = new EnterpriseBasicInfo();
				
				BeanUtils.copyProperties(enterpriseRegForm, sysUser, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseRegForm, null));
				sysUser.setAccountStatus("3");
				sysUser.setAccountType("2");
				sysUser.setUid(KeyUtil.getUUIDKey());
				sysUser.setSalt(RandomValidateCode.getRandomString(8));
        		sysUser.setAccountPwd(StrEncryptUtil.md5(enterpriseRegForm.getAccountPwd() + sysUser.getSalt()));
				
				BeanUtils.copyProperties(enterpriseRegForm, enterpriseBasicInfo, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseRegForm, null));
				
				enterpriseBasicInfo.setId(KeyUtil.getUUIDKey());
				sysUser.setDeptId(enterpriseBasicInfo.getId());
				sysUserService.insertSelective(sysUser);
				
				enterpriseBasicInfo.setCreateUserId(sysUser.getUid());				
				enterpriseInfoService.addEnterpriseInfo(enterpriseBasicInfo);
			}else{
				SysUser sysUser = sysUserService.selectByPrimaryKey(enterpriseRegForm.getUserId());
				BeanUtils.copyProperties(enterpriseRegForm, sysUser, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseRegForm, null));
				sysUser.setAccountStatus("3");
				sysUserService.updateByPrimaryKeySelective(sysUser);
				
				EnterpriseBasicInfo enterpriseBasicInfo = enterpriseInfoService.selectEnterpriseInfoById(enterpriseRegForm.getEnterPriseId());
				BeanUtils.copyProperties(enterpriseRegForm, enterpriseBasicInfo, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseRegForm, null));
				enterpriseInfoService.updateEnterpriseInfoById(enterpriseBasicInfo);
			}
			
			
			
		} catch (Exception e) {
			log.error("【企业注册】操作出错,e={}",e.getMessage());
			throw new IOCException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success();
		
	}
	
	@ApiOperation(value = "查询注册企业管理员帐号是否存在")
    @GetMapping("/checkUserAccount/{userAccount}")
	public ResultVO<Object> checkUserAccount(@PathVariable String userAccount){
		List<SysUser> sysUserList = sysUserService.selectSysUser(userAccount);
		if(sysUserList.size() > 0){
			log.error("【查询注册企业管理员帐号是否存在】管理员帐号已存在");
			throw new IOCException(ResultEnum.ACCOUNT_EXIST);
		}
		return ResultVOUtil.success();
	}
	
	@ApiOperation(value = "查询注册企业是否存在")
    @GetMapping("/checkOrgCode/{orgCode}")
	public ResultVO<Object> checkOrgCode(@PathVariable String orgCode){
		
		EnterpriseBasicInfoExample example = new EnterpriseBasicInfoExample();
		example.createCriteria().andOrgCodeEqualTo(orgCode);
		
		List<EnterpriseBasicInfo> enterpriseBasicInfoList = enterpriseInfoService.selectEnterpriseInfoByExample(example);
		if(enterpriseBasicInfoList.size() > 0){
			log.error("【查询注册企业是否存在】企业已存在");
			throw new IOCException(ResultEnum.ENTERPRISE_EXIST);
		}
		return ResultVOUtil.success();
	}

	@ApiOperation(value = "查询企业注册审核状态")
    @GetMapping("/queryRegCheckStatus/{orgCode}")
	public ResultVO<Object> queryRegCheckStatus(@PathVariable String orgCode){
		EnterpriseBasicInfoExample example = new EnterpriseBasicInfoExample();
		example.createCriteria().andOrgCodeEqualTo(orgCode);
		
		List<EnterpriseBasicInfo> enterpriseBasicInfoList = enterpriseInfoService.selectEnterpriseInfoByExample(example);
		
		EnterpriseRegDTO dto = new EnterpriseRegDTO();
		if(enterpriseBasicInfoList.size() > 0){
			BeanUtils.copyProperties(enterpriseBasicInfoList.get(0), dto, BeanCopyUtil.getNullOrIgnorePropertyNames(enterpriseBasicInfoList.get(0), null));
			
			if(!StringUtils.isEmpty(enterpriseBasicInfoList.get(0).getOrgFilePath())){
				dto.setViewOrgFilePath(projectPath.getFileUrlPath() + enterpriseBasicInfoList.get(0).getOrgFilePath());
			}
			if(!StringUtils.isEmpty(enterpriseBasicInfoList.get(0).getAuthorizeFile())){
				dto.setViewAuthorizeFile(projectPath.getFileUrlPath() + enterpriseBasicInfoList.get(0).getAuthorizeFile());
			}
			dto.setEnterpriseId(enterpriseBasicInfoList.get(0).getId());
			
			SysUser sysUser = sysUserService.selectByPrimaryKey(enterpriseBasicInfoList.get(0).getCreateUserId());
			if(null != sysUser){
				dto.setUserId(sysUser.getUid());
				dto.setAccount(sysUser.getAccount());
				dto.setAccountPwd(sysUser.getAccountPwd());
				dto.setUserName(sysUser.getUserName());
				dto.setIdCard(sysUser.getIdCard());
				dto.setEmail(sysUser.getEmail());
				dto.setMobliePhone(sysUser.getMobliePhone());
				dto.setAccountType(sysUser.getAccountType());
				dto.setAccountStatus(sysUser.getAccountStatus());
				dto.setRemarks(sysUser.getRemarks());
			}
			
		}else{
			log.error("【查询企业审核状态】企业不存在");
			throw new IOCException(ResultEnum.ENTERPRISE_NOEXIST);
		}
		
		return ResultVOUtil.success(dto);
	}
}
