package org.dromara.zhishu.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.pop.sdk.common.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.zhishu.domain.bo.EncryptionDataBo;
import org.dromara.zhishu.domain.bo.UserRechargeBo;
import org.dromara.zhishu.domain.dto.request.UpdateTokenRequest;
import org.dromara.zhishu.domain.dto.response.GetWlnShopListResponse;
import org.dromara.zhishu.domain.vo.DecryptDataVo;
import org.dromara.zhishu.domain.vo.XyCategoryVo;
import org.dromara.zhishu.manager.TaskExecutorManager;
import org.dromara.zhishu.mapper.ShopMapper;
import org.dromara.zhishu.service.*;
import org.dromara.zhishu.service.impl.RunningTaskByShopServiceImpl;
import org.dromara.zhishu.service.impl.RunningTaskServiceImpl;
import org.dromara.zhishu.util.DateUtilsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.zhishu.domain.vo.ShopVo;
import org.dromara.zhishu.domain.bo.ShopBo;
import org.dromara.common.mybatis.core.page.TableDataInfo;

import org.dromara.zhishu.mapper.ShopDepotMapper;
import org.dromara.system.service.ISysConfigService;
import org.dromara.zhishu.util.InterfaceUtils;

/**
 * 店铺主表
 *
 * @author yxy
 * @date 2025-03-10
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zhishu/shop")
public class ShopController extends BaseController {

    private final IShopService shopService;
    private final ISysConfigService configService;
    private final IXyCategoryService xyCategoryService;
    private final RunningTaskServiceImpl runningTaskServiceImpl;
    private final TaskExecutorManager taskExecutorManager;
    private final SysUserMapper sysUserMapper;
    private final RunningTaskByShopServiceImpl runningTaskByShopServiceImpl;
    private final ShopMapper shopMapper;
    private final IUserRechargeService userRechargeService;


    private static final String TODAY_GOODS_CACHE_KEY = "todayGoods:";
    private static final long CACHE_EXPIRE_MINUTES = 5; // 缓存5分钟

    /**
     * 查询店铺主表列表
     */
    @GetMapping("/list")
    @SaIgnore
    public TableDataInfo<ShopVo> list(ShopBo bo, PageQuery pageQuery) {
        return shopService.queryPageList(bo, pageQuery);
    }

    @SaCheckPermission("zhishu:shop:list")
    @GetMapping("/inviteList")
    public TableDataInfo<ShopVo> inviteList(ShopBo bo, PageQuery pageQuery) {
        return shopService.queryPageListInvite(bo, pageQuery);
    }

    @GetMapping("/getList")
    public List<ShopVo> getList() {
        return shopService.queryList(new ShopBo());
    }

    @GetMapping("/getRunningShopList")
    @SaIgnore
    public List<Map> getRunningShopList(String taskType){
        List<Map> mapList = runningTaskServiceImpl.selectTaskGroupShop(taskType);
        Iterator<Map> iterator = mapList.iterator();
        while (iterator.hasNext()) {
            Map map = iterator.next();
            ShopVo shopVo = shopService.queryById(Long.parseLong(map.get("shop_id").toString()));

            if (shopVo == null) {
                iterator.remove(); // 安全删除
            } else {
                map.put("shopName", shopVo.getShopName());
            }
        }

        return mapList;
    }

    @GetMapping("/getJavaTaskPoolStatus")
    @SaIgnore
    public Map getJavaTaskPoolStatus() {
        String bIp = "119.45.237.193";
        String es1Ip = "36.212.12.247";
        String url = "/task/metrics";

        List<CompletableFuture<Map>> futures = Arrays.asList(
                CompletableFuture.supplyAsync(
                        () -> runningTaskServiceImpl.getJavaTaskPool(bIp, "10046", url),
                        taskExecutorManager.getExecutor()
                ).orTimeout(500, TimeUnit.SECONDS), // 设置5秒超时

                CompletableFuture.supplyAsync(
                        () -> runningTaskServiceImpl.getJavaTaskPool(bIp, "10045", url),
                        taskExecutorManager.getExecutor()
                ).orTimeout(500, TimeUnit.SECONDS),

                //新增节点
                CompletableFuture.supplyAsync(
                        () -> runningTaskServiceImpl.getJavaTaskPool(es1Ip, "10047", url),
                        taskExecutorManager.getExecutor()
                ).orTimeout(500, TimeUnit.SECONDS), // 设置5秒超时

                CompletableFuture.supplyAsync(
                        () -> runningTaskServiceImpl.getJavaTaskPool(es1Ip, "10048", url),
                        taskExecutorManager.getExecutor()
                ).orTimeout(500, TimeUnit.SECONDS), // 设置5秒超时

                CompletableFuture.supplyAsync(
                        () -> runningTaskServiceImpl.getJavaTaskPool(es1Ip, "10049", url),
                        taskExecutorManager.getExecutor()
                ).orTimeout(500, TimeUnit.SECONDS), // 设置5秒超时

                CompletableFuture.supplyAsync(
                        () -> runningTaskServiceImpl.getJavaTaskPool(es1Ip, "10050", url),
                        taskExecutorManager.getExecutor()
                ).orTimeout(500, TimeUnit.SECONDS)

        );

        // 处理结果，添加超时和异常处理
        List<Map> javaTaskPoolStatusList = new ArrayList<>();

        for (CompletableFuture<Map> future : futures) {
            try {
                Map result = future.get(6, TimeUnit.SECONDS); // 总体超时6秒
                javaTaskPoolStatusList.add(result);
            } catch (TimeoutException e) {
                // 记录超时日志
                javaTaskPoolStatusList.add(createTimeoutResponse());
            } catch (Exception e) {
                // 记录异常日志
                javaTaskPoolStatusList.add(createErrorResponse());
            }
        }

        // 获取任务池各通道数据
        List<Map> shopMd5MapList = runningTaskServiceImpl.selectTaskByGroupShopMd5();

        Map dataMap = new HashMap();
        dataMap.put("javaTaskPoolStatusList", javaTaskPoolStatusList);
        dataMap.put("shopMd5MapList", shopMd5MapList);
        return dataMap;
    }

    private Map createTimeoutResponse() {
        Map<String, Object> timeoutResponse = new HashMap<>();
        timeoutResponse.put("error", "请求超时");
        timeoutResponse.put("active", -2);
        timeoutResponse.put("submitted", -2);
        timeoutResponse.put("completed", -2);
        timeoutResponse.put("shopMd5", "请求超时");
        return timeoutResponse;
    }

    private Map createErrorResponse() {
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("error", "请求异常");
        errorResponse.put("active", -3);
        errorResponse.put("submitted", -3);
        errorResponse.put("completed", -3);
        errorResponse.put("shopMd5", "请求异常");
        return errorResponse;
    }



    /**
     * 导出店铺主表列表
     */
    @SaCheckPermission("zhishu:shop:export")
    @Log(title = "店铺主表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ShopBo bo, HttpServletResponse response) {
        List<ShopVo> list = shopService.queryList(bo);
        ExcelUtil.exportExcel(list, "店铺主表", ShopVo.class, response);
    }

    /**
     * 获取闲鱼类目列表
     */
    @GetMapping("/getXyCategoryList")
    public TableDataInfo getXyCategoryList() {
        List<XyCategoryVo> list = xyCategoryService.selectXyCategoryList();
        return TableDataInfo.build(list);
    }


    /**
     * 获取店铺主表详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("zhishu:shop:query")
    @GetMapping("/{id}")
    public R<ShopVo> getInfo(@NotNull(message = "主键不能为空")
                             @PathVariable Long id) {
        return R.ok(shopService.queryById(id));
    }

    @SaCheckPermission("zhishu:shop:query")
    @GetMapping("/type/{type}")
    public List<ShopVo> getShopList (@PathVariable String type) {
        Long userId = LoginHelper.getUserId();
        return shopService.queryByType(type, userId);
    }

    /**
     * 新增店铺主表
     */
    @SaCheckPermission("zhishu:shop:add")
    @Log(title = "店铺主表", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ShopBo bo) {
        Boolean mark = false;

//        bo.setShopExpirationTime(DateUtilsUtils.getNextMonths(Integer.parseInt(bo.getPayMonth())));
//
//        bo.setIsExpiration("1");

        mark = shopService.insertByBo(bo);

        return toAjax(mark);
    }

    /**
     * 修改店铺主表
     */
    @SaCheckPermission("zhishu:shop:edit")
    @Log(title = "店铺主表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ShopBo bo) {
        return toAjax(shopService.updateByBo(bo));
    }

    /**
     * 删除店铺主表
     *
     * @param ids 主键串
     */
    @SaCheckPermission("zhishu:shop:remove")
    @Log(title = "店铺主表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(shopService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 获取店铺主表详细信息
     *
     * @param id 主键
     */
    @SaIgnore
    @GetMapping("/getShopInfo")
    public ShopVo getShopInfo(@NotNull(message = "主键不能为空") Long id) {
        return shopService.queryById(id);
    }

    /**
     * 根据三方店铺Id获取店铺主表详细信息
     *
     * @param mailId 主键
     */
    @SaIgnore
    @GetMapping("/getShopInfoByMailId")
    public ShopVo getShopInfoByMailId(@NotNull(message = "主键不能为空") Long mailId,  Integer shopType) {
        Integer finalShopType = shopType == null ? 1 : shopType;
        return shopService.queryByMailId(mailId, finalShopType);

    }

    /**
     * 修改店铺订单更新时间
     *
     * @param shopId
     * @param startUpdatedAt
     * @return
     */
    @SaIgnore
    @PutMapping("/updateTime")
    public Boolean updateTime(@NotNull(message = "主键不能为空") Long shopId, @NotNull(message = "更新时间不能为空") Long startUpdatedAt) {
        return shopService.updateTime(shopId, startUpdatedAt);
    }

    /**
     * 修改店铺是否开启订单状态
     *
     * @param shopId
     * @param status
     * @return
     */
    @SaIgnore
    @PutMapping("/updateShopIsSynOrder")
    public R<Boolean> updateShopIsSynOrder(@NotNull(message = "主键不能为空") Long shopId, @NotNull(message = "店铺订单同步状态不能为空") int status) {
        return R.ok(shopService.updateShopIsSynOrder(shopId, status));
    }

    @SaIgnore
    @PutMapping("/updateToken")
    public Boolean updateToken(@RequestBody UpdateTokenRequest request) {
        return shopService.updateToken(request);
    }

    /**
     * 获取万里牛店铺列表
     *
     * @param shopId
     * @return
     */
    @SaIgnore
    @GetMapping("/getWlnShopList")
    public R<List<GetWlnShopListResponse>> getWlnShopList(@NotNull(message = "页码不能为空") @RequestParam("page") Integer page, @NotNull(message = "条数不能为空") @RequestParam("limit") Integer limit, @NotNull(message = "店铺Id不能为空") @RequestParam("shopId") Long shopId, String shopNick) {
        return R.ok(shopService.getWlnShopList(page, limit, shopId, shopNick));
    }

    /**
     * 万里牛店铺授权
     *
     * @param shopId
     * @param shopName
     * @param shopNick
     * @return
     */
    @SaIgnore
    @GetMapping("/authorizationWln")
    public R<Boolean> authorizationWln(@NotNull(message = "店铺Id不能为空") Long shopId, @NotNull(message = "万里牛店铺名称不能为空") String shopName, @NotNull(message = "万里牛系统ID不能为空") String shopNick) {
        return R.ok(shopService.authorizationWln(shopId, shopName, shopNick));
    }

    /**
     * 加密数据
     *
     * @param jsonString
     * @return
     */
    @PostMapping("/encryption")
    @SaIgnore
    public Map encryption(@RequestBody String jsonString) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        EncryptionDataBo bo = mapper.readValue(jsonString, EncryptionDataBo.class);
        // 手动处理shopId字段
        Map result = shopService.encryptionData(bo);
        return result;
    }

    /**
     * 解密数据
     *
     * @param data
     * @return
     */
    @GetMapping("/decryption")
    @SaIgnore
    public DecryptDataVo decryption(String data) {
//        System.out.println("data:" + data);
        DecryptDataVo decryptDataVo = shopService.decryptionData(data);
        return decryptDataVo;
    }

    /**
     * 获取解密后的URL列表
     * @param data 加密后的URL
     * @return 原始URL列表
     */
    @GetMapping("/getDecryptedUrlList")
    @SaIgnore
    public Object  getDecryptedUrlList(String data) {
        try {
            Object  decryptDataVoList = shopService.decryptDataVoList(data);
            return decryptDataVoList;
        } catch (Exception e) {
            throw new RuntimeException("解密URL列表失败", e);
        }
    }

    /**
     * 获取解密后的URL列表  带前缀SHXY
     * @param data 加密后的URL
     * @return 原始URL列表
     */
    @GetMapping("/getDecryptedUrlListPrefix")
    @SaIgnore
    public Object  getDecryptedUrlListPrefix(String data) {
        try {
            // 判断前四位是否为SHXY
            if (data == null || data.length() < 4) {
                throw new RuntimeException("数据格式错误：数据长度不足4位");
            }
            String prefix = data.substring(0, 4);
            if (!"SHXY".equals(prefix)) {
                throw new RuntimeException("失败：数据前缀不是SHXY");
            }
            // 截取掉前四位
            String actualData = data.substring(4);
            Object  decryptDataVoList = shopService.decryptDataVoList(actualData);
            return decryptDataVoList;
        } catch (Exception e) {
            throw new RuntimeException("解密URL列表失败", e);
        }
    }

    @GetMapping("/updateShopSkuSpec")
    public R<Void> updateShopSkuSpec(String shopId,String type){
        // 当前用户id
        Long userId = LoginHelper.getUserId();
        if(userId == 1){
            shopService.updateShopSkuSpec(shopId,"服务版本:"+type+",周期:1个月");
        }
        return R.ok();
    }

    /**
     * 获取店铺绑定的仓库
     */
