/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;


import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.app.dto.UserCenterInfoDto;
import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.app.param.UserInfoParam;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.UserParam;
import com.yami.shop.config.WxConfig;
import com.yami.shop.dao.ChannelMapper;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 用户信息
 *
 * @author LGH
 */
@RestController
@RequestMapping("/p/user")
@Api(tags = "用户接口")
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    private final MapperFacade mapperFacade;

    private final OrderService orderService;

    private final ShopDetailService shopDetailService;

    private final ShopAuditingService shopAuditingService;

    private final WxConfig wxConfig;

    private final ChannelMapper channelMapper;


    /**
     * 查看用户接口
     */
    @GetMapping("/userInfo")
    @ApiOperation(value = "查看用户信息", notes = "根据用户ID（userId）获取用户信息")
    public ResponseEntity<UserDto> userInfo() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getUserByUserId(userId);
        UserDto userDto = mapperFacade.map(user, UserDto.class);
        Channel channel = channelMapper.selectById(user.getChannelId());
        if (ObjectUtils.isNotEmpty(channel)) {
            userDto.setEnterprise(channel.getChannelName());
        }
        if (userDto.getUserMobile() != null) {
            userDto.setMobile(userDto.getUserMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        }

        return ResponseEntity.ok(userDto);
    }

    @PutMapping("/setUserInfo")
    @ApiOperation(value = "设置用户信息", notes = "设置用户信息")
    public ResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = new User();
        user.setUserId(userId);
        user.setPic(StrUtil.isBlank(userInfoParam.getAvatarUrl()) ? null : userInfoParam.getAvatarUrl());
        user.setSex(userInfoParam.getSex() == null ? user.getSex() : userInfoParam.getSex());
        user.setNickName(userInfoParam.getNickName() == null ? user.getNickName() : userInfoParam.getNickName());
        user.setUserMobile(userInfoParam.getUserMobile() == null ? user.getUserMobile() : userInfoParam.getUserMobile());
        user.setBirthDate(userInfoParam.getBirthDate() == null ? user.getBirthDate() : userInfoParam.getBirthDate());
        user.setUserMail(StrUtil.isNotBlank(userInfoParam.getUserMail()) ? userInfoParam.getUserMail() : user.getUserMail());
        if (StrUtil.isNotBlank(userInfoParam.getNickName())) {
            user.setNickName(userInfoParam.getNickName());
        }
        userService.updateById(user);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/centerInfo")
    @ApiOperation(value = "个人中心信息", notes = "获取用户个人中心信息")
    public ResponseEntity<UserCenterInfoDto> centerInfo() {
        String userId = SecurityUtils.getUser().getUserId();
        UserCenterInfoDto userCenterInfoDto = new UserCenterInfoDto();
        userCenterInfoDto.setOrderCountData(orderService.getOrderCount(userId));

        ShopAuditing shopAuditing = shopAuditingService.getShopAuditingByUserId(userId);

        userCenterInfoDto.setShopAuditStatus(shopAuditing == null ? null : shopAuditing.getStatus());

        ShopDetail shopDetail = shopDetailService.getShopDetailByUserId(userId);

        userCenterInfoDto.setIsSetPassword(shopDetail != null && StrUtil.isNotBlank(shopDetail.getPassword()));

        userCenterInfoDto.setShopId(shopDetail == null ? null : shopDetail.getShopId());
        userCenterInfoDto.setShopStatus(shopDetail == null ? null : shopDetail.getShopStatus());
        return ResponseEntity.ok(userCenterInfoDto);
    }


    @GetMapping("/getPhoneNumber")
    @ApiOperation(value = "获取用户绑定手机号", notes = "根据小程序的加密数据，iv获取当前用户的手机号")
    public ResponseEntity<WxMaPhoneNumberInfo> getPhoneNumber(@RequestParam String encryptedData, @RequestParam String ivStr) {

        return ResponseEntity.ok(wxConfig.getWxMaService().getUserService().getPhoneNoInfo(SecurityUtils.getUser().getSessionKey(), encryptedData, ivStr));
    }

    @GetMapping("/getUserScore")
    @ApiOperation(value = "获取用户积分", notes = "返回用户的积分信息")
    public ResponseEntity<UserParam> getUserScore() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        UserParam userParam = mapperFacade.map(user, UserParam.class);
        System.out.println();
        return ResponseEntity.ok(userParam);
    }

}
