package com.ruoyi.web.controller.api;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.redis.RedisCache;
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.mapper.MallGoodsProductMapper;
import com.ruoyi.mall.service.*;
import io.swagger.models.auth.In;
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.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

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

/**
 * apiController
 *
 * @author chang
 * @date 2021-11-25
 */
@SuppressWarnings("AlibabaRemoveCommentedCode")
@RestController
@RequestMapping("/api/member")
@ResponseBody
public class ApiMemberController
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @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 IMallMemberCmsService mallMemberCmsService;

    @Resource
    private IMallSalesmanService mallSalesmanService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private MallGoodsProductMapper mallGoodsProductMapper;

    @Resource
    private IMallConfigService mallConfigService;


    /**
     * 小程序手机号登陆
     * @param
     * @return
     */
    @PostMapping("/memberUserLogin")
    public ApiResult memberUserLogin(@RequestBody Map<String, Object> param){
        if (!param.containsKey("phone") || MapUtils.getString(param,"phone") == null){
            return ApiResult.error("缺少phone");
        }
        if (!param.containsKey("password") || MapUtils.getString(param,"password") == null){
            return ApiResult.error("缺少password");
        }
        try {
            return memberUserService.memberUserLogin(param);
        }catch (Exception e){
            e.printStackTrace();
            return ApiResult.error("服务器异常");
        }
    }

    /**
     * 绑定openid
     * @param
     * @return
     */
    @PostMapping("/bindingOpenid")
    public ApiResult bindingOpenid(@RequestBody Map<String, Object> param){
        if (!param.containsKey("userId") || MapUtils.getLong(param,"userId") == null){
            return ApiResult.error("缺少userId");
        }
        if (!param.containsKey("loginCode") || MapUtils.getString(param,"loginCode") == null){
            return ApiResult.error("缺少loginCode");
        }
        try {
            MallMemberUser memberUser = memberUserService.selectMallMemberUserById(MapUtils.getLong(param, "userId"));

            if (ObjectUtils.isNotEmpty(memberUser)){
                // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
                String params = "appid=wxd6fbe722d11e00f5&secret=84396e677785af5d3905784d36db8d73&js_code=" + MapUtils.getString(param,"loginCode") + "&grant_type=" + "authorization_code";
                // 发送请求
                String response = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session?" + params,"");
                // 解析相应内容（转换成jso    n对象）
                JSONObject json = JSONObject.parseObject(response);
                String openid = json.getString("openid");
                memberUser.setOpenid(openid);
                memberUser.setAvatar(MapUtils.getString(param,"headImg"));

                if (memberUser.getSalesmanId() == null) {
                    // List<MallSalesman> salesmanList = mallSalesmanService.selectMallSalesmanUserNumList();
                    // if (salesmanList.size() > 0) {
                    //     memberUser.setSalesmanId(salesmanList.get(0).getId());
                    // }

                    MallConfig bindingSalesman = mallConfigService.selectMallConfigByIdentifying("bindingSalesman");
                    if (bindingSalesman != null) {
                        memberUser.setSalesmanId(bindingSalesman.getConfigInt());
                    }
                }

                return ApiResult.toAjax(memberUserService.updateMallMemberUser(memberUser));
            }
            return ApiResult.error("用户信息异常");
        }catch (Exception e){
            e.printStackTrace();
            return ApiResult.error("服务器异常");
        }
    }

    /**
     * 找回密码
     * @param
     * @return
     */
    @PostMapping("/resetPassword")
    public ApiResult resetPassword(@RequestBody Map<String, Object> param){
        if (!param.containsKey("phone") || MapUtils.getString(param,"phone") == null){
            return ApiResult.error("缺少phone");
        }
        if (!param.containsKey("cmsCode") || MapUtils.getString(param,"cmsCode") == null){
            return ApiResult.error("缺少cmsCode");
        }
        if (!param.containsKey("newPassword") || MapUtils.getString(param,"newPassword") == null){
            return ApiResult.error("缺少newPassword");
        }
        try {
            //比对验证码
            int i = mallMemberCmsService.checkCmsCode(MapUtils.getString(param, "phone"), MapUtils.getString(param, "cmsCode"));
            if(i == 1){
                return ApiResult.error("验证码已过期");
            }else if( i == 2){
                return ApiResult.error("验证码错误 ");
            }

            return memberUserService.resetPassword(param);
        }catch (Exception e){
            e.printStackTrace();
            return ApiResult.error("服务器异常");
        }
    }

    /**
     * 小程序授权登陆
     * @param
     * @return
     */
    @PostMapping("/getUserInfoForXCX")
    @ResponseBody
    @RepeatSubmit
    public ApiResult getUserInfoForXCX(@RequestBody Map<String, Object> map) {
        try {
            // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
            // 千冻网
            String params = "appid=wxd6fbe722d11e00f5&secret=84396e677785af5d3905784d36db8d73&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");
            String session_key = json.getString("session_key");

            // List<MallSalesman> salesmanList = mallSalesmanService.selectMallSalesmanUserNumList();

            //查看表里有没有这个用户
            MallMemberUser memberUserDO = memberUserService.queryByOpenid(openid);
            String nickName = map.get("nickName").toString();
            String avatarUrl = map.get("avatarUrl").toString();

            Long parentId = MapUtils.getLong(map, "parentId");
            Long salesmanId = MapUtils.getLong(map, "salesmanId");

            System.out.println("小程序授权登陆");


            if(memberUserDO==null){
                System.out.println("新增用户");

                //2、对encryptedData加密数据进行AES解密
                MallMemberUser memberUser = new MallMemberUser();
                memberUser.setName(nickName);
                memberUser.setOpenid(openid);
                memberUser.setAvatar(avatarUrl);
                memberUser.setToken(UUID.randomUUID().toString(true));
                memberUser.setCreateAt(DateUtils.getTime());
                memberUser.setUpdateAt(DateUtils.getTime());

                if (parentId == null && salesmanId == null){
                    System.out.println("无parentId");

                    MallConfig bindingSalesman = mallConfigService.selectMallConfigByIdentifying("bindingSalesman");
                    if (bindingSalesman != null) {
                        memberUser.setSalesmanId(bindingSalesman.getConfigInt());
                    }
                }else {
                    if (salesmanId != null){
                        MallSalesman salesman = mallSalesmanService.selectMallSalesmanById(salesmanId.intValue());
                        if (salesman != null) {
                            memberUser.setSalesmanId(salesman.getId());
                        }else{
                            // 如果是非业务员,默认绑定
                            MallConfig bindingSalesman = mallConfigService.selectMallConfigByIdentifying("bindingSalesman");
                            if (bindingSalesman != null) {
                                memberUser.setSalesmanId(bindingSalesman.getConfigInt());
                            }
                        }
                    }else {
                        System.out.println("有parentId");
                        System.out.println("分享人parentId:" + parentId);

                        // 邀请分配业务员
                        memberUser.setIntroUser(parentId);
                        MallSalesman salesman = mallSalesmanService.selectMallSalesmanByUserId(parentId);
                        if (salesman != null) {
                            memberUser.setSalesmanId(salesman.getId());
                        }else{
                            // 如果是非业务员,默认绑定
                            MallConfig bindingSalesman = mallConfigService.selectMallConfigByIdentifying("bindingSalesman");
                            if (bindingSalesman != null) {
                                memberUser.setSalesmanId(bindingSalesman.getConfigInt());
                            }
                        }
                    }
                }

                if(memberUserService.insertMallMemberUser(memberUser)>0){
                    memberUser.setSessionKey(session_key);
                    return ApiResult.ok().put("data", memberUser);
                }
            } else {
                System.out.println("旧用户");

                // 查询会员未下单天数（订单须付款）
                int noOrderDays = memberUserService.queryNoOrderDaysByUserId(memberUserDO.getId());
                // 更改业务员冻结时间（天）
                MallConfig freezeTime = mallConfigService.selectMallConfigByIdentifying("freezeTime");

                System.out.println("会员未下单天数=" + noOrderDays);
                System.out.println("更改业务员冻结时间=" + freezeTime.getConfigInt());

                if (salesmanId != null && noOrderDays >= freezeTime.getConfigInt()) {

                    System.out.println("有salesmanId");
                    System.out.println(map.get("salesmanId").toString());

                    // 邀请分配业务员
                    MallSalesman salesman = mallSalesmanService.selectMallSalesmanById(salesmanId.intValue());
                    if (salesman != null) {
                        memberUserDO.setSalesmanId(salesman.getId());
                    }
                    memberUserService.updateMallMemberUser(memberUserDO);
                }else if (parentId != null && noOrderDays >= freezeTime.getConfigInt()) {

                    System.out.println("有parentId");
                    System.out.println(map.get("parentId").toString());

                    // 邀请分配业务员
                    MallSalesman salesman = mallSalesmanService.selectMallSalesmanByUserId(parentId);
                    if (salesman != null) {
                        memberUserDO.setSalesmanId(salesman.getId());
                    }
                    memberUserService.updateMallMemberUser(memberUserDO);
                }

                if (memberUserDO.getSalesmanId() == null || StringUtils.isBlank(memberUserDO.getSalesmanId().toString())) {
                    System.out.println("旧用户无业务员默认绑定");
                    MallConfig bindingSalesman = mallConfigService.selectMallConfigByIdentifying("bindingSalesman");
                    if (bindingSalesman != null) {
                        memberUserDO.setSalesmanId(bindingSalesman.getConfigInt());
                        memberUserService.updateMallMemberUser(memberUserDO);
                    }
                }
                memberUserDO.setSessionKey(session_key);
            }
            return ApiResult.ok("登陆成功").put("data", memberUserDO);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("授权失败");
        }
    }

    /**
     * 小程序授权手机号登陆
     * @param params
     * @return
     */
    @PostMapping("/user/getUserPhone")
    @ResponseBody
    public ApiResult getXcxPhoneUserInfo(@RequestBody Map<String,Object> params) {
        if (!params.containsKey("sessionKey")||!params.containsKey("encryptedData")||!params.containsKey("iv")){
            return ApiResult.error("缺少参数");
        }
        try {
            String session_key = params.get("sessionKey").toString();

            Long parentId = MapUtils.getLong(params, "parentId");
            Long salesmanId = MapUtils.getLong(params, "salesmanId");

            //对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);

                List<MallSalesman> salesmanList = mallSalesmanService.selectMallSalesmanUserNumList();

                if (mu==null){
                    MallMemberUser memberUser = new MallMemberUser();
                    if (params.containsKey("memberName")){
                        memberUser.setName(jsons.get("nickName").toString());
                    }else{
                        memberUser.setName("XFML"+buildCode());
                    }

                    memberUser.setName(memberPhone);
                    memberUser.setPhone(memberPhone);
                    if (params.containsKey("openid")){
                        String openid = params.get("openid").toString();
                        memberUser.setOpenid(openid);
                    }
                    memberUser.setAvatar("https://xiaoniuimage.xnszz.com/IMG_110_110@FiqFJWBkG7DBZtn4SvxvDFKKtWJY.png");
                    memberUser.setToken(UUID.randomUUID().toString(true));
                    memberUser.setCreateAt(DateUtils.getTime());
                    memberUser.setUpdateAt(DateUtils.getTime());

                    if (salesmanId == null && parentId == null){
                        System.out.println("无parentId");

                        MallConfig bindingSalesman = mallConfigService.selectMallConfigByIdentifying("bindingSalesman");
                        if (bindingSalesman != null) {
                            memberUser.setSalesmanId(bindingSalesman.getConfigInt());
                        }
                    }else {
                        if (salesmanId != null){
                            MallSalesman salesman = mallSalesmanService.selectMallSalesmanById(salesmanId.intValue());
                            if (salesman != null) {
                                memberUser.setSalesmanId(salesman.getId());
                            }else{
                                // 如果是非业务员,默认绑定
                                MallConfig bindingSalesman = mallConfigService.selectMallConfigByIdentifying("bindingSalesman");
                                if (bindingSalesman != null) {
                                    memberUser.setSalesmanId(bindingSalesman.getConfigInt());
                                }
                            }
                        }else {
                            System.out.println("有parentId");
                            System.out.println("分享人parentId:" + MapUtils.getLong(params, "parentId"));

                            // 邀请分配业务员
                            memberUser.setIntroUser(Long.parseLong(params.get("parentId").toString()));
                            MallSalesman salesman = mallSalesmanService.selectMallSalesmanByUserId(MapUtils.getLong(params, "parentId"));
                            if (salesman != null) {
                                memberUser.setSalesmanId(salesman.getId());
                            }else{
                                // 如果是非业务员,默认绑定
                                MallConfig bindingSalesman = mallConfigService.selectMallConfigByIdentifying("bindingSalesman");
                                if (bindingSalesman != null) {
                                    memberUser.setSalesmanId(bindingSalesman.getConfigInt());
                                }
                            }
                        }
                    }

                    if(memberUserService.insertMallMemberUser(memberUser)>0){
                        return ApiResult.ok().put("data", memberUser);
                    }
                }else {
                    mu.setName(memberPhone);
                    memberUserService.updateMallMemberUser(mu);
                    return ApiResult.ok().put("data",mu);
                }
            }
            return ApiResult.error("信息解析异常");
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 获取用户手机号
     *
     * @return
     */
    @PostMapping("/phone/getXcxPhoneInfo")
    @ResponseBody
    public ApiResult getXcxPhoneInfo(@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();

            System.out.println("================获取用户手机号================");
            System.out.println("openid=" + openid);
            System.out.println("phoneCode=" + phoneCode);

            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();
            }

            System.out.println("result=" + result);
            System.out.println("errcode=" + result.getString("errcode"));
            System.out.println("phone_info=" + result.getJSONObject("phone_info"));
            System.out.println("phoneNumber=" + phoneNumber);

            if (StringUtils.isBlank(phoneNumber)){
                return ApiResult.error("获取手机号失败");
            }
            //查看表里有没有这个用户
            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";
        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=" + "wxd6fbe722d11e00f5" + "&" +
                    "secret=" + "84396e677785af5d3905784d36db8d73");
            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位随机数
     * @return
     */
    @SuppressWarnings("AlibabaRemoveCommentedCode")
    private String buildCode() {
        // 加上一些字母，就可以生成pc站的验证码了
        String sources = "0123456789";
        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();
    }

    /**
     * 获取个人信息
     */
    @SuppressWarnings("AlibabaRemoveCommentedCode")
    @GetMapping("/user/info")
    @ResponseBody
    public ApiResult userInfo(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")
        ){
            return ApiResult.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            MemberUserVO userVO = memberUserService.selectMemberVOUserById(Long.parseLong(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("name")||!params.containsKey("phone")
                ||!params.containsKey("default")
        ){
            return ApiResult.error("参数异常");
        }
        if (StringUtils.isBlank(params.get("address").toString()) && StringUtils.isBlank(params.get("meetId").toString())) {
            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("userId")
                ||!params.containsKey("name")||!params.containsKey("phone")
                ||!params.containsKey("default")
        ){
            return ApiResult.error("参数异常");
        }
        if (StringUtils.isBlank(params.get("address").toString()) && StringUtils.isBlank(params.get("meetId").toString())) {
            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("参数错误");
            }

            MallMemberUser memberUser = memberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));

            //查询购物车的正常商品
            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());
                BigDecimal price = new BigDecimal(0);
                // 商品规格
                List<GoodsProductVO> goodsProductVOList = mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(memberCart.getGoodsId());
                if (goodsProductVOList.size() > 0) {
                    for (GoodsProductVO productVO : goodsProductVOList) {
                        if (memberCart.getTotal().equals(productVO.getNum()) || memberCart.getTotal() > productVO.getNum()) {

                            if ("1".equals(memberUser.getVip())) {
                                price = productVO.getPriceVip();
                            } else {
                                price = productVO.getPrice();
                            }

                        }
                    }
                }

                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(goods.getSpec());
                goodsVO.setPrice(price.toString());
                goodsVO.setPriceN(price.toString());
                goodsVO.setStock(goods.getStock().toString());
                goodsVO.setNumSale(goods.getMonthlySales().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) {
            e.printStackTrace();
            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();

            MallMemberUser memberUser = memberUserService.selectMallMemberUserById(Long.parseLong(userId));


            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());

                    BigDecimal price = new BigDecimal(0);
                    // 商品规格
                    List<GoodsProductVO> goodsProductVOList = mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(memberCart.getGoodsId());
                    if (goodsProductVOList.size() > 0) {
                        for (GoodsProductVO productVO : goodsProductVOList) {
                            if (memberCart.getTotal().equals(productVO.getNum()) || memberCart.getTotal() > productVO.getNum()) {

                                if ("1".equals(memberUser.getVip())) {
                                    price = productVO.getPriceVip();
                                } else {
                                    price = productVO.getPrice();
                                }

                            }
                        }
                    }

                    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(goods.getSpec());
                    goodsVO.setPrice(price.toString());
                    goodsVO.setPriceN(price.toString());
                    goodsVO.setStock(goods.getStock().toString());
                    goodsVO.setNumSale(goods.getMonthlySales().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("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()));
            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);

            MallMemberCart mallMemberCart = memberCartService.selectMallMemberCartById(Long.parseLong(map.get("cartId").toString()));
            MallMemberUser memberUser = memberUserService.selectMallMemberUserById(Long.parseLong(map.get("userId").toString()));

            // 商品规格
            List<GoodsProductVO> goodsProductVOList = mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(mallMemberCart.getGoodsId());
            if (goodsProductVOList.size() > 0) {
                for (GoodsProductVO productVO : goodsProductVOList) {
                    if (mallMemberCart.getTotal().equals(productVO.getNum()) || mallMemberCart.getTotal() > productVO.getNum()) {

                        if ("1".equals(memberUser.getVip())) {
                            mallMemberCart.setPrice(productVO.getPriceVip());
                        } else {
                            mallMemberCart.setPrice(productVO.getPrice());
                        }

                    }
                }
            }
            return status > 0 ? ApiResult.ok().put("data", mallMemberCart) : 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("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.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("服务器网络异常");
        }
    }

    /**
     * 批量删除收藏
     */
    @PostMapping("/goods/deleteCollectByGoodsIds")
    @ResponseBody
    public ApiResult deleteCollectByGoodsIds(@RequestBody Map<String, Object> params){
        if (!params.containsKey("ids")
        ){
            return ApiResult.error("缺少ids");
        }
        if (!params.containsKey("userId") || MapUtils.getInteger(params,"userId") == null
        ){
            return ApiResult.error("缺少userId");
        }
        try{

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

    /**
     * 获取足迹
     * @param params
     * @return
     */
    @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("服务器网络异常");
        }
    }

    /**
     *  意见反馈
     * @param params
     * @return
     */
    @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("服务器网络异常");
