/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2023/2/2
 */
package org.springblade.modules.baseinfo.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.baseinfo.user.entity.OpenUserEntity;
import org.springblade.modules.baseinfo.user.service.IOpenUserService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserDept;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IRegionService;
import org.springblade.modules.system.service.IUserDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.transaction.annotation.Transactional;
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 java.util.List;

/***
 * Date:2023/2/2
 * Title:开放用户人员接口
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author swp
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/open/user")
@AllArgsConstructor
@Api(value = "开放用户人员接口", tags = "开放用户人员模块管理")
public class OpenUserController extends BladeController {
	private final IUserService userService;
	private final IDeptService deptService;
	private final IUserDeptService userDeptService;
	private final IRegionService regionService;
	private final IOpenUserService openUserService;

	/**
	 * 注册
	 */
	@PostMapping("/reg")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "注册", notes = "传入 OpenUserEntity")
	@Transactional
	public R openUserReg(@RequestBody OpenUserEntity openUserEntity) {
		try {
			if (openUserEntity.getCompanyName()==null){
				return R.fail("公司名称不能为空");
			}
			if (openUserEntity.getPersonName()==null){
				return R.fail("性名不能为空");
			}
			if (openUserEntity.getMail()==null){
				return R.fail("邮箱不能为空");
			}
			if (openUserEntity.getContactPhone()==null){
				return R.fail("联系手机不能为空");
			}
			LambdaQueryWrapper<OpenUserEntity> openUserWrapper = Wrappers.<OpenUserEntity>query().lambda();
			openUserWrapper.eq(OpenUserEntity::getContactPhone, openUserEntity.getContactPhone());
			openUserWrapper.eq(OpenUserEntity::getIsDeleted, 0);
			openUserWrapper.eq(OpenUserEntity::getApproveStatus,0).or().eq(OpenUserEntity::getApproveStatus,1);

			List<OpenUserEntity> openUserEntityList = openUserService.list(openUserWrapper);
			if (openUserEntityList != null && openUserEntityList.size()>0){
				return R.fail("请勿重复进行申请");
			}

//			String account;
//			if (openUserEntity.getUserAccount()!=null){
//				account=openUserEntity.getUserAccount();
//			}else{
//				account=openUserEntity.getContactPhone();
//			}
			LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
			wrapper.eq(User::getAccount, openUserEntity.getContactPhone());
			wrapper.eq(User::getIsDeleted, 0);
			List<User> userList = userService.list(wrapper);
			if (null != userList && userList.size() > 0) {
				return R.fail("帐号已经存在,请更换一个手机号进行申请");
			}

		   openUserEntity.setApproveStatus(0);

			openUserService.save(openUserEntity);




//			if (null == openUserEntity.getRegionCode()){
//				return R.fail("所在区划参数不能为空");
//			}
			//创建组织机构
			Dept parentDept = deptService.getById(BusinessConstant.DEPT_DH_ID);
			Dept dept = new Dept();
			dept.setParentId(BusinessConstant.DEPT_DH_ID);
			dept.setDeptCategory(1);
			dept.setDeptName(openUserEntity.getCompanyName());
			dept.setFullName(openUserEntity.getCompanyName());
			dept.setAncestors(parentDept.getAncestors()+","+parentDept.getId());
			dept.setSort(1);
			deptService.save(dept);
            //创建用户
			User u = new User();
			u.setAccount(openUserEntity.getContactPhone());
			u.setPhone(openUserEntity.getContactPhone());
			u.setEmail(openUserEntity.getMail());
			u.setName(openUserEntity.getPersonName());
			u.setRealName(openUserEntity.getPersonName());
			u.setPassword(DigestUtil.encrypt(openUserEntity.getContactPhone() + BusinessConstant.ACCOUNT_PW_SUFFIX));
			u.setDeptId(Func.toStr(dept.getId()));
			u.setRoleId(BusinessConstant.ROLE_ORG_ADMIN_ID);
			u.setPostId(BusinessConstant.POST_ORG_ADMIN_ID);
			u.setUserType(1);
			userService.save(u);
            //创建关联关系
			UserDept userDept=new UserDept();
			userDept.setUserId(u.getId());
			userDept.setDeptId(dept.getId());
			userDeptService.save(userDept);
//			//创建组织机构
//			LambdaQueryWrapper<Region> regionQueryWrapper = Wrappers.<Region>query().lambda();
//			regionQueryWrapper.eq(Region::getCode,openUserEntity.getRegionCode());
//			Region rootRegion =regionService.getOne(regionQueryWrapper);
//			regionQueryWrapper = Wrappers.<Region>query().lambda();
//			regionQueryWrapper.or().eq(Region::getCode,openUserEntity.getRegionCode());
//			regionQueryWrapper.or().likeRight(Region::getAncestors,rootRegion.getAncestors()+","+rootRegion.getCode());
//			regionQueryWrapper.orderByAsc(Region::getCode);
//			List<Region> regionList = regionService.list(regionQueryWrapper);
//            if (null != regionList&&regionList.size()>0){
//				List<CustomizeRegionInfoEntity> regionInfoEntityList=new LinkedList<>();
//				for (Region region:regionList){
//					CustomizeRegionInfoEntity entity=new CustomizeRegionInfoEntity();
//					entity.setDeptId(dept.getId());
//					entity.setAdcd(region.getCode());
//					entity.setAdnm(region.getName());
//                    entity.setParentCode(region.getParentCode());
//                    entity.setAncestors(region.getAncestors());
//					regionInfoEntityList.add(entity);
//				}
//				customizeRegionInfoService.saveBatch(regionInfoEntityList);
//			}
//			CustomizeRegionOrgBindInfoEntity regionOrgBindInfoEntity=new CustomizeRegionOrgBindInfoEntity();
//			regionOrgBindInfoEntity.setAdcd(openUserEntity.getRegionCode());
//			regionOrgBindInfoEntity.setDeptId(dept.getId());
//			customizeRegionOrgBindInfoService.save(regionOrgBindInfoEntity);
//
//			//消息通知
//			NoticeEntity noticeEntity=new NoticeEntity();
//			noticeEntity.setDeptId(dept.getId());
//			noticeEntity.setTitle("帐号注册成功");
//			noticeEntity.setContent("欢迎使用智能运维系统，系统操作介绍说明请详见【辅助业务】菜单中的【用户使用手册】！");
//			noticeEntity.setReleaseTime(new Date());
//			noticeEntity.setCategory(1);
//			noticeService.save(noticeEntity);


//			String title = "";
//			if (null != rtuName) {
//				title += rtuName;
//			}
//			if (warningInfo.getWarningStatus().equals(GBConstants.WARNING_STATUS_HAPPEN)) {
//				title += "<故障预警>";
//			} else {
//				title += "<故障恢复>";
//			}
//			String mailText = "<div>设备名称：";
//			if (null != rtuName) {
//				mailText += "<span>" + rtuName + "</span>";
//			}
//			mailText += "</div>";
//			mailText += "<div>项目名称：";
//			if (null != projectName) {
//				mailText += projectName;
//			}
//			mailText += "</div>";
//			mailText += "<div>机构名称：";
//			if (null != orgName) {
//				mailText += orgName;
//			}
//			mailText += "</div>";
//			mailText += "<div>预警信息：" + warningInfo.getWarningInfo();
//			mailText += "</div>";
//			MailHelp.sendMail(toMail, title, mailText);

			return R.success("帐号申请已注册成功");

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("注册失败");
		}

	}
}
