package com.jsowell.api.uniapp;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.exception.ServiceException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.SMSUtil;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.MemberPlateNumberRelation;
import com.jsowell.pile.dto.BindingCarNoDTO;
import com.jsowell.pile.dto.BindingCardDTO;
import com.jsowell.pile.dto.InvoiceTitleDTO;
import com.jsowell.pile.dto.MemberRegisterAndLoginDTO;
import com.jsowell.pile.dto.MemberRegisterDTO;
import com.jsowell.pile.dto.UniAppQueryMemberBalanceDTO;
import com.jsowell.pile.dto.WechatLoginDTO;
import com.jsowell.pile.dto.WeixinPayDTO;
import com.jsowell.pile.service.IMemberBasicInfoService;
import com.jsowell.pile.service.IMemberPlateNumberRelationService;
import com.jsowell.pile.vo.MemberPlateNumberVO;
import com.jsowell.pile.vo.uniapp.InvoiceTitleVO;
import com.jsowell.pile.vo.uniapp.MemberVO;
import com.jsowell.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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 javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 小程序接口
 */
// 不登录直接访问
@Anonymous
@RestController
@RequestMapping("/uniapp/member")
public class MemberController extends BaseController {

	@Autowired
	private MemberService memberService;

	@Autowired
	private IMemberBasicInfoService memberBasicInfoService;

	@Autowired
	private IMemberPlateNumberRelationService memberPlateNumberRelationService;

	/**
	 * 下发短信接口 business
	 * http://localhost:8080/uniapp/member/sendSMS
	 */
	@PostMapping("/sendSMS")
	public RestApiResponse<?> sendSMS(HttpServletRequest request, @RequestBody MemberRegisterAndLoginDTO dto) {
		logger.info("下发短信接口 param:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			if (StringUtils.isBlank(dto.getMobileNumber())) {
				throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
			}
			String sendSMSResult = SMSUtil.sendSMS(request, dto.getMobileNumber());
			response = new RestApiResponse<>(sendSMSResult);
		} catch (Exception e) {
			logger.error("下发短信接口 发生异常 error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_SEND_SMS_ERROR);
		}
		logger.info("下发短信接口 result:{}", JSONObject.toJSONString(response));
		return response;
	}


	/**
	 * 会员登录注册
	 * 登录成功，返回memberToken
	 * http://localhost:8080/uniapp/member/memberRegisterAndLogin
	 */
	@PostMapping("/memberRegisterAndLogin")
	public RestApiResponse<?> memberRegisterAndLogin(HttpServletRequest request, @RequestBody MemberRegisterAndLoginDTO dto) {
		logger.info("会员登录注册接口 param:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			// 执行登录（查这个手机号在后台有没有数据，如果没有就静默注册）
			String memberToken = memberService.memberRegisterAndLogin(dto);

			// 返回前端成功
			Map<String, String> map = Maps.newHashMap();
			map.put("memberToken", memberToken);
			response = new RestApiResponse<>(map);
		} catch (ServiceException e) {
			logger.warn("会员登录注册接口 warn", e);
			response = new RestApiResponse<>(e.getMessage());
		} catch (Exception e) {
			logger.error("会员登录注册接口 发生异常 error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_MEMBER_REGISTER_AND_LOGIN_ERROR);
		}
		return response;
	}

	/**
	 * 微信一键登录
	 * http://localhost:8080/uniapp/member/wechatLogin
	 */
	@PostMapping("/wechatLogin")
	public RestApiResponse<?> wechatLogin(@RequestBody WechatLoginDTO dto) {
		RestApiResponse<?> response = null;
		try {
			String memberToken = memberService.wechatLogin(dto);
			response = new RestApiResponse<>(ImmutableMap.of("memberToken", memberToken));
		} catch (Exception e) {
			logger.error("微信登录异常", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_WECHAT_LOGIN_ERROR);
		}
		return response;
	}

	/**
	 * 接收并处理前端用户信息
	 *
	 * http://localhost:8080/uniapp/member/saveUserInfo
	 */
	@PostMapping("/saveUserInfo")
	public RestApiResponse<?> saveUserInfo(HttpServletRequest request, @RequestBody MemberRegisterDTO dto) {
		logger.info("接受前端用户信息并处理 param:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			memberService.handleUserInfo(memberId, dto);
			response = new RestApiResponse<>();
		} catch (Exception e) {
			logger.error("处理用户信息异常", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_HANDLE_USER_INFO_ERROR);
		}
		logger.info("接受前端用户信息并处理 result:{}", response);
		return response;
	}

	/**
	 * 查询用户账户信息
	 *
	 * http://localhost:8080/uniapp/member/getMemberInfo
	 * @return 用户账户信息
	 */
	@GetMapping("/getMemberInfo")
	public RestApiResponse<?> getMemberInfo(HttpServletRequest request) {
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			logger.info("查询账户总余额 param memberId:{}", memberId);
			MemberVO memberVO = memberService.getMemberInfoByMemberId(memberId);
			response = new RestApiResponse<>(memberVO);
		}catch (BusinessException e) {
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		}catch (Exception e) {
			logger.error("查询用户账户总余额异常", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_MEMBER_ACCOUNT_AMOUNT_ERROR);
		}
		logger.info("查询用户账户信息 result:{}", response);
		return response;
	}

