package com.ruoyi.app.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.app.utils.DateUtil;
import com.ruoyi.app.utils.PayPush;
import com.ruoyi.app.utils.RsaMima;
import com.ruoyi.app.utils.UUIDUtil;
import com.ruoyi.app.utils.trtc.TLSSigAPIv2;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUserDto;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.constants.MerchantAccountConstants;
import com.ruoyi.app.user.dto.MerchantLoginView;
import com.ruoyi.system.domain.vo.UserDTO;
import com.ruoyi.app.service.ImAccountService;
import com.ruoyi.system.mapper.InfoUserMapper;
import com.ruoyi.system.mapper.PosOrderMapper;
import com.ruoyi.system.mapper.PosStoreMapper;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.system.service.IInfoUserService;
import com.ruoyi.system.service.ISysDictDataService;

import com.ruoyi.system.service.IPosOrderService;
import com.ruoyi.system.service.IUserWalletService;
import com.ruoyi.system.service.IVipUserService;
import com.ruoyi.system.service.MerchantStoreAccessService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.AuthContext;
import com.ruoyi.system.utils.JwtUtil;
import com.ruoyi.system.utils.MobileSMS;
import com.ruoyi.app.user.dto.OAuthBindDto;
import com.ruoyi.app.user.dto.OAuthLoginDto;
import com.ruoyi.app.utils.oauth.OAuthVerifyService;
import com.ruoyi.system.mapper.InfoUserOauthMapper;

import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户信息Controller
 *
 * @author ruoyi
 * @date 2023-05-13
 */
@RestController
@RequestMapping("/infouser/user")
public class InfoUserController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(InfoUserController.class);

    @Autowired
    private IInfoUserService infoUserService;
    @Autowired
    private ImAccountService imAccountService;
    @Autowired
    private InfoUserMapper infoUserMapper;
    @Autowired
    private IVipUserService vipUserService;
    @Autowired
    private PosStoreMapper posStoreMapper;
    @Autowired
    private PosOrderMapper posOrderMapper;
    @Autowired
    private IUserWalletService userWalletService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IPosOrderService posOrderService;
    @Autowired
    private InfoUserOauthMapper infoUserOauthMapper;
    @Autowired
    private OAuthVerifyService oauthVerifyService;
    @Autowired
    private MerchantStoreAccessService merchantStoreAccessService;
    @Autowired
    private MerchantTokenSessionService merchantTokenSessionService;
    @Autowired
    private ISysDictDataService dictDataService;
    /** 三方登录首登临时凭证 Redis 前缀 */
    private static final String OAUTH_TEMP_PREFIX = "oauth:bind:";


    @Anonymous
    @PostMapping("/testBathPush")
    public AjaxResult testBathPush(@RequestBody List<String> cids){
        PayPush push=new PayPush();
        push.userPushBatch(cids,"测试","内容","{\"ddId\":991754272700492,\"state\":3,\"type\":-1}");
        return success();
    }
    @Anonymous
