package com.softwarebr.nunu.web.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.brframework.commondb.core.ControllerPageHandle;
import com.brframework.commonsecurity.core.SecurityContextHolder;
import com.brframework.commonsecurity.core.SecuritySubject;
import com.brframework.commonweb.json.JSONResult;
import com.brframework.commonweb.json.Page;
import com.brframework.commonweb.json.PageParam;
import com.brframework.commonwebadmin.json.admin.adminuser.LoginResult;
import com.brframework.webapppatch.domain.RequestFlag;
import com.brframework.webapppatch.utils.RequestFlagUtils;
import com.google.common.collect.Lists;
import com.softwarebr.nunu.dto.user.MemberParamDTO;
import com.softwarebr.nunu.entity.user.Member;
import com.softwarebr.nunu.entity.user.Message;
import com.softwarebr.nunu.json.api.user.*;
import com.softwarebr.nunu.service.sms.CaptchaConstant;
import com.softwarebr.nunu.service.sms.CaptchaService;
import com.softwarebr.nunu.service.user.MemberService;
import com.softwarebr.nunu.service.user.MessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 用户
 * @Author lilin
 * @Date 2020-02-17 14:07:07
 */

@RestController
@Api(tags = "用户基本信息")
@RequestMapping("/api")
public class ApiUserController {

	@Autowired
	private MemberService memberService;

	@Autowired
	private CaptchaService captchaService;

	@Autowired
	private MessageService messageService;


	@ApiOperation(value = "用户注册", notes = "用户注册", produces = "text/plain")
	@PostMapping("/v1/user/member/register")
	public JSONResult<LoginResult> memberRegisterV1(@Valid @RequestBody MemberRegisterParam param) {
		captchaService.verify(param.getPhone(), CaptchaConstant.BUSINESS_IDENTITY, param.getCaptcha());
		MemberParamDTO memberParamDTO = new MemberParamDTO();
		memberParamDTO.setPhone(param.getPhone());
		memberParamDTO.setPassword(param.getPassword());
		memberParamDTO.setType(param.getType());
		memberParamDTO.setThirdPartyId(param.getThirdPartyId());
		memberParamDTO.setIdentityType(Member.IDENTITY_TYPE_MEMBER);
		String token = memberService.register(memberParamDTO);
		return JSONResult.ok(LoginResult.builder().token(token).build());
	}

	@ApiOperation(value = "机构注册", notes = "机构注册", produces = "text/plain")
	@PostMapping("/v1/user/enterprise/register")
	public JSONResult enterpriseRegisterV1(@Valid @RequestBody EnterpriseRegisterParam param) {
		captchaService.verify(param.getPhone(), CaptchaConstant.BUSINESS_IDENTITY, param.getCaptcha());
		MemberParamDTO memberParamDTO = new MemberParamDTO();
		memberParamDTO.setPhone(param.getPhone());
		memberParamDTO.setPassword(param.getPassword());
		memberParamDTO.setType(param.getType());
		memberParamDTO.setThirdPartyId(param.getThirdPartyId());
		memberParamDTO.setIdentityType(Member.IDENTITY_TYPE_ENTERPRISE);
		memberParamDTO.setCompanyName(param.getCompanyName());
		memberParamDTO.setUsername(param.getUsername());
		String token = memberService.register(memberParamDTO);
		return JSONResult.ok(LoginResult.builder().token(token).build());
	}

	@ApiOperation(value = "验证手机号码是否已注册", notes = "验证手机号码是否已注册", produces = "text/plain")
	@GetMapping("v1/member/check/register")
	public JSONResult<CheckRegisterResult> checkRegisterV1(@Valid CheckRegisterParam param) {
		CheckRegisterResult registerResult = new CheckRegisterResult();
		registerResult.setCode(memberService.checkRegister(param.getPhone(), param.getType()));
		return JSONResult.ok(registerResult);
	}

	@ApiOperation(value = "发送验证码", notes = "发送验证码", produces = "text/plain")
	@PostMapping("v1/member/captcha/{phone}")
	public JSONResult sendSmsV1(@PathVariable("phone") String phone) {
		captchaService.send(phone, CaptchaConstant.BUSINESS_IDENTITY);
		return JSONResult.ok();
	}

	@ApiOperation(value = "用户登录", notes = "用户登录")
	@PostMapping("v1/member/login")
	public JSONResult<LoginResult> loginV1(@Valid @RequestBody LoginParam param) {
		String token = memberService.login(param.getPhone(), param.getPassword());
		return JSONResult.ok(LoginResult.builder()
				.token(token)
				.build());
	}

