package com.ruoyi.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.AesCbcUtil;
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.UUID;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.vo.*;
import com.ruoyi.mall.service.*;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * apiController
 *
 * @author chang
 * @date 2021-11-25
 */
@RestController
@RequestMapping("/api/member")
@ResponseBody
public class ApiMemberController
{
    @Autowired
    private IMallMemberUserService memberUserService;
    @Autowired
    private IMallMemberAddressService memberAddressService;

    @Autowired
    private IMallMemberCartService memberCartService;

    @Autowired
    private IMallGoodsGoodsService goodsGoodsService;

    @Autowired
    private IMallGoodsProductService goodsProductService;

    @Autowired
    private IMallFeedbackService feedbackService;

    @Autowired
    private IMallCouponService couponService;

    @Autowired
    private IMallMemberSearchHistoryService searchHistoryService;

    @Resource
    private ITbSignUpService tbSignUpService;

    /**
     * 小程序授权登陆
     * @param
     * @return
     */
    @PostMapping("/getUserInfoForXCX")
    @ResponseBody
    public ApiResult getUserInfoForXCX(@RequestBody Map<String, Object> map) {
        try {
            // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
            // 千卓
//            String params = "appid=wxe11d71c10e2cc018&secret=9658439e9700927f5f1e9db73a27f12e&js_code=" + map.get("loginCode").toString() + "&grant_type=" + "authorization_code";
            String params = "appid=wx236db05b13789344&secret=1d65fa7709260c9d3c1dcfb535a80b3e&js_code=" + map.get("loginCode").toString() + "&grant_type=" + "authorization_code";
            // 发送请求
            String response = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session?" + params,"");
            // 解析相应内容（转换成jso    n对象）
            JSONObject json = JSONObject.parseObject(response);
            System.out.println("授权登录请求json："+json);
            String openid = json.getString("openid");
            //查看表里有没有这个用户
            MallMemberUser memberUserDO = memberUserService.queryByOpenid(openid);
            if(memberUserDO==null){
                //2、对encryptedData加密数据进行AES解密
                MallMemberUser memberUser = new MallMemberUser();
                memberUser.setName(map.get("nickName").toString());
                memberUser.setOpenid(openid);
                memberUser.setAvatar(map.get("avatarUrl").toString());
                memberUser.setToken(UUID.randomUUID().toString(true));
                memberUser.setCreateAt(DateUtils.getTime());
                memberUser.setUpdateAt(DateUtils.getTime());
                if (map.containsKey("parentId")){
                    memberUser.setIntroUser(Long.parseLong(map.get("parentId").toString()));
                }
                if(memberUserService.insertMallMemberUser(memberUser)>0){
                    return ApiResult.ok().put("data", memberUser);
                }
            }
            return ApiResult.ok("登陆成功").put("data", memberUserDO);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("授权失败");
        }
    }

    /**
     * 小程序授权手机号登陆
     * @param params
     * @return
     */
    @PostMapping("/phone/getXcxPhoneUserInfo")
    @ResponseBody
    public ApiResult getXcxPhoneUserInfo(@RequestBody Map<String,Object> params) {
        if (!params.containsKey("session_key")||!params.containsKey("encryptedData")||!params.containsKey("iv")){
            return ApiResult.error("缺少参数");
        }
        try {
            String session_key = params.get("session_key").toString();
            //对encryptedData加密数据进行AES解密
            String decrypts = AesCbcUtil.decrypt(params.get("encryptedData").toString(), session_key,
                    params.get("iv").toString(), "UTF-8");
            if (null != decrypts && decrypts.length() > 0) {
                JSONObject jsons = JSONObject.parseObject(decrypts);
                String memberPhone = jsons.get("phoneNumber").toString();
                MallMemberUser mu = memberUserService.queryByPhone(memberPhone);
                if (mu==null){
                    MallMemberUser memberUser = new MallMemberUser();
                    if (params.containsKey("memberName")){
                        memberUser.setName(jsons.get("nickName").toString());
                    }else{
                        memberUser.setName("XFML"+buildCode());
                    }

                    memberUser.setPhone(memberPhone);
                    if (params.containsKey("openid")){
                        String openid = params.get("openid").toString();
                        memberUser.setOpenid(openid);
                    }
                    memberUser.setAvatar("https://image.xnszz.com/2024/04/16/6098aa849b0cb029031dd2544b2a4cef_20240416225245A003.png");
                    memberUser.setToken(UUID.randomUUID().toString(true));
                    memberUser.setCreateAt(DateUtils.getTime());
                    memberUser.setUpdateAt(DateUtils.getTime());
                    if(memberUserService.insertMallMemberUser(memberUser)>0){
                        return ApiResult.ok().put("data", memberUser);
                    }
                }else {
                    return ApiResult.ok().put("data",mu);
                }
            }
            return ApiResult.error("信息解析异常");
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

//    /**
//     * 发送验证码
//     */
//    @PostMapping( "/sms/send")
//    @ResponseBody
//    public ApiResult smsSend(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("phone")){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            String phone = params.get("phone").toString();
////			String type = params.get("type").toString();
//            SmsCode codeDO = new SmsCode();
//            codeDO.setCreateAt(new Date());
//            codeDO.setPhone(phone);
//            codeDO.setType(1);
//            codeDO.setStatus(0);
//            codeDO.setDelFlag(0);
//            codeDO.setCode(buildCode());
//            //发送验证码
//            JuSms.sendSms(phone,codeDO.getCode());
//            smsCodeService.insertSmsCode(codeDO);
//            return ApiResult.ok("发送成功").put("data",codeDO);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }

    //生成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)) + "");
        }
//			System.out.println(flag.toString());
        return flag.toString();
    }