//    @SaCheckPermission("zhishu:shop:bind")
    @GetMapping("/getShopDepot/{shopId}")
    public R<Object> getShopDepot(@NotNull(message = "店铺ID不能为空") @PathVariable Long shopId) {
        // 这里调用service层方法获取店铺绑定的仓库信息
        return R.ok(shopService.getShopDepotByShopId(shopId));
    }

    /**
     * 绑定仓库到店铺
     */
//    @SaCheckPermission("zhishu:shop:bind")
    @Log(title = "店铺绑定仓库", businessType = BusinessType.UPDATE)
    @PostMapping("/bindDepot")
    public R<Void> bindDepotToShop(@RequestBody Map<String, Object> request) {
        // 检查必要的参数是否存在
        if (request.get("shopId") == null) {
            return R.fail("shopId参数不能为空");
        }
        if (request.get("depotIds") == null) {  // 改为 depotIds
            return R.fail("depotIds参数不能为空");
        }

        try {
            Long shopId = Long.valueOf(request.get("shopId").toString());

            // 处理depotIds为数组的情况
            Object depotIdsObj = request.get("depotIds");  // 改为 depotIds
            List<Long> depotIds = new ArrayList<>();

            if (depotIdsObj instanceof Object[]) {
                // 处理Object数组
                Object[] depotIdArray = (Object[]) depotIdsObj;
                for (Object item : depotIdArray) {
                    if (item != null) {
                        depotIds.add(Long.valueOf(item.toString()));
                    }
                }
            } else if (depotIdsObj instanceof List) {
                // 处理List
                List<?> depotIdList = (List<?>) depotIdsObj;
                for (Object item : depotIdList) {
                    if (item != null) {
                        depotIds.add(Long.valueOf(item.toString()));
                    }
                }
            } else {
                return R.fail("depotIds参数格式错误，应为数组");  // 错误信息也更新
            }

            if (depotIds.isEmpty()) {
                return R.fail("请至少选择一个仓库进行绑定");
            }

            boolean result = shopService.bindDepotToShop(shopId, depotIds);
            return toAjax(result);
        } catch (NumberFormatException e) {
            return R.fail("参数格式错误，请提供有效的数字ID");
        } catch (Exception e) {
            log.error("绑定仓库失败", e);
            return R.fail("系统错误，绑定失败");
        }
    }

    /**
     *  手动开通选品中心按钮操作
     */

    @PostMapping("/dredgeCenterBook")
    @SaCheckPermission("zhishu:shop:centerBook")
    @Log(title = "选品中心开通", businessType = BusinessType.UPDATE)
    @SaIgnore
    public R<Object> dredgeCenterBook(
            @NotNull(message = "用户ID不能为空") @RequestParam Long userId,
            @NotNull(message = "类型不能为空") @RequestParam Integer type) {
        try {
            String title = type == 1 ? "页面展示会员" : "高级搜索会员";
            String unit = type == 1 ? "年" : "月";
            String price = type == 1 ? "198000" : "9800";
            String orederType = type == 1 ? "centerBookPage" : "centerBookSearch";
            Map<String, String> orderParams = new HashMap<>();
            orderParams.put("service_name", title);
            orderParams.put("price", price);
            orderParams.put("unit", unit);
            orderParams.put("length", String.valueOf(1));
            orderParams.put("type", orederType);
            orderParams.put("sort", "1");
            String orderUrl = configService.selectConfigByKey("order.url");
            String service = InterfaceUtils.postForm(orderUrl, "/api/createService", orderParams);
//            String service = InterfaceUtils.postForm("https://go.order.service.buzhiyushu.cn/", "/api/createService", params);
            if (service != null) {
                JSONObject jsonObject = JSONObject.parseObject(service);
                if (jsonObject != null && jsonObject.containsKey("data")) {
                    String serviceId = jsonObject.getString("data");
                    orderParams.put("serviceId", serviceId);
                }
            }
            // 新增新后台订单表插入
            Map<String, String> params1 = new HashMap<>();
            params1.put("orderType", "centerBookPage");
            params1.put("userId", String.valueOf(userId));
            params1.put("goodsId", orderParams.get("serviceId"));
            params1.put("count", "1");
            String orderId = null;
            String order = InterfaceUtils.postForm("https://go.order.service.buzhiyushu.cn/", "/api/orders/createOrder", params1);
            System.out.println("order:"+order);
            if (order != null) {
                JSONObject jsonObject = JSONObject.parseObject(order);
                if (jsonObject != null && jsonObject.containsKey("data")) {
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    // 再从data对象中获取orderId
                    orderId = dataObject.getString("orderId");
                    System.out.println("orderId:"+orderId);
                    params1.put("orderId", orderId);
                }
            }
            // 获取外部接口地址
            String goUrl = configService.selectConfigByKey("go.url");
            String path = "/user/updateMemberRecord";

            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("userId", userId);
            params.put("type", type);

            // 调用外部接口
            String result = InterfaceUtils.getInterfacePost(goUrl, path, params);
            System.out.println("result:" + result);
            if (result != null && !result.isEmpty()) {
                log.info("选品中心开通成功，用户ID: {}, 类型: {}, 返回结果: {}", userId, type, result);
                // 解析返回的JSON
                JSONObject json = JSON.parseObject(result);
                int code = json.getIntValue("code");
                String msg = json.getString("msg");
                if (Objects.equals(msg, "会员记录更新成功")) {
                    // 修改新后台新订单表
                    if (orderId != null){
                        Map map1 = new HashMap();
                        map1.put("orderId",orderId);
                        map1.put("orderInfo", "{\"remark\":\"管理员手动新增会员\"}");
                        map1.put("userId",String.valueOf(userId));
                        String interfaceGet = InterfaceUtils.postForm(orderUrl, "/api/orders/orderForPay", map1);
                        System.out.println("充值结果: "+interfaceGet);
                        Map orderSuccess = JsonUtils.parseObject(interfaceGet,Map.class);
                        Integer orderCode = (Integer) orderSuccess.get("code");
                        if (orderCode == null || code != 200) {
                            // 这里可以打印日志或抛异常
                            System.err.println("更新服务失败，返回结果：" + orderSuccess);
                            return R.fail("更新服务失败"+orderSuccess);
                        }

                    }
                }
                Object data = json.get("data");
                if (data instanceof JSONObject dataJson) {
                    // 获取 data 中的字段
                    String userId1 = dataJson.getString("user_id");
                    SysUser user = sysUserMapper.selectUserById(Long.valueOf(userId1));
                    if (user != null && user.getPhonenumber() != null){
                        dataJson.put("phone", user.getPhonenumber());
                    } else {
                        dataJson.put("phone", "");
                    }
                    data = dataJson;
                }

                // 根据 Go 返回的 code 自适应响应
                if (code == 200 || code == 201) {
                    return R.ok(msg, data);
                } else {
                    return R.fail(msg, data);
                }
            } else {
                log.error("选品中心开通失败，用户ID: {}, 类型: {}", userId, type);
                return R.fail("开通失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("选品中心开通异常，用户ID: {}, 类型: {}", userId, type, e);
            return R.fail("系统异常，开通失败");
        }
    }

    @GetMapping("/todayGoods")
    public Map<String, Object> selectTodayGoods() {

        List<String> shopId = shopMapper.getShopIdByCreateBy(LoginHelper.getUserId());
        return runningTaskByShopServiceImpl.selectTodayGoods(shopId);
    }

    @GetMapping("/todaySales")
    public Map<String, Object> selectTodaySales() {
        List<String> shopId = shopMapper.getShopIdByCreateBy(LoginHelper.getUserId());
        return runningTaskByShopServiceImpl.selectTodaySales(shopId);
    }

    @GetMapping("/limitedTimeFree")
    public R<Void> limitedTimeFree(String id,String priceStr){
        System.out.println(id);
        Long userId = LoginHelper.getUserId();
        ShopVo shopVo = shopService.queryById(Long.parseLong(id));
        SysUser user = sysUserMapper.queryUserByUserId(userId);
        BigDecimal price = new BigDecimal(priceStr).multiply(new BigDecimal(100));
        BigDecimal balanceOld = user.getBalance();
        if (balanceOld.compareTo(price) < 0){
            return R.fail("余额不足,请前往钱包进行用户充值");
        }
        BigDecimal balanceNew = balanceOld.subtract(price);
        user.setBalance(balanceNew);
        sysUserMapper.updateBalance(userId,user.getBalance().longValue());

        UserRechargeBo userRechargeBo = new UserRechargeBo();
        userRechargeBo.setCommission(BigDecimal.ZERO);
        userRechargeBo.setRechargPrice(price);
        userRechargeBo.setRechargType("6");
        userRechargeBo.setStatus("6");
        userRechargeBo.setUserId(userId);
        userRechargeBo.setCreateBy(userId);
        userRechargeBo.setUpdateBy(userId);
        userRechargeBo.setLogTxt("拼多多店铺："+shopVo.getShopName()+"试用版解除上架限制");
        userRechargeBo.setOriginalPrice(balanceOld);
        userRechargeBo.setUpdatePrice(balanceNew);
        userRechargeService.insertByBo(userRechargeBo);

        ShopBo shopBo = new ShopBo();
        shopBo.setId(Long.parseLong(id));
        shopBo.setDeregulation("2");
        shopService.updateByBo(shopBo);

        return R.ok("订购成功");
    }
}
