package com.ruoyi.web.controller.api;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.mall.domain.*;

import com.ruoyi.mall.mapper.MallMemberUserMapper;
import com.ruoyi.mall.mapper.MallSchoolMapper;
import com.ruoyi.mall.service.*;
import com.ruoyi.set.domain.SetRegion;
import com.ruoyi.set.service.ISetRegionService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * 用户接口
 *
 * @author LCL
 * @date 2023-10-12
 */
@RestController
@RequestMapping("/api/member")
@ResponseBody
public class ApiMemberController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private IMallMemberUserService memberUserService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private ISetRegionService setRegionService;

    @Resource
    private IMallConfigFunctionService mallConfigFunctionService;

    @Resource
    private IBusinessCouponService businessCouponService;

    @Resource
    private IUserCouponService userCouponService;

    @Resource
    private MallSchoolMapper schoolMapper;

    @Resource
    private IMallMemberBannerService mallMemberBannerService;

    @Resource
    private MallMemberUserMapper mallMemberUserMapper;


    /**
     * 小程序授权登陆
     *
     * @param
     * @return
     */
    @PostMapping("/getUserInfoForXCX")
    @ResponseBody
    public ApiResult getUserInfoForXCX(@RequestBody Map<String, Object> map) {
        try {
            // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
            String params = "appid=wx898f44c913f1de6f&secret=995c5b868a455f2ce2cf025fd526957a&js_code=" + map.get("code").toString() + "&grant_type=" + "authorization_code";
            // 发送请求
            String response = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session?" + params, "");
            // 解析相应内容（转换成json对象）
            JSONObject json = JSONObject.parseObject(response);
            System.out.println("授权登录请求json：" + json);
            String openid = json.getString("openid");
            //查看表里有没有这个用户
            MallMemberUser memberUserDO = memberUserService.queryByOpenid(openid);

            // JSONObject userInfoJson = JSONObject.parseObject(map.get("userInfo").toString());
            // String nickName = userInfoJson.getString("nickName");
            // String avatarUrl = userInfoJson.getString("avatarUrl");

            String nickName = map.get("nickName").toString();
            String avatarUrl = map.get("avatarUrl").toString();


            if (memberUserDO == null) {
                //2、对encryptedData加密数据进行AES解密
                MallMemberUser memberUser = new MallMemberUser();
                memberUser.setName(nickName);
                memberUser.setOpenid(openid);
                memberUser.setAvatar(avatarUrl);
                memberUser.setCreateNum(5);
                memberUser.setToken(UUID.randomUUID().toString(true));
                memberUser.setCreateAt(DateUtils.getTime());
                memberUser.setUpdateAt(DateUtils.getTime());
                if (map.containsKey("parentId") && ObjectUtils.isNotEmpty(map.get("parentId"))) {
                    memberUser.setIntroUser(Long.parseLong(map.get("parentId").toString()));
                }
                // 生成自己的邀请码
                String code = memberUserService.getCode();
                memberUser.setInvitationCode(code);

                if (memberUserService.insertMallMemberUser(memberUser) > 0) {

                    // 新人优惠券
                    BusinessCoupon businessCoupon = new BusinessCoupon();
                    businessCoupon.setCouponType("1");
                    businessCoupon.setDelFlag("0");
                    List<BusinessCoupon> couponList = businessCouponService.selectBusinessCouponList(businessCoupon);
                    if (couponList.size() > 0) {
                        // 给用户返
                        for (BusinessCoupon coupon : couponList) {

                            Date endTime = coupon.getEndTime();
                            Date nowTime = new Date();

                            if (nowTime.compareTo(endTime) < 1) {
                                UserCoupon userCoupon = new UserCoupon();
                                userCoupon.setUserId(memberUser.getId());
                                userCoupon.setCouponId(coupon.getCouponId());
                                userCoupon.setTitle(coupon.getTitle());
                                userCoupon.setCouponMoney(coupon.getCouponMoney());
                                userCoupon.setCouponType(coupon.getCouponType());
                                userCoupon.setStartTime(coupon.getStartTime());
                                userCoupon.setEndTime(coupon.getEndTime());
                                userCoupon.setStatus("1");
                                userCouponService.insertUserCoupon(userCoupon);
                            }
                        }
                    }

                    return ApiResult.ok().put("data", memberUser);
                }
            }else{
                // 绑定上级
                if (ObjectUtils.isEmpty(memberUserDO.getIntroUser())){
                    if (map.containsKey("parentId") && ObjectUtils.isNotEmpty(map.get("parentId"))) {
                        memberUserDO.setIntroUser(Long.parseLong(map.get("parentId").toString()));
                        memberUserService.updateMallMemberUser(memberUserDO);
                    }
                }else{
                    if(map.containsKey("parentId") && ObjectUtils.isNotEmpty(map.get("parentId")) && !memberUserDO.getIntroUser().equals(MapUtils.getLong(map, "parentId"))) {
                        return ApiResult.error(409,"已绑定上级,请重新登录");
                    }
                }
            }
            return ApiResult.ok("登陆成功").put("data", memberUserDO);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("授权失败");
        }
    }

    /**
     * 获取用户手机号
     *
     * @return
     */
    @PostMapping("/phone/getXcxPhoneUserInfo")
    @ResponseBody
    public ApiResult getXcxPhoneUserInfo(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("openid") || StringUtils.isEmpty(params.get("openid").toString())) {
            return ApiResult.error("缺少openid");
        }
        if (!params.containsKey("phoneCode") || StringUtils.isEmpty(params.get("phoneCode").toString())) {
            return ApiResult.error("缺少phoneCode");
        }
        try {
            String phoneNumber = "";
            String openid = params.get("openid").toString();
            String phoneCode = params.get("phoneCode").toString();

            String accessToken = this.getAccessToken();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", phoneCode);
            String res = HttpUtil.createPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken).
                    body(jsonObject.toString()).execute().body();

            JSONObject result = JSONObject.parseObject(res);
            if ("0".equals(result.getString("errcode"))) {
                JSONObject phone_info = result.getJSONObject("phone_info");
                phoneNumber = phone_info.get("phoneNumber").toString();
            }

            //查看表里有没有这个用户
            MallMemberUser memberUser = memberUserService.queryByOpenid(openid);
            if (memberUser == null) {
                return ApiResult.error("请先授权登录");
            } else {
                memberUser.setUpdateAt(DateUtils.getTime());
                memberUser.setPhone(phoneNumber);
                if (memberUserService.updateMallMemberUser(memberUser) > 0) {
                    return ApiResult.ok().put("data", memberUser);
                }
            }

            return ApiResult.error("信息解析异常");
        } catch (Exception e) {
            return ApiResult.error("信息解析异常");
        }
    }

    /**
     * 获取access_token
     */
    public String getAccessToken() {
        JSONObject jsonObject = new JSONObject();
        String accessToken = "";
        //String redisKey = "xcx:access_token";
        String redisKey = "xcxtest:access_token";
        try {
            if (redisCache.hasKey(redisKey)) {
                return redisCache.getCacheObject(redisKey).toString();
            }
            String url = "https://api.weixin.qq.com/cgi-bin/token";
            String result = HttpUtils.sendGet(url, "" +
                    "grant_type=client_credential&" +
                    "appid=" + "wx898f44c913f1de6f" + "&" +
                    "secret=" + "995c5b868a455f2ce2cf025fd526957a");
            jsonObject = JSONObject.parseObject(result);
            // 有效期(s)
            Integer expiresIn = 0;
            if (ObjectUtils.isNotEmpty(jsonObject)) {
                accessToken = jsonObject.getString("access_token");
                expiresIn = jsonObject.getInteger("expires_in");
            }
            if (StringUtils.isBlank(accessToken)) {
                logger.error("小程序获取access_token失败 -> {" + DateUtils.getTime() + ": " + jsonObject + "}");
            } else {
                redisCache.setCacheObject(redisKey, accessToken, expiresIn, SECONDS);
            }
        } catch (Exception e) {
            logger.error("小程序获取access_token异常 -> {" + DateUtils.getTime() + ": " + e.getMessage() + "}");
        }
        return accessToken;
    }

    //生成6位随机数
    private String buildCode() {
        String sources = "0123456789"; // 加上一些字母，就可以生成pc站的验证码了
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 6; j++) {
            flag.append(sources.charAt(rand.nextInt(10)) + "");
        }
        return flag.toString();
    }

    /**
     * 获取省列表
     *
     * @return 行政区域集合
     */
    @GetMapping("/getProvinceList")
    public AjaxResult getProvinceList() {
        try {
            List<SetRegion> list = setRegionService.selectRegionProvinceList();
            return AjaxResult.success().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取省列表异常");
        }
    }

    /**
     * 获取市或区县列表
     *
     * @param id 行政区域ID
     * @return 行政区域集合
     */
    @GetMapping("/getCityOrAreaList")
    public AjaxResult getCityOrAreaList(Integer id) {
        try {
            List<SetRegion> list = setRegionService.selectRegionCityOrAreaList(id);
            return AjaxResult.success().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取市或区县列表异常");
        }
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户ID
     * @return 行政区域集合
     */
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(@RequestParam Long userId) {
        try {

            UserCoupon couponUser = new UserCoupon();
            couponUser.setUserId(userId);
            couponUser.setCouponType("1");
            List<UserCoupon> list = userCouponService.selectUserCouponList(couponUser);

            if (list.size() < 1) {
                // 新人优惠券
                BusinessCoupon businessCoupon = new BusinessCoupon();
                businessCoupon.setCouponType("1");
                businessCoupon.setDelFlag("0");
                List<BusinessCoupon> couponList = businessCouponService.selectBusinessCouponList(businessCoupon);
                if (couponList.size() > 0) {
                    // 给用户返
                    for (BusinessCoupon coupon : couponList) {

                        Date endTime = coupon.getEndTime();
                        Date nowTime = new Date();

                        if (nowTime.compareTo(endTime) < 1) {
                            UserCoupon userCoupon = new UserCoupon();
                            userCoupon.setUserId(userId);
                            userCoupon.setCouponId(coupon.getCouponId());
                            userCoupon.setTitle(coupon.getTitle());
                            userCoupon.setCouponMoney(coupon.getCouponMoney());
                            userCoupon.setCouponType(coupon.getCouponType());
                            userCoupon.setStartTime(coupon.getStartTime());
                            userCoupon.setEndTime(coupon.getEndTime());
                            userCoupon.setStatus("1");
                            userCouponService.insertUserCoupon(userCoupon);
                        }
                    }
                }
            }
            MallMemberUser mallMemberUser = memberUserService.selectMallMemberUserById(userId);
            if (ObjectUtils.isNotEmpty(mallMemberUser)){
                return AjaxResult.success(mallMemberUser);
            }else{
                return AjaxResult.error(403, "用户信息异常,请重新登录");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取用户信息异常");
        }
    }

    /**
     * 修改用户信息
     *
     * @param mallMemberUser userId 用户ID
     * @return
     */
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestBody MallMemberUser mallMemberUser) {
        if (mallMemberUser.getId() == null) {
            return AjaxResult.error("缺少用户IDuserId");
        }
        try {
            if (mallMemberUser.getProvinceId() != null) {
                SetRegion regionProvince = setRegionService.selectSetRegionById(mallMemberUser.getProvinceId());
                if (regionProvince != null) {
                    mallMemberUser.setProvinceName(regionProvince.getName());
                }
            }
            if (mallMemberUser.getCityId() != null) {
                SetRegion regionCity = setRegionService.selectSetRegionById(mallMemberUser.getCityId());
                if (regionCity != null) {
                    mallMemberUser.setCityName(regionCity.getName());
                }
            }
            return AjaxResult.success().put("data", memberUserService.updateMallMemberUser(mallMemberUser));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("修改用户信息异常");
        }
    }

    /**
     * 获取更多功能列表
     *
     * @return 集合
     */
    @GetMapping("/getConfigFunctionList")
    public AjaxResult getConfigFunctionList() {
        try {
            MallConfigFunction mallConfigFunction = new MallConfigFunction();
            mallConfigFunction.setStatus("0");
            mallConfigFunction.setIsShow("0");
            List<MallConfigFunction> list = mallConfigFunctionService.selectMallConfigFunctionList(mallConfigFunction);
            return AjaxResult.success().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取更多功能列表异常");
        }
    }

    /**
     * 用户优惠券列表
     *
     * @param pageNum  页码
     * @param pageSize 每页个数
     * @param userId   用户ID
     * @param status   使用状态：1-可使用，2-已使用，3-已过期
     * @return
     */
    @GetMapping("/getUserCouponList")
    public AjaxResult getUserCouponList(@RequestParam(defaultValue = "1") Integer pageNum,
                                        @RequestParam(defaultValue = "10") Integer pageSize,
                                        @RequestParam Long userId,
                                        @RequestParam String status) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setUserId(userId);
            userCoupon.setStatus(status);
            userCoupon.setDelFlag("0");
            List<UserCoupon> userCouponList = userCouponService.selectUserCouponList(userCoupon);
            PageInfo<UserCoupon> pageInfo = new PageInfo<>(userCouponList);
            return AjaxResult.success().put("data", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("用户优惠券列表异常");
        }
    }

    /**
     * 分享海报
     * @param id id
     * @return 结果
     */
    @GetMapping("/getPoster")
    public AjaxResult getPoster(@RequestParam Long id){
        if (ObjectUtils.isEmpty(id)){
            return AjaxResult.error("缺少id");
        }
        try {
            return memberUserService.getPoster(id);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }

    /**
     * 扫码进入会员绑定
     *
     * @return
     */
    @PostMapping("/bindingSchool")
    @ResponseBody
    public AjaxResult bindingSchool(@RequestBody Map<String, Object> params) {
        try {
            long schoolId = 0L;

            if (params.containsKey("schoolId") && StringUtils.isNotBlank(params.get("schoolId").toString())) {
                schoolId = Long.parseLong(params.get("schoolId").toString());
            }

            if (params.containsKey("userId") && StringUtils.isNotBlank(params.get("userId").toString())) {
                long userId = Long.parseLong(params.get("userId").toString());
                System.out.println("扫码进入会员绑定");
                System.out.println("schoolId="+schoolId);
                System.out.println("userId="+userId);

                MallMemberUser mallMemberUser = memberUserService.selectMallMemberUserById(userId);
                if (mallMemberUser != null) {
                    if (mallMemberUser.getIndexUserId() == 0 || mallMemberUser.getIndexUserId() == null) {
                        // 绑定
                        MallMemberUser user = new MallMemberUser();
                        user.setId(userId);
                        user.setIndexUserId(schoolId);
                        memberUserService.updateMallMemberUserInfo(user);
                    } else {
                        schoolId = mallMemberUser.getIndexUserId();
                    }
                }
            }

            return AjaxResult.success().put("data", memberUserService.selectMallMemberUserById(schoolId));
        } catch (Exception e) {
            return AjaxResult.error("扫码进入会员绑定异常");
        }
    }

    /**
     * 获取会员价格
     *
     * @return
     */
    @GetMapping("/getUserPrice")
    public AjaxResult getUserPrice(@RequestParam Map<String, Object> params) {
        try {
            HashMap<String, Object> map = new HashMap<>();
            String userPrice = "-1";
            if (params.containsKey("userId") && StringUtils.isNotBlank(params.get("userId").toString())) {
                long userId = Long.parseLong(params.get("userId").toString());
                MallMemberUser mallMemberUser = memberUserService.selectMallMemberUserById(userId);
                if (mallMemberUser != null && mallMemberUser.getIndexUserId() != 0 && mallMemberUser.getIndexUserId() != null) {
                    MallMemberUser topUser = memberUserService.selectMallMemberUserById(mallMemberUser.getIndexUserId());
                    if (topUser != null && topUser.getIndexPrice().compareTo(new BigDecimal(0)) > 0) {
                        userPrice = String.valueOf(topUser.getIndexPrice());
                    }
                }
            }
            map.put("userPrice", userPrice);
            return AjaxResult.success(map);
        } catch (Exception e) {
            return AjaxResult.error("获取会员价格异常");
        }
    }

    /**
     * 获取扫码绑定上级用户轮播列表
     *
     * @param memberUserId 登录用户ID
     * @return 获取扫码绑定上级退货轮播列表
     */
    @GetMapping("/getBindingTopUserList")
    public AjaxResult getBindingTopUserList(Long memberUserId) {
        try {
            MallMemberUser memberUser = mallMemberUserMapper.selectMallMemberUserById(memberUserId);
            List<MallMemberBanner> list = new ArrayList<>();
            if (memberUser != null && memberUser.getIndexUserId() != 0) {
                MallMemberBanner memberBanner = new MallMemberBanner();
                memberBanner.setMemberUserId(memberUser.getIndexUserId());
                list = mallMemberBannerService.selectMallMemberBannerList(memberBanner);
            }
            return AjaxResult.success().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取扫码绑定上级用户轮播列表异常");
        }
    }
}