    /**
     * 获取个人信息
     */
    @GetMapping("/user/info")
    @ResponseBody
    public ApiResult userInfo(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")
        ){
            return ApiResult.error("参数异常");
        }
        try{
            MemberUserVO userVO = memberUserService.selectMemberVOUserById(MapUtils.getLong(params, "userId"));
            if (userVO==null){
                return ApiResult.error("用户信息异常");
            }
            return ApiResult.ok().put("data",userVO);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 修改个人信息
     */
    @PostMapping("/user/update")
    @ResponseBody
    public ApiResult userDate(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")){
            return ApiResult.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            MallMemberUser userDO = memberUserService.selectMallMemberUserById(Long.parseLong(userId));
            if (params.containsKey("avatar")){
                String avatar = params.get("avatar").toString();
                userDO.setAvatar(avatar);
            }
            if (params.containsKey("name")){
                String name = params.get("name").toString();
                userDO.setName(name);
            }
            if (params.containsKey("wechat")){
                String wechat = params.get("wechat").toString();
                userDO.setWechat(wechat);
            }
            if (params.containsKey("phone")){
                String phone = params.get("phone").toString();
                userDO.setPhone(phone);
            }
            if (params.containsKey("sex")){
                String sex = params.get("sex").toString();
                userDO.setSex(sex);
            }
            memberUserService.updateMallMemberUser(userDO);
            MemberUserVO result = new MemberUserVO();
            result.setId(userDO.getId());
            result.setAvatar(userDO.getAvatar());
            result.setName(userDO.getName());
            result.setOpenid(userDO.getOpenid());
            result.setPhone(userDO.getPhone());
            result.setQrCode(userDO.getQrCode());
            result.setSex(userDO.getSex());
            result.setWechat(userDO.getWechat());
            return ApiResult.ok().put("data",result);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 修改密码
     */
    @PostMapping( "/user/changePwd")
    @ResponseBody
    public ApiResult userChangePwd(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||!params.containsKey("oldPwd")||!params.containsKey("newPwd")){
            return ApiResult.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            String oldPwd = params.get("oldPwd").toString();
            String newPwd = params.get("newPwd").toString();
            MallMemberUser userDO = memberUserService.selectMallMemberUserById(Long.parseLong(userId));
            if (userDO==null){
                return ApiResult.error("账号信息异常请重新登录!");
            }
            String pwd = userDO.getPassword();
            if (!pwd.equals(Md5Utils.hash(oldPwd))){
                return ApiResult.error("原密码错误!");
            }
            String nPwd = Md5Utils.hash(newPwd);
            userDO.setPassword(nPwd);
            memberUserService.updateMallMemberUser(userDO);
            return ApiResult.ok().put("data",userDO);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 查询默认收货地址
     */
    @GetMapping("/address/getDefault")
    @ResponseBody
    public ApiResult addressGetDefault(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")){
            return ApiResult.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            MemberAddressVO list = memberAddressService.getDefaultVO(Long.parseLong(userId));
            return ApiResult.ok().put("data",list);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 查询个人收货地址列表
     */
    @GetMapping( "/address/list")
    @ResponseBody
    public ApiResult addressList(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")){
            return ApiResult.error("参数异常");
        }
        try{
            List<MemberAddressVO> list = memberAddressService.queryAddressVOByUserId(params);
            return ApiResult.ok().put("data",list);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 根据id获取收货地址详情
     */
    @GetMapping("/address/info")
    @ResponseBody
    public ApiResult addressInfo(@RequestParam Map<String, Object> params){
        if (!params.containsKey("addressId")){
            return ApiResult.error("参数异常");
        }
        try{
            String addressId = params.get("addressId").toString();
            MemberAddressVO address = memberAddressService.selectMallMemberAddressVOById(Long.parseLong(addressId));
            return ApiResult.ok().put("data",address);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 添加收货地址
     */
    @PostMapping( "/address/add")
    @ResponseBody
    public ApiResult addressAdd(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||!params.containsKey("province")
                ||!params.containsKey("city")||!params.containsKey("area")
                ||!params.containsKey("address")
                ||!params.containsKey("name")||!params.containsKey("phone")
                ||!params.containsKey("default")
        ){
            return ApiResult.error("参数异常");
        }
        try{
            int count = memberAddressService.add(params);
            if (count>0){
                return ApiResult.ok();
            }
            return ApiResult.error();
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 修改收货地址
     */
    @PostMapping("/address/change")
    @ResponseBody
    public ApiResult addressChange(@RequestBody Map<String, Object> params){
        if (!params.containsKey("id")||!params.containsKey("province")
                ||!params.containsKey("city")||!params.containsKey("area")
                ||!params.containsKey("address")||!params.containsKey("userId")
                ||!params.containsKey("name")||!params.containsKey("phone")
                ||!params.containsKey("default")
        ){
            return ApiResult.error("参数异常");
        }
        try{
            int count =memberAddressService.change(params);
            if (count>0){
                return ApiResult.ok();
            }
            return ApiResult.error();
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 删除收货地址
     */
    @PostMapping( "/address/remove")
    @ResponseBody
    public ApiResult addressRemove(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("userId")
        ){
            return ApiResult.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            String addressId = params.get("addressId").toString();
            MallMemberAddress addressDO = memberAddressService.selectMallMemberAddressById(Long.parseLong(addressId));
            if (!userId.equals(addressDO.getUserId().toString())){
                return ApiResult.error("收货地址异常");
            }
            memberAddressService.deleteMallMemberAddressById(Long.parseLong(addressId));
            return ApiResult.ok("删除成功");
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 设置默认收货地址
     */
    @PostMapping("/address/default")
    @ResponseBody
    public ApiResult addressDefault(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("userId")
        ){
            return ApiResult.error("参数异常");
        }
        try{
            return memberAddressService.toDefault(params);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 查询全局优惠券
     */
//    @PostMapping( "/coupon/list")
//    @ResponseBody
//    public ApiResult couponList(@RequestBody Map<String, Object> params){
//        try{
////			String userId = params.get("userId").toString();
//            List<CouponCoupon> list = couponCouponService.queryAll(params);
//            return ApiResult.ok().put("data",list.get(0));
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }

    /**
     * 领取全局优惠券
     */
//    @PostMapping( "/get/coupon")
//    @ResponseBody
//    public ApiResult getCoupon(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("couponId")||!params.containsKey("userId")){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            int count = memberCouponService.count(params);
//            if (count>0){
//                return ApiResult.error("您已领取过该优惠券");
//            }
//            String couponId = params.get("couponId").toString();
//            String userId = params.get("userId").toString();
//            CouponCoupon couponCoupon = couponCouponService.selectCouponCouponById(couponId);
//            if (couponCoupon==null){
//                return ApiResult.error("优惠券不存在");
//            }
//            int num = couponCoupon.getTotalNum();
//            if (num<1){
//                return ApiResult.error("优惠券已被抢完");
//            }
//            MemberCoupon memberCoupon = new MemberCoupon();
//            memberCoupon.setId(StringUtils.get32UUID());
//            memberCoupon.setUserId(userId);
//            memberCoupon.setCouponId(couponId);
//            memberCoupon.setCouponName(couponCoupon.getName());
//            memberCoupon.setMoney(couponCoupon.getMoney());
//            memberCoupon.setEnoughMoney(couponCoupon.getEnoughMoney());
//            memberCoupon.setStatus(0);
//            memberCoupon.setEndAt(couponCoupon.getEndAt());
//            memberCoupon.setCreateAt(DateUtils.getNowDate());
//            memberCoupon.setDelFlag(0);
//            memberCoupon.setDay(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,couponCoupon.getEndAt()));
//            memberCoupon.setType(0);
//            memberCouponService.insertMemberCoupon(memberCoupon);
//            couponCouponService.sendCoupon(couponCoupon);
//
//            return ApiResult.ok("您已成功领取优惠券");
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }

    /**
     * 我的优惠券列表
     */
//    @PostMapping( "/myCoupon/list")
//    @ResponseBody
//    public ApiResult myCouponList(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")||!params.containsKey("status")
//                ||!params.containsKey("pageNum")
//                ||!params.containsKey("pageSize")){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            //先设置过期优惠券
//            params.put("today",DateUtils.getDayBegin());
//            memberCouponService.overdue(params);
//
//            PageInfo<Map<String,Object>> list = memberCouponService.queryPageByUserId(params);
//            return ApiResult.ok().put("data",list);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }

    /**
     * 查询可用优惠券
     */
//    @PostMapping( "/myCoupon/available")
//    @ResponseBody
//    public ApiResult myCouponAvailable(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")||!params.containsKey("money")
//        ){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            //先设置过期优惠券
//            params.put("today",DateUtils.getDayBegin());
//            memberCouponService.overdue(params);
//            //查询可用优惠券
//            List<MemberCoupon> list = memberCouponService.queryAvailable(params);
//            return ApiResult.ok().put("data",list);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }


    /**
     * 购物车查询
     * @param params
     * @return
     */
    @GetMapping("/cart/list")
    @ResponseBody
    public ApiResult list(@RequestParam Map<String, Object> params){
        try {
            if (!params.containsKey("userId")){
                return ApiResult.error("参数错误");
            }
            //查询购物车的正常商品
            MallMemberCart cart = new MallMemberCart();
            cart.setUserId(Long.parseLong(params.get("userId").toString()));
            List<MallMemberCart> list = memberCartService.selectMallMemberCartList(cart);

            List<MallCartGoodsVO> result = new ArrayList<>();
            for (MallMemberCart memberCart: list) {
                MallGoodsGoods goods = goodsGoodsService.selectMallGoodsGoodsById(memberCart.getGoodsId());
                MallGoodsProduct product = goodsProductService.selectMallGoodsProductById(memberCart.getProductId());

                MallCartGoodsVO goodsVO = new MallCartGoodsVO();
                goodsVO.setGoodsId(goods.getId().toString());
                goodsVO.setGoodsName(goods.getGoodsName());
                goodsVO.setGoodsTitle(goods.getGoodsTitle());
                goodsVO.setGoodsImg(goods.getGoodsImg());
                goodsVO.setPostFee(goodsVO.getPostFee());
                goodsVO.setProductName(product.getProductName());
                goodsVO.setPrice(product.getPrice().toString());
                goodsVO.setPriceN(product.getPriceN().toString());
                goodsVO.setStock(product.getStock().toString());
                goodsVO.setNumSale(product.getNumSale().toString());
                goodsVO.setCount(memberCart.getTotal().toString());
                goodsVO.setCartId(memberCart.getId().toString());
                goodsVO.setProductId(product.getId().toString());
                result.add(goodsVO);
            }
            return ApiResult.ok().put("data", result);
        } catch (Exception e) {

            return ApiResult.error("购物车查询失败");
        }
    }

    /**
     * 购物车 确认订单
     * @param map
     * @return
     */
    @GetMapping("/cart/enter")
    @ResponseBody
    public ApiResult cartEnter(@RequestParam Map<String, Object> map){
        try {
            if (!map.containsKey("cartIds")|| !map.containsKey("userId")){
                return ApiResult.error("参数错误");
            }
			String cartIds = map.get("cartIds").toString();
            String userId = map.get("userId").toString();

            String[] cartIdsList = cartIds.split(",");

            List<MallCartGoodsVO> result = new ArrayList<>();
            for (String cartId :cartIdsList) {
                MallMemberCart cart = new MallMemberCart();
                cart.setUserId(Long.parseLong(userId));
                cart.setId(Long.parseLong(cartId));
                List<MallMemberCart> list = memberCartService.selectMallMemberCartList(cart);
                if (list.size() > 0){
                    MallMemberCart memberCart = list.get(0);
                    MallGoodsGoods goods = goodsGoodsService.selectMallGoodsGoodsById(memberCart.getGoodsId());
                    MallGoodsProduct product = goodsProductService.selectMallGoodsProductById(memberCart.getProductId());

                    MallCartGoodsVO goodsVO = new MallCartGoodsVO();
                    goodsVO.setGoodsId(goods.getId().toString());
                    goodsVO.setGoodsName(goods.getGoodsName());
                    goodsVO.setGoodsTitle(goods.getGoodsTitle());
                    goodsVO.setGoodsImg(goods.getGoodsImg());
                    goodsVO.setPostFee(goodsVO.getPostFee());
                    goodsVO.setProductName(product.getProductName());
                    goodsVO.setPrice(product.getPrice().toString());
                    goodsVO.setPriceN(product.getPriceN().toString());
                    goodsVO.setStock(product.getStock().toString());
                    goodsVO.setNumSale(product.getNumSale().toString());
                    goodsVO.setCount(memberCart.getTotal().toString());
                    goodsVO.setCartId(memberCart.getId().toString());
                    goodsVO.setProductId(product.getId().toString());
                    result.add(goodsVO);
                }
            }

            return ApiResult.ok().put("data",result);
        } catch (Exception e) {
            return ApiResult.error("购物车确认失败");
        }
    }

    /**
     * 购物车添加
     * @param map
     * @return
     */
    @RequestMapping("/cart/add")
    @ResponseBody
    public ApiResult cartAdd(@RequestBody Map<String, Object> map){
        try {
            if (!map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())
                    || !map.containsKey("goodsId") || StringUtils.isBlank(map.get("goodsId").toString())
                    || !map.containsKey("productId") || StringUtils.isBlank(map.get("productId").toString())
                    || !map.containsKey("num") || StringUtils.isBlank(map.get("num").toString())
            ){
                return ApiResult.error("参数错误");
            }

            MallMemberCart memberCart = new MallMemberCart();
            memberCart.setUserId(Long.parseLong(map.get("userId").toString()));
            memberCart.setGoodsId(Long.parseLong(map.get("goodsId").toString()));
            memberCart.setProductId(Long.parseLong(map.get("productId").toString()));
            MallMemberCart orgMemberCart = memberCartService.selectMallMemberCartByCart(memberCart);
            if (orgMemberCart != null){
                memberCart.setTotal(Integer.parseInt(map.get("num").toString()) + orgMemberCart.getTotal());
                memberCart.setUpdateAt(DateUtils.getTime());
                memberCart.setId(orgMemberCart.getId());
                int status = memberCartService.updateMallMemberCart(memberCart);
                return status > 0 ? ApiResult.ok("添加成功") : ApiResult.error("添加购物车失败");
            }else {
                memberCart.setTotal(Integer.parseInt(map.get("num").toString()));
                memberCart.setUpdateAt(DateUtils.getTime());
                int status = memberCartService.insertMallMemberCart(memberCart);
                return status > 0 ? ApiResult.ok("添加成功") : ApiResult.error("添加购物车失败");
            }


        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("添加购物车失败");
        }
    }

    /**
     * 购物车删除
     * @param map
     * @return
     */
    @RequestMapping("/cart/remove")
    @ResponseBody
    public ApiResult cartRemove(@RequestBody Map<String, Object> map){
        try {
            if (!map.containsKey("cartIds") || StringUtils.isBlank(map.get("cartIds").toString())
                    ||!map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())
            ){
                return ApiResult.error("参数错误");
            }
            memberCartService.removeByUserIdAndCardIds(map.get("cartIds").toString(),map.get("userId").toString());
            return ApiResult.ok("删除成功");
        } catch (Exception e) {
            return ApiResult.error("购物车删除失败");
        }
    }

    /**
     * 根据购物车id购物车修改
     * @param map
     * @return
     */
    @RequestMapping("/cart/addAndSub")
    @ResponseBody
    public ApiResult addAndSub(@RequestBody Map<String, Object> map){
        try {
            if (!map.containsKey("cartId") || StringUtils.isBlank(map.get("cartId").toString())
                    || !map.containsKey("num") || StringUtils.isBlank(map.get("num").toString())
                    || !map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())
            ){
                return ApiResult.error("参数错误");
            }

            MallMemberCart cart = new MallMemberCart();
            cart.setId(Long.parseLong(map.get("cartId").toString()));
            cart.setTotal(Integer.parseInt(map.get("num").toString()));
            cart.setUserId(Long.parseLong(map.get("userId").toString()));
            int status = memberCartService.updateMallMemberCart(cart);
            return status > 0 ? ApiResult.ok() : ApiResult.error("购物车修改失败");
        } catch (Exception e) {
            return ApiResult.error("购物车修改失败");
        }
    }

    /**
     * 根据商品信息 购物车修改
     * @param map
     * @return
     */
    @RequestMapping("/cart/addAndSubByGoods")
    @ResponseBody
    public ApiResult addAndSubByGoods(@RequestBody Map<String, Object> map){
        try {
            if (!map.containsKey("productId") || StringUtils.isBlank(map.get("productId").toString())
                    || !map.containsKey("goodsId") || StringUtils.isBlank(map.get("goodsId").toString())
                    || !map.containsKey("num") || StringUtils.isBlank(map.get("num").toString())
                    || !map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())
            ){
                return ApiResult.error("参数错误");
            }
            MallMemberCart cart = new MallMemberCart();
            cart.setGoodsId(Long.parseLong(map.get("goodsId").toString()));
            cart.setProductId(Long.parseLong(map.get("productId").toString()));
            cart.setUserId(Long.parseLong(map.get("userId").toString()));
            MallMemberCart orgCart = memberCartService.selectMallMemberCartByCart(cart);
            if (orgCart != null){
                orgCart.setTotal(orgCart.getTotal() + Integer.parseInt(map.get("num").toString()));
                orgCart.setUpdateAt(DateUtils.getTime());
                int status = memberCartService.updateMallMemberCart(orgCart);
                return status > 0 ? ApiResult.ok("添加成功") : ApiResult.error("修改购物车失败");
            }
            cart.setTotal(Integer.parseInt(map.get("num").toString()));
            cart.setUpdateAt(DateUtils.getTime());
            int status = memberCartService.insertMallMemberCart(cart);
            return status > 0 ? ApiResult.ok("添加成功") : ApiResult.error("添加购物车失败");
        } catch (Exception e) {
            return ApiResult.error("购物车修改失败");
        }
    }


//    /**
//     * -我的推荐   --直属团队
//     */
//    @PostMapping( "/user/myUnder")
//    @ResponseBody
//    public ApiResult codeList(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            return memberUserService.queryMyUnder(params);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }
//
//
//    /**
//     * 注销功能
//     */
//    @PostMapping( "/user/delFlag")
//    @ResponseBody
//    public ApiResult delFlag(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId") || StringUtils.isBlank(params.get("userId").toString())){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            String userId = params.get("userId").toString();
//
//            MemberUser userDO = memberUserService.selectMemberUserById(userId);
//
////			BigDecimal useMoney = orderOrderService.canUseMoney(params);
////			if (useMoney.compareTo(new BigDecimal(0)) == 1) {
////				return ApiResult.error("请清理账户余额");
////			}
////			int number = orderOrderService.getNoSuccessOrderNumber(params);
////			if (number != 0) {
////				return ApiResult.error("请清理未完成订单");
////			}
//            userDO.setDisabled(2);
//            memberUserService.updateMemberUser(userDO);
//            return ApiResult.ok();
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }
//
//    /**
//     * 今日签到
//     */
//    @PostMapping( "/user/signIn")
//    @ResponseBody
//    public ApiResult userSignIn(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            return memberSignService.signIn(params);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }
//
//    /**
//     * 签到列表
//     */
//    @PostMapping( "/user/signList")
//    @ResponseBody
//    public ApiResult userSignList(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")||!params.containsKey("month")){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            List<MemberSign>list = memberSignService.list(params);
//            return ApiResult.ok().put("data",list);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }
//
    /**
     * 商品收藏
     */
    @PostMapping("/goods/collectOrCancel")
    @ResponseBody
    public ApiResult collectOrCancel(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")
                ||!params.containsKey("goodsId")
//				||!params.containsKey("type") //1-收藏 ，0-取消收藏
        ){
            return ApiResult.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            String goodsId = params.get("goodsId").toString();
            int count = memberUserService.selectCollectCount(params);
            if (count<1){
                MemberCollectVO memberGoods = new MemberCollectVO();
                memberGoods.setGoodsId(Long.parseLong(goodsId));
                memberGoods.setMemberId(Long.parseLong(userId));
                memberUserService.insertMemberGoods(memberGoods);
                return ApiResult.ok("收藏成功").put("data",1);

            }else {
                memberUserService.deleteMemberGoodsByParam(params);
                return ApiResult.ok("已取消收藏").put("data",0);
            }
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 商品收藏列表
     */
    @GetMapping("/goods/collectList")
    @ResponseBody
    public ApiResult collectList(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")
                ||!params.containsKey("pageNum")
                ||!params.containsKey("pageSize")
        ){
            return ApiResult.error("参数异常");
        }
        try{
            PageInfo<IndexGoodsVO> list = memberUserService.queryByUserId(params);

            return ApiResult.ok().put("data",list);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /*
    * 获取足迹
    * */
    @GetMapping("/goods/foodMarkList")
    @ResponseBody
    public ApiResult foodMarkList(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")
                ||!params.containsKey("pageNum")
                ||!params.containsKey("pageSize")
                ){
            return ApiResult.error("参数异常");
        }
        try{
            PageInfo<IndexGoodsVO> list = memberUserService.queryFoodMarkByUserId(params);

            return ApiResult.ok().put("data",list);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /*
     * 意见反馈
     * */
    @PostMapping("/feedback")
    @ResponseBody
    public ApiResult feedback(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")
                ||!params.containsKey("phone")
                ||!params.containsKey("context")
                ){
            return ApiResult.error("参数异常");
        }
        try{

            MallFeedback feedback = new MallFeedback();
            feedback.setContext(params.get("context").toString());
            feedback.setUserId(Long.parseLong(params.get("userId").toString()));
            feedback.setPhone(params.get("phone").toString());
            feedback.setCreateAt(DateUtils.getTime());
            int status = feedbackService.insertMallFeedback(feedback);

            return status > 0 ? ApiResult.ok("反馈成功") : ApiResult.ok("反馈失败");
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }
//
//    /**
//     * 文章收藏
//     */
//    @PostMapping( "/article/collectOrCancel")
//    @ResponseBody
//    public ApiResult articleCollectOrCancel(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")
//                ||!params.containsKey("articleId")
////				||!params.containsKey("type") //1-收藏 ，0-取消收藏
//        ){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            String userId = params.get("userId").toString();
//            String articleId = params.get("articleId").toString();
//            int count = memberArticleService.count(params);
//            if (count<1){
//                MemberArticle memberArticle = new MemberArticle();
//                memberArticle.setArticleId(articleId);
//                memberArticle.setUserId(userId);
//                memberArticleService.insertMemberArticle(memberArticle);
//                return ApiResult.ok("收藏成功").put("data",1);
//
//            }else {
//                memberArticleService.deleteMemberArticleByParam(params);
//                return ApiResult.ok("已取消收藏").put("data",0);
//            }
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }
//
//    /**
//     * 文章收藏列表
//     */
//    @PostMapping( "/article/collectList")
//    @ResponseBody
//    public ApiResult articleCollectList(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")
//                ||!params.containsKey("pageNum")
//                ||!params.containsKey("pageSize")
//        ){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            PageInfo<Map<String,Object>> list = memberArticleService.queryByUserId(params);
//
//            return ApiResult.ok().put("data",list);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }
//
//    /**
//     * 我的总积分
//     */
//    @PostMapping( "/score/myInfo")
//    @ResponseBody
//    public ApiResult scoreMyInfo(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")
//        ){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            String userId = params.get("userId").toString();
//            MemberUser memberUser = memberUserService.selectMemberUserById(userId);
//
//            BigDecimal allScore = memberScoreService.countByUserId(userId);
//            Map<String,Object> map = new HashMap<>();
//            map.put("score",memberUser.getScore());
//            map.put("allScore",allScore);
//
//            return ApiResult.ok().put("data",map);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }
//
//    /**
//     * 积分详情列表
//     */
//    @PostMapping( "/score/list")
//    @ResponseBody
//    public ApiResult scoreList(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")
//                ||!params.containsKey("type")
//                ||!params.containsKey("pageNum")
//                ||!params.containsKey("pageSize")
//        ){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            PageInfo<Map<String,Object>> list = memberScoreService.queryByUserId(params);
//
//            return ApiResult.ok().put("data",list);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }
//
//    /**
//     * 分享信息查询
//     */
//    @PostMapping( "/user/share")
//    @ResponseBody
//    public ApiResult userShare(@RequestBody Map<String, Object> params){
//        if (!params.containsKey("userId")){
//            return ApiResult.error("参数异常");
//        }
//        try{
//            String userId = params.get("userId").toString();
////            MemberUser userDO = memberUserService.selectMemberUserById(userId);
//            MemberUser userDO = memberUserService.selectMemberUserById(userId);
//            if (userDO==null){
//                return ApiResult.error("用户id不存在");
//            }
//            Map<String,Object> map = new HashMap<>();
//            map.put("name",userDO.getName());
//            map.put("avator",userDO.getAvator());
//            map.put("phone",userDO.getPhone());
//            map.put("code","http://app.hntyp.com/share/register.html?parentId="+userDO.getId());
//            CmsHome cmsHome = cmsHomeService.selectCmsHomeById(6l);
//            map.put("background",cmsHome.getValue());
//
//            return ApiResult.ok().put("data",map);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }

    //获取新人优惠券
    @GetMapping("/getNewPersonCoupons")
    public ApiResult getNewPersonCoupons(){
        List<Map<String, Object>> coupons = couponService.selectMallCouponVOList();
        return ApiResult.ok().put("data",coupons);
    }
    //领取新人优惠券
    @PostMapping("/drawNewPersonCoupons")
    public ApiResult drawNewPersonCoupons(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("couponId")){
            return ApiResult.error("缺少参数");
        }
        try{
            Map<String, Object> map = memberUserService.checkUserCoupon(Long.parseLong(params.get("userId").toString()),params.get("couponId").toString());
            if (map == null){
                MallCoupon coupon = couponService.selectMallCouponById(Long.parseLong(params.get("couponId").toString()));
                MallMemberCoupon memberCoupon = new MallMemberCoupon();
                memberCoupon.setUserId(Long.parseLong(params.get("userId").toString()));
                memberCoupon.setCouponId(Long.parseLong(params.get("couponId").toString()));
                memberCoupon.setCreateAt(DateUtils.getTime());
                memberCoupon.setIsUsed("0");
                memberCoupon.setPrice(coupon.getPrice());
                memberUserService.insertUserCoupon(memberCoupon);
                return ApiResult.ok("领取成功");
            }else {
                return ApiResult.ok("已领取,不能重复领取");
            }

        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    //获取我的优惠券列表
    @GetMapping("/getMyCoupons")
    public ApiResult getMyCoupons(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")){
            return ApiResult.error("缺少参数");
        }
        List<Map<String, Object>> coupons = memberUserService.getMyCoupons(Long.parseLong(params.get("userId").toString()));
        return ApiResult.ok().put("data",coupons);
    }

    //获取搜索记录
    @GetMapping("/getMySearchHistory")
    public ApiResult getMySearchHistory(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")){
            return ApiResult.error("缺少参数");
        }
        MallMemberSearchHistory mallMemberSearchHistory = new MallMemberSearchHistory();
        mallMemberSearchHistory.setUserId(Long.parseLong(params.get("userId").toString()));
        List<MallMemberSearchHistory> coupons = searchHistoryService.selectMallMemberSearchHistoryList(mallMemberSearchHistory);
        return ApiResult.ok().put("data",coupons);
    }

    //删除搜索记录
    @PostMapping("/deleteMySearchHistory")
    public ApiResult deleteMySearchHistory(@RequestBody Map<String, Object> params){
        if (!params.containsKey("historyId")){
            return ApiResult.error("缺少参数");
        }
        try{
            searchHistoryService.deleteMallMemberSearchHistoryById(Long.parseLong(params.get("historyId").toString()));
            return ApiResult.ok("删除成功");
        }catch (Exception e){
            return ApiResult.error("系统出错");
        }

    }

    //批量删除搜索记录
    @PostMapping("/deleteAllSearchHistory")
    public ApiResult deleteAllSearchHistory(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")){
            return ApiResult.error("缺少参数");
        }
        try{
            searchHistoryService.deleteMallMemberSearchHistoryByUserId(Long.parseLong(params.get("userId").toString()));
            return ApiResult.ok("删除成功");
        }catch (Exception e){
            return ApiResult.error("系统出错");
        }

    }

    //获取记录个数
    @GetMapping("/getMyRecordCount")
    public ApiResult getMyRecordCount(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")){
            return ApiResult.error("缺少参数");
        }
        Map<String, Object> map = memberUserService.getMyRecordCount(Long.parseLong(params.get("userId").toString()));
        return ApiResult.ok().put("data",map);
    }

    /**
     * 查询所得积分
     * @param userId 用户ID
     * @return 结果
     */
    @GetMapping("/getSignUpScore")
    public AjaxResult getSignUpScore(@RequestParam(required = false) String userId){
        if (StringUtils.isBlank(userId)){
            throw new ServiceException("参数错误");
        }

        JSONObject result = tbSignUpService.getSignUpScore(Long.parseLong(userId));
        return AjaxResult.success(result);
    }

    /**
     * 签到
     * @param params 参数
     * @return 结果
     */
    @RepeatSubmit
    @PostMapping("/signUp")
    public AjaxResult signUp(@RequestBody Map<String,Object> params){
        String userId = MapUtils.getString(params, "userId");
        if (StringUtils.isBlank(userId)){
            throw new ServiceException("参数错误");
        }

        int signUp = tbSignUpService.getSignUp(Long.parseLong(userId));
        if (signUp>0){
            throw new ServiceException("今日已签到");
        }

        TbSignUp tbSignUp = new TbSignUp();
        tbSignUp.setUserId(Long.parseLong(userId));
        tbSignUp.setScore(1L);
        tbSignUp.setCreateTime(DateUtils.getNowDate());
        int i = tbSignUpService.insertTbSignUp(tbSignUp);
        return i > 0 ? AjaxResult.success() : AjaxResult.error();
    }
}