//        }
//    }

    /**
     * 获取新人优惠券
     * @return
     */
    @GetMapping("/getNewPersonCoupons/{type}")
    public ApiResult getNewPersonCoupons(@PathVariable("type") Integer type){
        List<Map<String, Object>> coupons = couponService.selectMallCouponVOList(type);
        return ApiResult.ok().put("data",coupons);
    }

    /**
     * 领取新人优惠券
     * @param params
     * @return
     */
    @PostMapping("/drawNewPersonCoupons")
    public ApiResult drawNewPersonCoupons(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("couponId")){
            return ApiResult.error("缺少参数");
        }
        try{

            // 用户id
            Long userId = MapUtils.getLong(params, "userId");
            // 优惠券id
            Long couponId = MapUtils.getLong(params, "couponId");

            Map<String, Object> map = memberUserService.checkUserCoupon(userId,couponId.toString());
            if (map == null){
                MallCoupon coupon = couponService.selectMallCouponById(couponId);
                MallMemberCoupon memberCoupon = new MallMemberCoupon();
                memberCoupon.setUserId(userId);
                memberCoupon.setCouponId(couponId);
                memberCoupon.setName(coupon.getName());
                memberCoupon.setEnoughPrice(coupon.getEnoughPrice());
                memberCoupon.setPrice(coupon.getPrice());
                memberCoupon.setType(Integer.parseInt(coupon.getType()));
                memberCoupon.setCreateAt(DateUtils.getTime());
                memberCoupon.setIsUsed("0");
                memberUserService.insertUserCoupon(memberCoupon);
                return ApiResult.ok("领取成功");
            }else {
                return ApiResult.ok("已领取,不能重复领取");
            }

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

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

    /**
     * 获取可用优惠券优惠券列表
     * @param params
     * @return
     */
    @GetMapping("/getEnableCoupons")
    public ApiResult getEnableCoupons(@RequestParam Map<String, Object> params){
        if (!params.containsKey("userId")){
            return ApiResult.error("缺少参数");
        }
            if (!params.containsKey("price")){
            return ApiResult.error("缺少参数");
        }
        return ApiResult.ok().put("data",memberUserService.getEnableCoupons(params));
    }

    /**
     * 获取搜索记录
     * @param params
     * @return
     */
    @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<MallMemberSearchHistoryDto> coupons = searchHistoryService.selectMallMemberSearchHistoryList(mallMemberSearchHistory);
        return ApiResult.ok().put("data",coupons);
    }

    /**
     * 删除搜索记录
     * @param params
     * @return
     */
    @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("系统出错");
        }

    }

    /**
     * 批量删除搜索记录
     * @param params
     * @return
     */
    @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("系统出错");
        }

    }

    /**
     * 获取记录个数
     * @param params
     * @return
     */
    @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);
    }
}