	/**
	 * 获取openId
	 * http://localhost:8080/uniapp/member/getOpenId
	 */
	@PostMapping("/getOpenId")
	public RestApiResponse<?> getOpenId(HttpServletRequest request, @RequestBody WeixinPayDTO dto) {
		logger.info("获取openId param:{}", dto.toString());
		RestApiResponse<?> response;
		try {
			getMemberIdByAuthorization(request);
			String openId = memberService.getOpenIdByCode(dto.getCode());
			response = new RestApiResponse<>(ImmutableMap.of("openId", openId));
		} catch (Exception e) {
			logger.error("获取openId error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_OPEN_ID_BY_CODE_ERROR);
		}
		logger.info("获取openId result:{}", response);
		return response;
	}


	/**
	 * 获取用户账户余额变动信息
	 * http://localhost:8080/uniapp/member/getMemberBalanceChanges
	 * @param request
	 * @param dto
	 * @return
	 */
	@PostMapping("/getMemberBalanceChanges")
	public RestApiResponse<?> getMemberBalanceChanges(HttpServletRequest request, @RequestBody UniAppQueryMemberBalanceDTO dto) {
		logger.info("查询用户账户余额变动信息 params:{}", dto.toString() );
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			dto.setMemberId(memberId);
			PageResponse pageResponse = memberService.getMemberBalanceChanges(dto);
			response = new RestApiResponse<>(pageResponse);
		} catch (Exception e) {
			logger.error("查询用户账户余额变动信息 error:", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_BALANCE_CHANGES_ERROR);
		}
		logger.info("查询用户账户余额变动信息 result:{}", response);
		return response;
	}


	/**
	 * 通过 memberId 查询用户绑定车牌信息
	 * http://localhost:8080/uniapp/member/getMemberCarNoInfo
	 *
	 * @return
	 */
	@GetMapping("/getMemberCarNoInfo")
	public RestApiResponse<?> getMemberCarNoInfo(HttpServletRequest request){
		String memberId = getMemberIdByAuthorization(request);
		logger.info("通过 memberId 查询用户个人基本信息 param:{}", memberId);
		RestApiResponse<?> response = null;
		try {
			MemberPlateNumberRelation info = new MemberPlateNumberRelation();
			info.setMemberId(memberId);
			List<MemberPlateNumberRelation> resultList = memberPlateNumberRelationService.selectMemberPlateNumberRelationList(info);
			response = new RestApiResponse<>(resultList);
		} catch (Exception e) {
			logger.error("通过 memberId 查询用户个人基本信息 error", e);
			response = new RestApiResponse<>(e);
		}
		logger.info("通过 memberId 查询用户个人基本信息 result:{}", response);
		return response;
	}