//    @Auth
    @GetMapping("/createUserWallets")
    public AjaxResult createUserWallets() {
        List<InfoUser> users = infoUserService.list();
        List<UserWallet> wallets = userWalletService.list();
        List<UserWallet> inserts = new ArrayList<>();
        for (InfoUser user : users) {
            boolean exist = wallets.stream().anyMatch(x -> x.getUserId().equals(user.getUserId()));
            if (!exist) {
                UserWallet insert = new UserWallet();
                insert.setUserId(user.getUserId());
                insert.setVersion(0);
                insert.setPointsWallet(0L);
                insert.setBalanceWallet(BigDecimal.ZERO);
                insert.setBlockedFunds(BigDecimal.ZERO);
                inserts.add(insert);
            }
        }
        if (!inserts.isEmpty()) {
            userWalletService.saveBatch(inserts);
        }
        return success();
    }

    /**
     * 获取rtc用户签名
     *
     * @return
     */
    @Anonymous
    @GetMapping("/getUserSig")
    public AjaxResult getUserSig(@RequestParam String userId) {
        TLSSigAPIv2 tlss = new TLSSigAPIv2();
        String obj = tlss.genUserSig(userId, 140000000);
        return success(MessageUtils.message("no.obtained.permission"), obj);
    }

    /**
     * 首页用户统计
     *
     * @return
     */
    @GetMapping("/gettongji")
    public AjaxResult gettongji(@RequestParam(defaultValue = "") String startDate, @RequestParam(defaultValue = "") String endDate) {
        JSONObject obj = new JSONObject();
        int user = infoUserMapper.getUserSum("0", startDate, endDate);
        int sjia = infoUserMapper.getUserSum("1", startDate, endDate);
        int qishou = infoUserMapper.getUserSum("2", startDate, endDate);
        int mend = posStoreMapper.getStoreSum(startDate, endDate);
        int orderCount = posOrderMapper.getOrderCountByDate(startDate, endDate);
        int orderSum = posOrderMapper.getOrderSumByDate(startDate, endDate);
        obj.put("userSum", user);
        obj.put("sjiaSum", sjia);
        obj.put("qisSum", qishou);
        obj.put("storeSum", mend);
        obj.put("orderCount", orderCount);
        obj.put("orderSum", orderSum);
        return success(obj);
    }

    /**
     * 首页曲线图
     *
     * @return
     */
    @GetMapping("/getOrderCount")
    public AjaxResult getOrderCount() {
        JSONObject obj = new JSONObject();
        List<PosOrder> orcount = posOrderMapper.getOrderCount();
        List<PosOrder> orsum = posOrderMapper.getOrderSum();
        int[] coun = new int[12];
        Double[] Sum = new Double[12];
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
        String formattedDate = currentDate.format(formatter);
        System.out.println("当前年份：" + formattedDate);
        for (int i = 0; i < 12; i++) {
            coun[i] = posOrderMapper.getMoorcoun(formattedDate + "-" + (i + 1) + "-1");
            Sum[i] = posOrderMapper.getMoorSun(formattedDate + "-" + (i + 1) + "-1");
        }
        obj.put("orcount", orcount.get(0).getAmount());
        obj.put("ordersum", orsum.get(0).getAmount());
        obj.put("counlist", coun);
        obj.put("sumlist", Sum);
        return success(obj);
    }

    /**
     * 判断会员日期
     *
     * @param userId
     * @return
     */
    @Anonymous
    @GetMapping("/getvip")
    public AjaxResult getvip(@RequestParam String userId) {
        DateUtil date = new DateUtil();
        QueryWrapper<VipUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        VipUser vipUser = vipUserService.getOne(queryWrapper);
        if (vipUser == null) {
            return success(MessageUtils.message("no.user.not.vip"), null);
        } else {
            boolean orn = date.isPastDate(vipUser.getYxtim());
            if (orn) {
                return success(MessageUtils.message("no.user.vip.expired"), null);
            } else {
                return success(MessageUtils.message("no.obtained.success"), vipUser.getYxtim());
            }
        }

    }

    /**
     * 开通 IM 账号：APP 在用户注册完成后（或首次沟通前）调用。
     * 通过登录 token 解析 userId，幂等创建/获取 IM 凭证并返回，供 APP 初始化 IM SDK。
     */
    @Anonymous
    @Auth
    @GetMapping("/imOpen")
    public AjaxResult openIm(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        String id;
        try {
            id = jwtUtil.getusid(token);
        } catch (Exception e) {
            return error("请先登录");
        }
        if (id == null || id.isEmpty()) {
            return error("请先登录");
        }
        return AjaxResult.success(imAccountService.openImAccount(Long.valueOf(id)));
    }

    /**
     * 删除用户
     */
    @Anonymous
    @GetMapping("/deleuser")
    public AjaxResult deleuser(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        Long userId = Long.valueOf(id);
        LambdaQueryWrapper<PosOrder> query = new LambdaQueryWrapper<>();
        query.in(PosOrder::getState, 0L, 1L, 2L)
                .and(role -> role.eq(PosOrder::getUserId, userId)
                        .or().eq(PosOrder::getQsId, userId)
                        .or().eq(PosOrder::getShId, userId));
        boolean exist = posOrderService.exists(query);
        if (exist) {
            throw new ServiceException("抱歉，您還有未完成的訂單，無法刪除帳號");
        }
        return toAjax(infoUserService.deleteInfoUserByUserId(userId));
    }

    /**
     * 骑手注册
     */
    @Anonymous
    @PostMapping("/addqishou")
    public AjaxResult addqishou(@RequestBody UserDTO userDTO) {
        String ncode = redisCache.getCacheObject(userDTO.getTelPhone().trim().replaceAll("\\+", ""));
        if (infoUserService.getinfouserName(userDTO.getUserName()) != null) {
            throw new ServiceException(MessageUtils.message("no.user.add") + userDTO.getUserName() + MessageUtils.message("no.user.login.exist"));
        }
        if ("".equals(userDTO.getPassword()) || userDTO.getPassword() == null) {
            throw new ServiceException(MessageUtils.message("no.user.password.not.null"));
        }
        if (ncode == null) {
            if (userDTO.getCode().equals("8888")) {
                return createQsUser(userDTO);
            } else {
                //验证码不正确
                throw new ServiceException(MessageUtils.message("no.user.jcaptcha.error"));
            }
        } else {
            if (ncode.equals(userDTO.getCode()) || userDTO.getCode().equals("8888")) {
                return createQsUser(userDTO);
            } else {
                throw new ServiceException(MessageUtils.message("no.user.jcaptcha.error"));
            }
        }
    }

    /**
     * 注册创建骑手用户
     *
     * @param userDTO
     * @return
     */
    public AjaxResult createQsUser(UserDTO userDTO) {
        InfoUser user = new InfoUser();
        UUIDUtil uuid = new UUIDUtil();
        user.setUserName(userDTO.getUserName());
        user.setPassword(userDTO.getPassword());
        user.setTelPhone(userDTO.getTelPhone());
        user.setUserType("2");
        user.setAuditStatus("0");
        user.setMycode(uuid.get8UUID());
        user.setStatus("0");
        user.setCid(userDTO.getCid());
        user.setCidType(userDTO.getCidType());
        user.setDeviceToken(userDTO.getDeviceToken());
        user.setVoIPToken(userDTO.getVoIPToken());
        int result = infoUserService.insertInfoUser(user);
        InfoUser infoUser = infoUserService.getinfouserName(userDTO.getUserName());
        createUserWallet(infoUser.getUserId());
        return toAjax(result);
    }

    /**
     * 商家注册
     */
    @Anonymous
    @PostMapping("/addshanghu")
    public AjaxResult addshanghu(@RequestBody UserDTO userDTO) {
        String ncode = redisCache.getCacheObject(userDTO.getTelPhone().trim().replaceAll("\\+", ""));
        if (infoUserService.getinfouserName(userDTO.getUserName()) != null) {
            throw new ServiceException(MessageUtils.message("no.user.add") + userDTO.getUserName() + MessageUtils.message("no.user.login.exist"));
        }
        if ("".equals(userDTO.getPassword()) || userDTO.getPassword() == null) {
            throw new ServiceException(MessageUtils.message("no.user.password.not.null"));
        }
        if (ncode == null) {
            if (userDTO.getCode().equals("8888")) {
                return createShUser(userDTO);
            } else {
                throw new ServiceException(MessageUtils.message("no.user.jcaptcha.error"));
            }
        } else {
            if (ncode.equals(userDTO.getCode()) || userDTO.getCode().equals("8888")) {
                return createShUser(userDTO);
            } else {
                throw new ServiceException(MessageUtils.message("no.user.jcaptcha.error"));
            }
        }

    }

    /**
     * 注册创建商户用户
     *
     * @param userDTO
     * @return
     */
    public AjaxResult createShUser(UserDTO userDTO) {
        InfoUser user = new InfoUser();
        UUIDUtil uuid = new UUIDUtil();
        user.setUserName(userDTO.getUserName());
        user.setPassword(userDTO.getPassword());
        user.setTelPhone(userDTO.getTelPhone());
        user.setUserType("1");
        user.setAuditStatus("0");
        user.setMycode(uuid.get8UUID());
        user.setStatus("0");
        user.setCid(userDTO.getCid());
        user.setCidType(userDTO.getCidType());
        user.setDeviceToken(userDTO.getDeviceToken());
        user.setVoIPToken(userDTO.getVoIPToken());
        int result = infoUserService.insertInfoUser(user);
        InfoUser infoUser = infoUserService.getinfouserName(userDTO.getUserName());
        createUserWallet(infoUser.getUserId());
        return toAjax(result);
    }

    /**
     * 商户登录
     *
     * @param userDTO
     * @return
     */
    @Anonymous
    @PostMapping("/shanglodeing")
    public AjaxResult shanglodeing(@RequestBody UserDTO userDTO) {
        JwtUtil tokn = new JwtUtil();
        RsaMima rsa = new RsaMima();
        try {
            QueryWrapper<InfoUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", userDTO.getUserName());
            queryWrapper.eq("del_flag", "0");
            queryWrapper.in("user_type", "1", "3", "4", "5");
            InfoUser user = infoUserService.getOne(queryWrapper);
            if (user == null) {
                throw new ServiceException(MessageUtils.message("no.user.not.exist"));
            }
            String wmima = rsa.decryptByPrivateKey(userDTO.getPassword());
            String nmima = rsa.decryptByPrivateKey(user.getPassword());
            if (wmima.equals(nmima)) {
                if (!MerchantAccountConstants.STATUS_ENABLED.equals(user.getStatus())) {
                    throw new ServiceException(MessageUtils.message("merchant.account.unavailable"));
                }
                if (MerchantAccountConstants.SUBACCOUNT_USER_TYPE.equals(user.getUserType())) {
                    merchantStoreAccessService.resolve(user.getUserId());
                }
                InfoUser info = new InfoUser();
                info.setUserId(user.getUserId());
                info.setLastLoginAt(new Date());
                if (userDTO.getCid() != null && !userDTO.getCid().isBlank()) {
                    info.setCid(userDTO.getCid());
                    info.setCidType(userDTO.getCidType());
                    info.setDeviceToken(userDTO.getDeviceToken());
                    info.setVoIPToken(userDTO.getVoIPToken());
                    user.setCid(userDTO.getCid());
                    user.setCidType(userDTO.getCidType());
                    user.setDeviceToken(userDTO.getDeviceToken());
                    user.setVoIPToken(userDTO.getVoIPToken());
                }
                infoUserService.updateInfoUser(info);
                user.setLastLoginAt(info.getLastLoginAt());
                // 根据客户端类型（APP端或PC端）选择对应的 token key
                String tokenKey = getTokenKeyByClientType();
                //app端
                if (tokenKey.equals(CacheConstants.SH_APP_TOKEN_KEY)) {
                    // 删除该用户同类型客户端的旧 token
                    redisCache.deleteKeys(tokenKey + user.getUserId() + ":" + "*");
                }

                // 补充登录用户信息
                LoginUserDto userDto = new LoginUserDto();
                userDto.setUserId(user.getUserId());
                userDto.setUserName(user.getUserName());
                fillLoginUserInfo(userDto);
                String token = JwtUtil.setToken(tokenKey, userDto);
                return success(MessageUtils.message("no.user.login.success"), merchantLoginView(user), token);
            } else {
                return error(MessageUtils.message("no.user.password.error"));
            }

        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            return error(MessageUtils.message("no.system.error"));
        }
    }

    /**
     * 骑手登录
     *
     * @param userDTO
     * @return
     */
    @Anonymous
    @PostMapping("/syslodeing")
    public AjaxResult syslodeing(@RequestBody UserDTO userDTO) {
        JwtUtil tokn = new JwtUtil();
        RsaMima rsa = new RsaMima();
        try {
            QueryWrapper<InfoUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", userDTO.getUserName());
            queryWrapper.eq("del_flag", "0");
            queryWrapper.eq("user_type", "2");
            InfoUser user = infoUserService.getOne(queryWrapper);
            if (user == null) {
                return error(MessageUtils.message("no.user.not.exist"));
            }
            String wmima = rsa.decryptByPrivateKey(userDTO.getPassword());
            String nmima = rsa.decryptByPrivateKey(user.getPassword());
            if (wmima.equals(nmima)) {
                InfoUser info = new InfoUser();
                info.setUserId(user.getUserId());
                info.setCid(userDTO.getCid());
                info.setCidType(userDTO.getCidType());
                info.setDeviceToken(userDTO.getDeviceToken());
                info.setVoIPToken(userDTO.getVoIPToken());
                info.setOffline("0");
                infoUserService.saveOrUpdate(info);
                if (!"".equals(userDTO.getCid())) {
                    user.setCid(userDTO.getCid());
                }
                ;
                //返回离线标识状态为在线
                user.setOffline("0");
                redisCache.deleteKeys(CacheConstants.QS_TOKEN_KEY + user.getUserId() + ":" + "*");

                // 补充登录用户信息
                LoginUserDto userDto = new LoginUserDto();
                userDto.setUserId(user.getUserId());
                userDto.setUserName(user.getUserName());
                fillLoginUserInfo(userDto);
                String token = JwtUtil.setToken(CacheConstants.QS_TOKEN_KEY, userDto);
                return success(MessageUtils.message("no.user.login.success"), user, token);
            } else {
                return error(MessageUtils.message("no.user.password.error"));
            }

        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            return error(MessageUtils.message("no.system.error"));
        }
    }

    /**
     * 填充登录用户信息（IP地址、登录地点、浏览器、操作系统、登录时间等）
     *
     * @param userDto 登录用户DTO
     * @return 填充后的登录用户DTO
     */
    private LoginUserDto fillLoginUserInfo(LoginUserDto userDto) {
        // 获取IP地址
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        userDto.setIpaddr(ip);
        // 获取登录地点
        userDto.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        // 获取浏览器和操作系统信息
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        userDto.setBrowser(userAgent.getBrowser().getName());
        userDto.setOs(userAgent.getOperatingSystem().getName());
        // 设置登录时间
        userDto.setLoginTime(System.currentTimeMillis());
        return userDto;
    }

    /**
     * 判断客户端类型（APP端还是PC端）
     * 通过 User-Agent 判断：包含 Mobile、Android、iPhone、iPad 等关键词则为 APP 端
     *
     * @return true 表示 APP 端，false 表示 PC 端
     */
    private boolean isAppClient() {
        String userAgent = ServletUtils.getRequest().getHeader("User-Agent");
        if (userAgent == null || userAgent.isEmpty()) {
            // 如果没有 User-Agent，默认认为是 PC 端
            return false;
        }
        String ua = userAgent.toLowerCase();
        // 判断是否为移动设备（APP端）
        return ua.contains("mobile") || ua.contains("android") || ua.contains("iphone")
                || ua.contains("ipad") || ua.contains("ipod") || ua.contains("windows phone");
    }

    /**
     * 根据客户端类型获取对应的 token key
     *
     * @return token key
     */
    private String getTokenKeyByClientType() {
        return isAppClient() ? CacheConstants.SH_APP_TOKEN_KEY : CacheConstants.SH_PC_TOKEN_KEY;
    }

    private MerchantLoginView merchantLoginView(InfoUser user) {
        MerchantLoginView view = new MerchantLoginView();
        view.setUserId(user.getUserId());
        view.setUserName(user.getUserName());
        view.setNickName(user.getNickName());
        view.setUserType(user.getUserType());
        view.setStoreId(user.getStoreId());
        view.setMerchantOwnerId(user.getMerchantOwnerId());
        view.setStatus(user.getStatus());
        view.setSubaccountStatus(user.getSubaccountStatus());
        view.setLastLoginAt(user.getLastLoginAt());
        return view;
    }

    /**
     * 商家端退出登录，仅撤销当前 JWT 对应的会话。
     */
    @Anonymous
    @Auth(session = true)
    @PostMapping("/merchantLogout")
    public AjaxResult merchantLogout(@RequestHeader String token) {
        merchantTokenSessionService.logoutCurrent(AuthContext.requireJti());
        return success();
    }


    private void createUserWallet(Long userId) {
        try {
            userWalletService.createUserWallet(userId);
        } catch (Exception e) {
            logger.error("用户钱包创建失败,userId:{}", userId, e);
            throw new ServiceException(MessageUtils.message("no.user.login.exist"));
        }

    }

    /**
     * 骑手切换离线状态(0:在线,1:离线)
     *
     * @param token
     * @return
     */
    @Anonymous
    @Auth
    @GetMapping("/qsSwitchOffline")
    public AjaxResult qsSwitchOffline(@RequestHeader String token, @RequestParam String offline) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        InfoUser user = infoUserService.getById(id);
        InfoUser qs = new InfoUser();
        qs.setUserId(user.getUserId());
        qs.setOffline(offline);
        infoUserService.saveOrUpdate(qs);
        return success();
    }

    /**
     * 获取手机短信
     *
     * @param phone
     * @return
     */
    @Anonymous
    @GetMapping("/getcode")
    public AjaxResult getcode(@RequestParam String phone) {
        // GET 查询参数中 "+" 会被解码成空格，此处还原：前导空格+数字 → +数字
        if (phone != null && phone.startsWith(" ") && phone.trim().matches("\\d+")) {
            phone = "+" + phone.trim();
        }
        MobileSMS sms = new MobileSMS();
//        System.out.println(phone.trim().replaceAll("\\+", ""));
        String toPhone = phone;

        String authcode = "1" + RandomStringUtils.randomNumeric(5);//生成随机数,我发现生成5位随机数时，如果开头为0，发送的短信只有4位，这里开头加个1，保证短信的正确性
        System.out.println("验证码：" + authcode);
        redisCache.setCacheObject(phone.trim().replaceAll("\\+", ""), authcode, 5, TimeUnit.MINUTES);//将验证码存入缓存
//        sms.getcode(phone, authcode);//发送短息
        sms.getTwCode(toPhone,authcode);
        return success(MessageUtils.message("no.sms.send.success"));
    }

    /**
     * 绑定手机号
     *
     * @param token
     * @param userDTO
     * @return
     */
    @Anonymous
    @Auth
    @PostMapping("/Bindingphone")
    public AjaxResult Bindingphone(@RequestHeader String token, @RequestBody UserDTO userDTO) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        String xcode = redisCache.getCacheObject(userDTO.getTelPhone().trim().replaceAll("\\+", ""));
        if (userDTO.getCode().equals(xcode)) {
            InfoUser user = infoUserService.getById(id);
            if (user == null) {
                return error(MessageUtils.message("no.user.not.exist"));
            } else {
                InfoUser infoUser = new InfoUser();
                infoUser.setUserId(user.getUserId());
                infoUser.setTelPhone(userDTO.getTelPhone());
                Boolean org = infoUserService.saveOrUpdate(infoUser);
                if (org) {
                    return success();
                } else {
                    return error();
                }
            }
        } else {
            return error(MessageUtils.message("no.user.jcaptcha.error"));
        }

    }

    /**
     * 用户修改密码
     *
     * @param token
     * @param userDTO
     * @return
     */
    @Anonymous
    @Auth
    @PostMapping("/setpassword")
    public AjaxResult setpassword(@RequestHeader String token, @RequestBody UserDTO userDTO) {
        JwtUtil jwtUtil = new JwtUtil();
        RsaMima rsa = new RsaMima();
        try {
            String id = jwtUtil.getusid(token);
            String wmima = rsa.decryptByPrivateKey(userDTO.getPassword());
            QueryWrapper<InfoUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", Long.valueOf(id));
            InfoUser user = infoUserService.getOne(queryWrapper);
            String nmima = rsa.decryptByPrivateKey(user.getPassword());
            if (wmima.equals(nmima)) {
                InfoUser infoUser = new InfoUser();
                infoUser.setUserId(user.getUserId());
                infoUser.setPassword(userDTO.getNewpassword());
                Boolean org = infoUserService.saveOrUpdate(infoUser);
                if (org) {
                    return success(MessageUtils.message("no.user.password.modify.success"));
                } else {
                    return error();
                }
            } else {
                return success(MessageUtils.message("no.user.password.old.error"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(MessageUtils.message("no.system.error"));
        }
    }

    /**
     * 修改用户信息
     *
     * @param token
     * @param infoUser
     * @return
     */
    @Anonymous
    @Auth
    @PostMapping("/setuser")
    public AjaxResult setuser(@RequestHeader String token, @RequestBody InfoUser infoUser) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        normalizeDeliveryType(infoUser);
        InfoUser user = new InfoUser();
        user.setUserId(Long.valueOf(id));
        user.setUserType(infoUser.getUserType());
        user.setCid(infoUser.getCid());
        user.setCidType(infoUser.getCidType());
        user.setDeviceToken(infoUser.getDeviceToken());
        user.setVoIPToken(infoUser.getVoIPToken());
        user.setNickName(infoUser.getNickName());
        user.setAvatar(infoUser.getAvatar());
        user.setEmail(infoUser.getEmail());
        user.setSex(infoUser.getSex());
        user.setStatus(infoUser.getStatus());
        user.setThiscode(infoUser.getThiscode());
        user.setAnnex(infoUser.getAnnex());
        user.setTelPhone(infoUser.getTelPhone());
        user.setDriversLicense(infoUser.getDriversLicense());
        user.setDrivingLicense(infoUser.getDrivingLicense());
        user.setVehiclePhotos(infoUser.getVehiclePhotos());
        user.setLicensePlate(infoUser.getLicensePlate());
        user.setVehicleType(infoUser.getVehicleType());
        user.setDeliveryType(infoUser.getDeliveryType());
        user.setRiderHeadPhoto(infoUser.getRiderHeadPhoto());
        user.setPreLaunchCity(infoUser.getPreLaunchCity());
        user.setBirthday(infoUser.getBirthday());
        user.setInsurancePhoto(infoUser.getInsurancePhoto());
        user.setPoliceCertificate(infoUser.getPoliceCertificate());
        user.setFullName(infoUser.getFullName());
        user.setIdNumber(infoUser.getIdNumber());
        user.setMerchantType(infoUser.getMerchantType());
        user.setBankAccount(infoUser.getBankAccount());
        user.setPassportPhoto(infoUser.getPassportPhoto());
        user.setBankPhoto(infoUser.getBankPhoto());
        user.setBankAccountName(infoUser.getBankAccountName());
        user.setBankName(infoUser.getBankName());
        user.setBankAccountNo(infoUser.getBankAccountNo());
        user.setMerchantIntroduction(infoUser.getMerchantIntroduction());
        user.setBusinessLicense(infoUser.getBusinessLicense());
        user.setDirectorsScreenshot(infoUser.getDirectorsScreenshot());
        user.setFoodPermit(infoUser.getFoodPermit());
        user.setUboStatement(infoUser.getUboStatement());
        user.setAddress(infoUser.getAddress());
        user.setLongitude(infoUser.getLongitude());
        user.setLatitude(infoUser.getLatitude());
        Boolean org = infoUserService.saveOrUpdate(user);
        if (org && Boolean.TRUE.equals(infoUser.getUpdateUserInfo())) {
            LambdaUpdateWrapper<InfoUser> auditUpdateWrapper = new LambdaUpdateWrapper<>();
            auditUpdateWrapper.eq(InfoUser::getUserId, Long.valueOf(id))
                    .eq(InfoUser::getAuditStatus, "2")
                    .set(InfoUser::getAuditStatus, "0")
                    .set(InfoUser::getAuditRejectReason, null);
            infoUserService.update(auditUpdateWrapper);
        }
        if (org) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 获取台湾银行列表（商家审核资料「银行名称」下拉的数据源，商家App共用）
     * 数据取自字典 taiwan_bank_list，运营可在平台后台字典管理中维护
     */
    @Anonymous
    @GetMapping("/bankList")
    public AjaxResult bankList() {
        SysDictData query = new SysDictData();
        query.setDictType("taiwan_bank_list");
        query.setStatus("0");
        return success(dictDataService.selectDictDataList(query));
    }


    /**
     * 获取用户信息详细信息
    */
    @Anonymous
    @Auth
    @GetMapping("/getuserinfo")
    public AjaxResult getuserinfo(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        QueryWrapper<InfoUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        wrapper.eq("del_flag", "0");
        wrapper.eq("status", 0);
        InfoUser user = infoUserService.getOne(wrapper);
        if (user == null) {
            return error(MessageUtils.message("no.user.not.exist"));
        } else {
            DateUtil date = new DateUtil();
            QueryWrapper<VipUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getUserId());
            VipUser vipUser = vipUserService.getOne(queryWrapper);
            if (vipUser == null) {
                user.setVip(null);
            } else {
                boolean orn = date.isPastDate(vipUser.getYxtim());
                if (orn) {
                    user.setVip(null);
                } else {
                    user.setVip(vipUser.getYxtim());
                }
            }
            LambdaQueryWrapper<UserWallet> walletQuery = new LambdaQueryWrapper<>();
            UserWallet userWallet = userWalletService.selectByUserId(user.getUserId());
            if (userWallet == null) {
                user.setPointsWallet(0L);
            } else {
                user.setPointsWallet(Long.valueOf(userWallet.getPointsWallet().toString()));
            }
            return success(user);
        }
    }

    /**
     * 校验商家是否已补充资料信息（商家App用）：data=true 已补充，false 未补充（App引导去资料补充页）
     * 判定口径：商家名称(nickName)已有值
     */
    @Anonymous
    @Auth
    @GetMapping("/checkMerchantProfile")
    public AjaxResult checkMerchantProfile(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        QueryWrapper<InfoUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        wrapper.eq("del_flag", "0");
        wrapper.eq("status", 0);
        InfoUser user = infoUserService.getOne(wrapper);
        if (user == null) {
            return error(MessageUtils.message("no.user.not.exist"));
        }
        // 商家名称(nickName)为空即视为未补充资料
        boolean completed = user.getNickName() != null && !user.getNickName().trim().isEmpty();
        return success(completed);
    }

    /**
     * 获取新的token
     *
     * @param token
     * @return
     */
    @Anonymous
    @Auth
    @GetMapping("/gettoken")
    public AjaxResult gettoken(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        QueryWrapper<InfoUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        wrapper.eq("status", 0);
        wrapper.eq("del_flag", "0");
        InfoUser user = infoUserService.getOne(wrapper);
        if (user == null) {
            return error(MessageUtils.message("no.user.stop"));
        } else {
            // 必须走写 Redis 会话的重载：无会话 token 会被 @Auth(session=true) 切面拒掉（修复普通用户 getidlist 报商家会话无效）
            LoginUserDto userDto = new LoginUserDto();
            userDto.setUserId(user.getUserId());
            userDto.setUserName(user.getUserName());
            fillLoginUserInfo(userDto);
            String wtoken = JwtUtil.setToken(CacheConstants.USER_TOKEN_KEY, userDto);
            return success(MessageUtils.message("no.user.token.success"), wtoken);
        }
    }


    /**
     * 用户登录或注册
     *
     * @param userDTO
     * @return
     */
    @Anonymous
    @PostMapping("/lodeing")
    public AjaxResult lodeing(@RequestBody UserDTO userDTO) {
        JwtUtil tokn = new JwtUtil();
        String xcode = redisCache.getCacheObject(userDTO.getPhone().trim().replaceAll("\\+", ""));
        if (xcode == null) {
            if (userDTO.getCode().equals("8888")) {
                InfoUser infoUser = infoUserService.getuser(userDTO.getPhone());
                if (infoUser == null) {
                    return createUser(userDTO);
                } else {
                    return userLoginUpdateInfo(userDTO, infoUser);
                }
            } else {
                return error(MessageUtils.message("no.user.jcaptcha.error"));
            }
        } else {
            if (xcode.equals(userDTO.getCode()) || userDTO.getCode().equals("8888")) {
                InfoUser infoUser = infoUserService.getuser(userDTO.getPhone());
                if (infoUser == null) {
                    return createUser(userDTO);
                } else {
                    return userLoginUpdateInfo(userDTO, infoUser);
                }
            } else {
                return error(MessageUtils.message("no.user.jcaptcha.error"));
            }
        }
    }

    /**
     * 用户注册创建用户
     *
     * @param userDTO
     * @return
     */
    public AjaxResult createUser(UserDTO userDTO) {
        UUIDUtil uuid = new UUIDUtil();
        InfoUser info = new InfoUser();
        info.setPhone(userDTO.getPhone());
        info.setNickName(userDTO.getPhone());
        info.setCid(userDTO.getCid());
        info.setCidType(userDTO.getCidType());
        info.setDeviceToken(userDTO.getDeviceToken());
        info.setVoIPToken(userDTO.getVoIPToken());
        info.setUserType("0");
        info.setMycode(uuid.get8UUID());
        infoUserService.saveOrUpdate(info);
        InfoUser inus = infoUserService.getuser(userDTO.getPhone());
        createUserWallet(inus.getUserId());
        redisCache.deleteKeys(CacheConstants.USER_TOKEN_KEY + inus.getUserId() + ":" + "*");
        // 补充登录用户信息
        LoginUserDto userDto = new LoginUserDto();
        userDto.setUserId(inus.getUserId());
        userDto.setUserName(inus.getPhone());
        fillLoginUserInfo(userDto);
        String token = JwtUtil.setToken(CacheConstants.USER_TOKEN_KEY, userDto);
        return success(MessageUtils.message("no.user.login.success"), inus, token);
    }

    /**
     * 用户登录更新用户信息
     * @param userDTO
     * @param infoUser
     * @return
     */
    public AjaxResult userLoginUpdateInfo(UserDTO userDTO, InfoUser infoUser) {
        DateUtil date = new DateUtil();
        QueryWrapper<InfoUser> query = new QueryWrapper<>();
        query.eq("user_id", infoUser.getUserId());
        query.eq("status", 0);
        query.eq("del_flag", "0");
        InfoUser user = infoUserService.getOne(query);
        if (user == null) {
            throw new ServiceException(MessageUtils.message("no.user.not.exist"));
        }
        user.setCid(userDTO.getCid());
        user.setCidType(userDTO.getCidType());
        user.setDeviceToken(userDTO.getDeviceToken());
        user.setVoIPToken(userDTO.getVoIPToken());
        infoUserService.saveOrUpdate(user);
        QueryWrapper<VipUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", infoUser.getUserId());
        VipUser vipUser = vipUserService.getOne(queryWrapper);
        if (vipUser == null) {
            user.setVip(null);
        } else {
            boolean orn = date.isPastDate(vipUser.getYxtim());
            if (orn) {
                user.setVip(null);
            } else {
                user.setVip(vipUser.getYxtim());
            }
        }
        redisCache.deleteKeys(CacheConstants.USER_TOKEN_KEY + user.getUserId() + ":" + "*");
        // 补充登录用户信息
        LoginUserDto userDto = new LoginUserDto();
        userDto.setUserId(user.getUserId());
        userDto.setUserName(user.getPhone());
        fillLoginUserInfo(userDto);
        String token = JwtUtil.setToken(CacheConstants.USER_TOKEN_KEY, userDto);
        return success(MessageUtils.message("no.user.login.success"), user, token);
    }

    // ==================== 三方登录（017-oauth-login）====================

    /**
     * 三方登录第一步：校验 provider 凭证 → 已绑定直接登录；未绑定返回 needPhone + tempKey。
     */
    @Anonymous
    @PostMapping("/oauthLogin")
    public AjaxResult oauthLogin(@RequestBody OAuthLoginDto dto) {
        if (dto == null || dto.getProvider() == null || dto.getProvider().isEmpty()) {
            return error(MessageUtils.message("no.oauth.provider.blank"));
        }
        log.info("[OAuth] oauthLogin provider={}", dto.getProvider());
        String providerUid = oauthVerifyService.verify(dto.getProvider(), dto.getCredential());

        // 查是否已绑定
        InfoUserOauth bind = infoUserOauthMapper.selectOne(
                new LambdaQueryWrapper<InfoUserOauth>()
                        .eq(InfoUserOauth::getProvider, dto.getProvider())
                        .eq(InfoUserOauth::getProviderUid, providerUid));
        if (bind != null) {
            // 已绑定：校验用户正常后直接登录
            log.info("[OAuth] 已绑定 provider={}, providerUid={}, userId={}", dto.getProvider(), providerUid, bind.getUserId());
            QueryWrapper<InfoUser> q = new QueryWrapper<>();
            q.eq("user_id", bind.getUserId()).eq("status", 0).eq("del_flag", "0");
            InfoUser u = infoUserService.getOne(q);
            if (u == null) {
                log.warn("[OAuth] 已绑定但账号已停用 userId={}", bind.getUserId());
                return error(MessageUtils.message("no.user.stop"));
            }
            u.setCid(dto.getCid());
            u.setCidType(dto.getCidType());
            u.setDeviceToken(dto.getDeviceToken());
            u.setVoIPToken(dto.getVoIPToken());
            infoUserService.saveOrUpdate(u);
            return issueOauthToken(u, dto.getProvider());
        }

        // 未绑定：缓存 {provider, providerUid}，返回 needPhone + tempKey
        log.info("[OAuth] 未绑定，返回 needPhone provider={}, providerUid={}", dto.getProvider(), providerUid);
        String tempKey = UUID.randomUUID().toString().replace("-", "");
        redisCache.setCacheObject(OAUTH_TEMP_PREFIX + tempKey,
                dto.getProvider() + "@" + providerUid, 5, TimeUnit.MINUTES);
        Map<String, Object> data = new HashMap<>();
        data.put("status", "needPhone");
        data.put("tempKey", tempKey);
        return AjaxResult.success(MessageUtils.message("no.oauth.needphone"), data);
    }

    /**
     * 三方登录第二步：手机号 + 短信验证 → 已注册关联 / 未注册新建 → 写绑定 → 签 token。
     */
    @Anonymous
    @PostMapping("/oauthBindPhone")
    public AjaxResult oauthBindPhone(@RequestBody OAuthBindDto dto) {
        if (dto == null || dto.getTempKey() == null || dto.getTempKey().isEmpty()) {
            log.warn("[OAuth] oauthBindPhone 缺 tempKey");
            return error(MessageUtils.message("no.oauth.tempkey.missing"));
        }
        String cached = redisCache.getCacheObject(OAUTH_TEMP_PREFIX + dto.getTempKey());
        if (cached == null) {
            log.warn("[OAuth] tempKey 已过期/不存在 tempKey={}", dto.getTempKey());
            return error(MessageUtils.message("no.oauth.tempkey.expired"));
        }
        int at = cached.indexOf('@');
        String provider = cached.substring(0, at);
        String providerUid = cached.substring(at + 1);
        log.info("[OAuth] 绑定流程 provider={}, providerUid={}", provider, providerUid);

        // 容错：若期间已被绑定，直接登录
        InfoUserOauth exist = infoUserOauthMapper.selectOne(
                new LambdaQueryWrapper<InfoUserOauth>()
                        .eq(InfoUserOauth::getProvider, provider)
                        .eq(InfoUserOauth::getProviderUid, providerUid));
        if (exist != null) {
            log.info("[OAuth] 绑定期间已被绑定，直接登录 userId={}", exist.getUserId());
            InfoUser u = infoUserService.getById(exist.getUserId());
            return issueOauthToken(u, provider);
        }

        // 验短信（复用 lodeing 逻辑：redis code 或万能码 8888）
        String phone = dto.getPhone();
        String xcode = redisCache.getCacheObject(phone.trim().replaceAll("\\+", ""));
        boolean codeOk = (xcode != null && xcode.equals(dto.getCode())) || "8888".equals(dto.getCode());
        if (!codeOk) {
            log.warn("[OAuth] 短信验证码错误 phone={}", maskPhone(phone));
            return error(MessageUtils.message("no.user.jcaptcha.error"));
        }

        // 查/建用户（手机号始终为主键）
        InfoUser user = infoUserService.getuser(phone);
        if (user != null && !"0".equals(user.getStatus())) {
            // 停用账号不允许绑定三方（与 lodeing 一致，防止绕过停用）
            log.warn("[OAuth] 账号已停用 phone={}", maskPhone(phone));
            return error(MessageUtils.message("no.user.stop"));
        }
        if (user == null) {
            // 新建：昵称=手机号（与 createUser 一致）
            InfoUser info = new InfoUser();
            info.setPhone(phone);
            info.setNickName(phone);
            info.setCid(dto.getCid());
            info.setCidType(dto.getCidType());
            info.setDeviceToken(dto.getDeviceToken());
            info.setVoIPToken(dto.getVoIPToken());
            info.setUserType("0");
            info.setMycode(new UUIDUtil().get8UUID());
            infoUserService.saveOrUpdate(info);
            user = infoUserService.getuser(phone);
            createUserWallet(user.getUserId());
            log.info("[OAuth] 新建账号 userId={}", user.getUserId());
        } else {
            user.setCid(dto.getCid());
            user.setCidType(dto.getCidType());
            user.setDeviceToken(dto.getDeviceToken());
            user.setVoIPToken(dto.getVoIPToken());
            infoUserService.saveOrUpdate(user);
            log.info("[OAuth] 关联已有账号 userId={}", user.getUserId());
        }

        // 写三方绑定
        InfoUserOauth bind = new InfoUserOauth();
        bind.setUserId(user.getUserId());
        bind.setProvider(provider);
        bind.setProviderUid(providerUid);
        bind.setCreateTime(new Date());
        infoUserOauthMapper.insert(bind);
        log.info("[OAuth] 写入绑定 provider={}, providerUid={}, userId={}", provider, providerUid, user.getUserId());

        redisCache.deleteObject(OAUTH_TEMP_PREFIX + dto.getTempKey());
        return issueOauthToken(user, provider);
    }

    /** 手机号脱敏：保留前 3 后 4，中间 ****（仅日志用）。 */
    private static String maskPhone(String phone) {
        if (phone == null || phone.length() < 8) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
    }

    /** 三方登录签发 token（claim provider=本次登录渠道），复用现有 JwtUtil + Redis 会话。 */
    private AjaxResult issueOauthToken(InfoUser user, String provider) {
        if (user == null) {
            return error(MessageUtils.message("no.user.not.exist"));
        }
        redisCache.deleteKeys(CacheConstants.USER_TOKEN_KEY + user.getUserId() + ":" + "*");
        LoginUserDto dto = new LoginUserDto();
        dto.setUserId(user.getUserId());
        dto.setUserName(user.getPhone());
        dto.setProvider(provider);
        fillLoginUserInfo(dto);
        String token = JwtUtil.setToken(CacheConstants.USER_TOKEN_KEY, dto);
        return success(MessageUtils.message("no.user.login.success"), user, token);
    }

    /**
     * 查询用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('infouser:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(InfoUser infoUser) {
        startPage();
        List<InfoUser> list = infoUserService.selectInfoUserList(infoUser);
        if (!list.isEmpty()) {
            List<Long> userIds = list.stream().map(InfoUser::getUserId).collect(Collectors.toList());
            List<UserWallet> wallets = userWalletService.list(new LambdaQueryWrapper<UserWallet>().in(UserWallet::getUserId, userIds).isNull(UserWallet::getStoreId));
            list.forEach(item -> {
                Optional<UserWallet> wallet = wallets.stream().filter(w -> w.getUserId().equals(item.getUserId())).findFirst();
                if (wallet.isPresent()) {
                    item.setPointsWallet(Long.valueOf(wallet.get().getPointsWallet().toString()));
                } else {
                    item.setPointsWallet(0L);
                }
            });
        }
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('infouser:user:export')")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoUser infoUser) {
        List<InfoUser> list = infoUserService.selectInfoUserList(infoUser);
        ExcelUtil<InfoUser> util = new ExcelUtil<InfoUser>(InfoUser.class);
        util.exportExcel(response, list, MessageUtils.message("no.export.excel.userinfo"));
    }

    /**
     * 获取用户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('infouser:user:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        InfoUser user = infoUserService.selectInfoUserByUserId(userId);
        DateUtil date = new DateUtil();
        QueryWrapper<VipUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getUserId());
        VipUser vipUser = vipUserService.getOne(queryWrapper);
        if (vipUser == null) {
            user.setVip(null);
        } else {
            boolean orn = date.isPastDate(vipUser.getYxtim());
            if (orn) {
                user.setVip(null);
            } else {
                user.setVip(vipUser.getYxtim());
            }
        }
        return success(user);
    }

    /**
     * 新增用户信息
     */
    @PreAuthorize("@ss.hasPermi('infouser:user:add')")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody InfoUser infoUser) {
        if (MerchantAccountConstants.SUBACCOUNT_USER_TYPE.equals(infoUser.getUserType())) {
            return error(MessageUtils.message("merchant.subaccount.platform.managed"));
        }
        if (!normalizeAuditRejectReason(infoUser)) {
            return error(MessageUtils.message("no.user.audit.reject.reason.required"));
        }
        normalizeDeliveryType(infoUser);
        if (infoUserService.getinfouserName(infoUser.getUserName()) != null) {
            return error(MessageUtils.message("no.user.add") + infoUser.getUserName() + MessageUtils.message("no.user.login.exist"));
        } else if (infoUserService.getinfoPhone(infoUser.getPhone()) != null) {
            return error(MessageUtils.message("no.user.add") + infoUser.getPhone() + MessageUtils.message("no.user.mobile.exist"));
        }
        UUIDUtil uuid = new UUIDUtil();
        infoUser.setMycode(uuid.get8UUID());
        infoUser.setStatus("0");
        System.out.println("加密：" + infoUser.getPassword());
        int result = infoUserService.insertInfoUser(infoUser);
        createUserWallet(infoUser.getUserId());
        return toAjax(result);
    }

    /**
     * 修改用户信息
     */
    @PreAuthorize("@ss.hasPermi('infouser:user:edit')")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InfoUser infoUser) {
        InfoUser existing = infoUser.getUserId() == null ? null
                : infoUserService.selectInfoUserByUserId(infoUser.getUserId());
        if (MerchantAccountConstants.SUBACCOUNT_USER_TYPE.equals(infoUser.getUserType())
                || (existing != null
                && MerchantAccountConstants.SUBACCOUNT_USER_TYPE.equals(existing.getUserType()))) {
            return error(MessageUtils.message("merchant.subaccount.platform.managed"));
        }
        if (!normalizeAuditRejectReason(infoUser)) {
            return error(MessageUtils.message("no.user.audit.reject.reason.required"));
        }
        normalizeDeliveryType(infoUser);
        return toAjax(infoUserService.updateInfoUser(infoUser));
    }

    private boolean normalizeAuditRejectReason(InfoUser infoUser) {
        if (!"2".equals(infoUser.getAuditStatus())) {
            infoUser.setAuditRejectReason(null);
            return true;
        }
        if (infoUser.getAuditRejectReason() == null) {
            return false;
        }
        String reason = infoUser.getAuditRejectReason().strip();
        if (reason.isEmpty()) {
            return false;
        }
        infoUser.setAuditRejectReason(reason);
        return true;
    }

    /** 骑手配送类型归一化；非法值返回国际化业务错误。 */
    private void normalizeDeliveryType(InfoUser infoUser) {
        try {
            infoUser.setDeliveryType(InfoUser.normalizeDeliveryTypes(infoUser.getDeliveryType()));
        } catch (IllegalArgumentException exception) {
            throw new ServiceException(MessageUtils.message("no.user.delivery.type.invalid"));
        }
    }

    /**
     * 删除用户信息
     */
    @PreAuthorize("@ss.hasPermi('infouser:user:remove')")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(infoUserService.deleteInfoUserByUserIds(userIds));
    }


}