	@ApiOperation(value = "第三方登录", notes = "第三方登录")
	@PostMapping("v1/member/third-party/login")
	public JSONResult<ThirdPartyLoginResult> thirdPartyLoginV1(@Valid @RequestBody ThirdPartyLoginParam param) throws WxErrorException, IOException {
		ThirdPartyLoginResult thirdPartyLoginResult = memberService.thirdPartyLogin(param.getType(), param.getThirdPartyId());
		return JSONResult.ok(thirdPartyLoginResult);
	}

	@ApiOperation(value = "第三方账号绑定", notes = "第三方账号绑定")
	@PutMapping("access/v1/third-party/save")
	public JSONResult saveThirdPartyV1(@Valid @RequestBody ThirdPartyLoginParam param) throws WxErrorException, IOException {
		SecuritySubject securitySubject = SecurityContextHolder.getSubject();
		memberService.saveThirdParty(param.getType(), param.getThirdPartyId(), securitySubject.getUsername());
		return JSONResult.ok();
	}

	@ApiOperation(value = "找回密码", notes = "找回密码")
	@PutMapping("v1/member/password/reset")
	public JSONResult passwordResetV1(@Valid @RequestBody PasswordResetParam param) {
		captchaService.verify(param.getPhone(), CaptchaConstant.BUSINESS_IDENTITY, param.getCaptcha());
		memberService.passwordReset(param.getPhone(), param.getPassword());
		return JSONResult.ok();
	}

	@ApiOperation(value = "个人信息", notes = "个人信息")
	@GetMapping("access/v1/member/info")
	public JSONResult<MemberResult> memberInfoV1() {
		RequestFlag flag = RequestFlagUtils.getReqeustFlag();
		SecuritySubject securitySubject = SecurityContextHolder.getSubject();
		Member member =memberService.bindingPushAndfindUser(securitySubject.getId(), flag);
		MemberResult result = ControllerPageHandle.convertTo(member, MemberResult.class);
		memberService.save(member);
		return JSONResult.ok(result);
	}

	@ApiOperation(value = "修改个人信息", notes = "修改个人信息")
	@PostMapping("access/v1/member/info/upd")
	public JSONResult memberInfoUpdV1(@Valid @RequestBody EditMemberInfoParam param) {
		Long memberId = Long.parseLong(SecurityContextHolder.getSubject().getId());
		memberService.updateMember(memberId, param.getHeadImgUri(),
				param.getNickname(),param.getUsername(),param.getCompanyName(),param.getPassword());
		return JSONResult.ok();
	}

	@ApiOperation(value = "消息记录", notes = "消息记录")
	@GetMapping("access/v1/message/list")
	public JSONResult<Page<MessageResult>> messageListV1(@Valid PageParam param) {
		SecuritySubject securitySubject = SecurityContextHolder.getSubject();
		org.springframework.data.domain.Page<Message> page = messageService.findPage(param, Long.parseLong(securitySubject.getId()));
		Page<MessageResult> pageResult = new Page<>(param.getPageIndex(), param.getPageSize(), page.getTotalElements());
		List<MessageResult> list = handleMessageResult(page.getContent());
		//处理未读消息
		messageService.handleUnreadMessage(list, Long.parseLong(securitySubject.getId()));
		pageResult.setList(list);
		return JSONResult.ok(pageResult);
	}

	@ApiOperation(value = "消息中心->未读数量")
	@GetMapping("access/v1/message/unread/total")
	public JSONResult<MessageUnreadResult> messageUnreadTotalV1() {
		SecuritySubject securitySubject = SecurityContextHolder.getSubject();
		int unreadCount = messageService.unreadCount(Long.parseLong(securitySubject.getId()));
		MessageUnreadResult unreadResult = MessageUnreadResult.builder().unreadCount(unreadCount).build();
		return JSONResult.ok(unreadResult);
	}

	@ApiOperation(value = "访问人数收集")
	@GetMapping("v1/index/access/statistics")
	public JSONResult accessStatisticsV1() {
		memberService.saveAccessStatistics();
		return JSONResult.ok();
	}


	/**
	 * 处理消息返回结果
	 * @param messages
	 * @return
	 */
	private List<MessageResult> handleMessageResult(List<Message> messages){
		List<MessageResult> messageResults = Lists.newArrayList();
		for (Message message : messages) {
			if(null == message){
				continue;
			}
			MessageResult result = MessageResult.builder()
					.id(message.getId())
					.createDate(message.getCreateDate())
					.type(message.getType())
					.build();
			JSONObject json = JSON.parseObject(message.getContent());
			if (!json.getString("title").isEmpty()) {
				result.setTitle(json.getString("title"));
			}
			if (!json.getString("message").isEmpty()) {
				result.setMessage(json.getString("message"));
			}
			if (!json.getString("targetType").isEmpty()) {
				result.setTargetType(json.getString("targetType"));
			}
			if (!json.getString("targetId").isEmpty()) {
				result.setTargetId(json.getString("targetId"));
			}
			messageResults.add(result);
		}
		return messageResults;
	}

}