	/**
	 * 用户绑定车牌号、vin
	 * http://localhost:8080/uniapp/member/memberBindingCarNo
	 *
	 * @return
	 */
	@PostMapping("/memberBindingCarNo")
	public RestApiResponse<?> memberBindingCarNo(HttpServletRequest request, @RequestBody BindingCarNoDTO dto){
		logger.info("用户绑定车牌号 param:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			dto.setMemberId(memberId);
			memberService.memberBindingCarNo(dto);
			response = new RestApiResponse<>();
		} catch (BusinessException e){
			logger.error("用户绑定车牌号 error", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e){
			logger.error("用户绑定车牌号 error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_USER_BINDING_CARNO_ERROR);
		}
		logger.info("用户绑定车牌号 result:{}", response);
		return response;
	}

	/**
	 * 用户修改车牌号
	 * http://localhost:8080/uniapp/member/memberUpdatePlateNumber
	 *
	 * @return
	 */
	@PostMapping("/memberUpdatePlateNumber")
	public RestApiResponse<?> memberUpdatePlateNumber(HttpServletRequest request, @RequestBody BindingCarNoDTO dto){
		logger.info("用户修改车牌号 params:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			MemberPlateNumberRelation relation = MemberPlateNumberRelation.builder()
					.id(Integer.valueOf(dto.getId()))
					.memberId(memberId)
					.licensePlateNumber(dto.getCarNo())
					.build();
			if (StringUtils.isNotBlank(dto.getVinCode())) {
				relation.setVinCode(dto.getVinCode());
			}
			int i = memberPlateNumberRelationService.updatePlateNumber(relation);
			response = new RestApiResponse<>(i);
		} catch (Exception e) {
			logger.error("用户修改车牌号 error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_USER_UNBIND_CARNO_ERROR);
		}
		logger.info("用户修改车牌号 result:{}", response);
		return response;
	}

	/**
	 * 用户解除绑定
	 * http://localhost:8080/uniapp/member/memberUnbindCarNo
	 *
	 * @return
	 */
	@PostMapping("/memberUnbindCarNo")
	public RestApiResponse<?> memberUnbindCarNo(@RequestBody BindingCarNoDTO dto){
		 logger.info("用户解绑车牌号 params:{}", JSONObject.toJSONString(dto));
		 RestApiResponse<?> response = null;
		 try {
			 // String memberId = getMemberIdByAuthorization(request);
			 // dto.setMemberId(memberId);
			 int i = memberPlateNumberRelationService.deleteCarNoByParams(dto.getIds());
			 response = new RestApiResponse<>(i);
		 } catch (Exception e) {
			logger.error("用户解绑车牌号 error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_USER_UNBIND_CARNO_ERROR);
		 }
		 logger.info("用户解绑车牌号 result:{}", response);
		 return response;
	}


	/**
	 * 用户绑定鉴权卡接口
	 * http://localhost:8080/uniapp/member/memberBindingCard
	 * @param dto
	 * @return
	 */
	@PostMapping("/memberBindingCard")
	public RestApiResponse<?> memberBindingCard(HttpServletRequest request, @RequestBody BindingCardDTO dto){
		logger.info("用户绑定鉴权卡 param:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			dto.setMemberId(memberId);
			int i = memberService.memberBindCard(dto);
			response = new RestApiResponse<>(i);
		} catch (BusinessException e){
			logger.error("用户绑定鉴权卡 error", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("用户绑定鉴权卡 error", e);
			response = new RestApiResponse<>(e);
		}
		logger.info("用户绑定鉴权卡 result:{}", response);
		return response;
	}

	/**
	 * 用户解绑鉴权卡
	 * @param request
	 * @param dto
	 * @return
	 */
	@PostMapping("/memberUnbindingCard")
	public RestApiResponse<?> memberUnbindingCard(HttpServletRequest request, @RequestBody BindingCardDTO dto) {
		logger.info("用户解绑鉴权卡 param:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			dto.setMemberId(memberId);
			int i = memberService.memberUnbindCard(dto);
			response = new RestApiResponse<>(i);
		} catch (BusinessException e) {
			logger.error("用户解绑鉴权卡 error", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("用户解绑鉴权卡 error", e);
			response = new RestApiResponse<>(e);
		}
		logger.info("用户解绑鉴权卡 result:{}", response);
		return response;
	}

	/**
	 * 新增会员发票抬头
	 * http://localhost:8080/uniapp/member/createMemberInvoiceTitle
	 */
	@PostMapping("/createMemberInvoiceTitle")
	public RestApiResponse<?> createMemberInvoiceTitle(HttpServletRequest request, @RequestBody InvoiceTitleDTO dto) {
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			dto.setMemberId(memberId);
			memberService.createMemberInvoiceTitle(dto);
			response = new RestApiResponse<>();
		} catch (BusinessException e) {
			logger.error("新增会员发票抬头 error", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("新增会员发票抬头 error", e);
			response = new RestApiResponse<>(e);
		}
		return response;
	}

	/**
	 * 修改会员发票抬头
	 * http://localhost:8080/uniapp/member/updateMemberInvoiceTitle
	 */
	@PostMapping("/updateMemberInvoiceTitle")
	public RestApiResponse<?> updateMemberInvoiceTitle(HttpServletRequest request, @RequestBody InvoiceTitleDTO dto) {
		logger.info("修改会员发票抬头 param:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			dto.setMemberId(memberId);
			memberService.updateMemberInvoiceTitle(dto);
			response = new RestApiResponse<>();
		} catch (BusinessException e) {
			logger.error("修改会员发票抬头 error", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("修改会员发票抬头 error", e);
			response = new RestApiResponse<>(e);
		}
		return response;
	}

	/**
	 * 删除会员发票抬头
	 * @param request
	 * @param dto
	 * @return
	 */
	@PostMapping("/deleteMemberInvoiceTitle")
	public RestApiResponse<?> deleteMemberInvoiceTitle(HttpServletRequest request, @RequestBody InvoiceTitleDTO dto) {
		logger.info("修改会员发票抬头 param:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			dto.setMemberId(memberId);
			memberService.deleteMemberInvoiceTitle(dto);
			response = new RestApiResponse<>();
		} catch (BusinessException e) {
			logger.error("修改会员发票抬头 error", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("修改会员发票抬头 error", e);
			response = new RestApiResponse<>(e);
		}
		return response;
	}

	/**
	 * 查询会员发票抬头列表
	 * http://localhost:8080/uniapp/member/queryMemberInvoiceTitles
	 */
	@GetMapping("/queryMemberInvoiceTitles")
	public RestApiResponse<?> queryMemberInvoiceTitles(HttpServletRequest request) {
		RestApiResponse<?> response = null;
		try {
			String memberId = getMemberIdByAuthorization(request);
			List<InvoiceTitleVO> list = memberService.queryMemberInvoiceTitles(memberId);
			response = new RestApiResponse<>(ImmutableMap.of("list", list));
		} catch (BusinessException e) {
			logger.error("查询会员发票抬头列表 error", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("查询会员发票抬头列表 error", e);
			response = new RestApiResponse<>(e);
		}
		logger.info("查询会员发票抬头列表 result:{}", response);
		return response;
	}
}
