package com.tzy.controller.merchant;

import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.tzy.annotation.ApiLog;
import com.tzy.annotation.RequireRoles;
import com.tzy.app.domain.AppUserPoint;
import com.tzy.app.domain.TzyMerchantArchives;
import com.tzy.app.dto.SimpleMerchantInfo;
import com.tzy.app.dto.SimpleUserShipDTO;
import com.tzy.app.dto.TypeCountDTO;
import com.tzy.app.dto.group.GiftCardManage;
import com.tzy.common.config.QuerySql;
import com.tzy.common.config.handle.ApiVersion;
import com.tzy.common.constant.Constants;
import com.tzy.common.constant.MsgConstants;
import com.tzy.common.dto.InDto;
import com.tzy.common.dto.OutDTO;
import com.tzy.common.dto.UserInfo;
import com.tzy.common.dto.group.NonEmptyQuery;
import com.tzy.common.dto.invoice.SimpleOrderDTO;
import com.tzy.common.enums.BusinessType;
import com.tzy.common.exception.AppAssert;
import com.tzy.common.json.JSON;
import com.tzy.common.utils.*;
import com.tzy.common.utils.bean.DozerUtils;
import com.tzy.common.utils.qiniu.QiniuUtil;
import com.tzy.express.ExpressUtils;
import com.tzy.express.service.ExpressService;
import com.tzy.framework.util.RedisUtils;
import com.tzy.pojo.app.AppMerchantFans;
import com.tzy.pojo.app.SimpleUser;
import com.tzy.pojo.card.CardGroupInfo;
import com.tzy.pojo.item.EvaluationRecord;
import com.tzy.sportcard.api.bean.invoice.AppUserInvoiceRecord;
import com.tzy.sportcard.api.bean.param.ShippingQuery;
import com.tzy.sportcard.api.domain.AppUserInfoDto;
import com.tzy.sportcard.api.domain.MerchantInfo;
import com.tzy.sportcard.api.domain.SysCashoutOrderList;
import com.tzy.sportcard.api.domain.TzyMerchantCenter;
import com.tzy.sportcard.api.dto.*;
import com.tzy.sportcard.api.dto.merchant.CompositeRankDTO;
import com.tzy.sportcard.api.dto.merchant.MerchantRankDetailDTO;
import com.tzy.sportcard.api.dto.merchant.MerchantRankingsDTO;
import com.tzy.sportcard.api.dto.merchant.MerchantScoreDTO;
import com.tzy.sportcard.api.service.GroupApiService;
import com.tzy.sportcard.api.service.MerchantApiService;
import com.tzy.sportcard.api.service.MineApiService;
import com.tzy.sportcard.api.service.TzyMerchantAssessService;
import com.tzy.sportcard.group.domain.CardGroupOrderInfo;
import com.tzy.sportcard.group.service.ICardGroupOrderInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.teasoft.bee.osql.Condition;
import org.teasoft.bee.osql.OrderType;
import org.teasoft.bee.osql.PreparedSql;
import org.teasoft.bee.osql.SuidRich;
import org.teasoft.honey.osql.core.ConditionImpl;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by po'yi
 * @Classname AppUserControllerNew
 * @Description
 * @Date 2022/3/3 13:24
 */
@Api(value = "app商户接口")
@RestController
@RequestMapping("/api/{version}/merchant")
@Slf4j
public class MerchantControllerNew {
    @Autowired
    private MineApiService mineApiService;
    @Autowired
    private SuidRich suidRich;
    @Autowired
    private PreparedSql preparedSql;
    @Autowired
    private GroupApiService groupApiService;
    @Autowired
    private ICardGroupOrderInfoService cardGroupOrderInfoService;
    @Autowired
    private MerchantApiService merchantApiService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private TzyMerchantAssessService tzyMerchantAssessService;
    @Autowired
    private ExpressService expressService;

    @ApiLog(title = "拒绝累积发货的用户订单数量", businessType = BusinessType.SEARCH)
    @ResponseBody
    @RequestMapping(value = "/refuseWaitShipping", method = RequestMethod.POST)
    @ApiVersion(1.0)
    @ApiOperation("拒绝累积发货的用户订单数量")
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING, UserType.USER_ROLE_DELIVERY})
    public OutDTO refuseWaitShipping(@RequestBody InDto inDto) {
        UserInfo user = UserUtils.getSimpleUserInfo();
        AppAssert.notNull(user,MsgConstants.NEED_LOGIN);
        String sql = QuerySql.getQuerySql("com.tzy.app.dto.CardGoodsDTO.refuseWaitShipping");
        String s = preparedSql.selectFun(sql, new Object[]{user.getMerchantId()});
        return OutDTO.ok().put("refuseCount", Integer.valueOf(s));
    }


    @ResponseBody
    @PostMapping(value = "/history/mall/order")
    @ApiVersion(1)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING, UserType.USER_ROLE_DELIVERY})
    @ApiOperation("用户历史待发货累积拼豆订单)")
    public OutDTO historyMallOrderOfGroup(@RequestBody InDto inDto) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo(true);
        AppAssert.notNull(userInfo, MsgConstants.NEED_LOGIN);
        Integer userId = inDto.getIntegerParam("orderUserId");
        String keyword = inDto.getString("keyword");
        ShippingQuery query = new ShippingQuery().setMerchantId(userInfo.getMerchantId()).setUserId(userId)
                .setKeyword(keyword).setPageNo(inDto.getPageNo()).setPageSize(inDto.getPageSize());
        PageInfo<UserOrderDTO> orders = groupApiService.historyMallOrderOfGroup(query);
        return OutDTO.ok().put("page", orders);
    }


    @ApiLog(title = "用户维度的发货(包含关联拼豆订单)", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/merchantShippingUser")
    @ApiVersion(1)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING, UserType.USER_ROLE_DELIVERY})
    @ApiOperation("用户维度的发货(包含关联拼豆订单)")
    public OutDTO merchantShippingUserV2(@RequestBody InDto inDto) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo(true);
        if (userInfo == null || userInfo.getMerchantId() == null) {
            return OutDTO.error500("权限不足");
        }
        String ids = inDto.getString("ids");
        List<Long> groupIds = null;
        if (StringUtils.isNotEmpty(ids)) {
            groupIds = Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList());
        }
        // 1:未发货 2:已发货; 不传则全部
        String shippingStatus = inDto.getString("shippingStatus");
        Integer infoStatus = inDto.getIntegerParam("infoStatus");
        boolean isOver = infoStatus != null && infoStatus == 301;
        String keyword = inDto.getString("keyword");
        String selfPickupCode = inDto.getString("selfPickupCode");
        boolean sortByTeam = getMerchantDefaultSortValue(inDto.get("sortByTeam"), userInfo.getMerchantId());
        int offSet = (inDto.getPageNo() - 1) * inDto.getPageSize();
        ShippingQuery query = new ShippingQuery().setMerchantId(userInfo.getMerchantId()).setKeyword(keyword).setShippingStatus(shippingStatus).setGroupIds(groupIds)
                .setOverFlag(isOver).setOffset(offSet).setPageSize(inDto.getPageSize()).setSelfPickupCode(selfPickupCode).setSortByTeam(sortByTeam);
        List<UserWaitOrderDTO> userInfoList = groupApiService.getMerchantGroupUserV2(query);
        buildShippingUserDataV3(userInfoList,query);
        boolean isSendExc = StringUtils.isNotEmpty(ids) && groupApiService.findOrderIsShipOverNew(groupIds);
        log.info("商家发货,id:{},状态:{}", userInfo.getMerchantId(),isSendExc);
        userInfoList.forEach(user -> {
            UserWaitOrderLog userLog = new UserWaitOrderLog();
            BeanUtils.copyProperties(user,userLog);
            log.info("商家发货用户信息:{}", JSON.marshalIgnoreNull(userLog));
        });
        return OutDTO.ok().put("userShippingOrders", userInfoList).put("isSendExc", isSendExc).put("userInfo",userInfo).put("sortByTeam",sortByTeam)
                .put("limitPickUp", groupApiService.isLimitMerchantPickUp(userInfo.getMerchantId()));
    }

    private boolean getMerchantDefaultSortValue(Object sortByTeam, Integer merchantId) {
        if (sortByTeam != null) {
            redisUtils.hset("merchant_default_sort_value", merchantId.toString(), sortByTeam);
        } else {
            Object defaultSortValue = redisUtils.hget("merchant_default_sort_value", merchantId.toString());
            if (defaultSortValue != null) {
                sortByTeam = defaultSortValue;
            } else {
                sortByTeam = false;
            }
        }
        return (boolean) sortByTeam;
    }

    private void buildShippingUserDataV3(List<UserWaitOrderDTO> userInfoList, ShippingQuery param) {
        if (CollectionUtils.isEmpty(userInfoList)) {
            return;
        }
        List<Long> userIds = userInfoList.stream().map(u -> u.getId().longValue()).collect(Collectors.toList());
        List<Integer> addrIds = userInfoList.stream().map(UserWaitOrderDTO::getShippingAddressId).collect(Collectors.toList());
        ShippingQuery query = new ShippingQuery().setMerchantId(param.getMerchantId()).setUserIds(userIds).setAddrIds(addrIds)
                .setGroupIds(param.getGroupIds()).setOverFlag(param.isOverFlag()).setSelfPickupCode(param.getSelfPickupCode())
                .setShippingStatus(param.getShippingStatus());
        List<UserOrderDTO> orders = groupApiService.getUserShippingOrderV2(query);
        ShippingQuery numQuery = new ShippingQuery().setMerchantId(param.getMerchantId()).setUserIds(userIds);
        List<TypeCountDTO> userNums = groupApiService.getMallOrderNumOfOverGroup(numQuery);
        Map<String, Integer> numData = userNums.stream().collect(Collectors.toMap(TypeCountDTO::getType, TypeCountDTO::getNum));
        userInfoList.forEach(userOrder -> {
            buildShippingUserData(userOrder, orders, param.isSortByTeam());
            if (!CollectionUtils.isEmpty(userOrder.getOrders())) {
                Integer num = numData.get(userOrder.getId().toString());
                userOrder.setHistoryOrderNum(num == null ? 0 : num);
            }
        });
    }

    private void buildShippingUserData(UserWaitOrderDTO userOrder, List<UserOrderDTO> orderList, boolean sortByTeam) {
        List<UserOrderDTO> userOrders = orderList.stream().filter(o -> o.getUserId() == userOrder.getId().intValue()
                        && o.getShippingAddressId() == userOrder.getShippingAddressId().intValue())
                .sorted(Comparator.comparing(o -> o.getGroupInfoId() == null))
                .collect(Collectors.toList());
        if (userOrders.isEmpty()) {
            return;
        }
        if (StringUtils.isEmpty(userOrder.getAddress())) {
            UserOrderDTO orderDTO = userOrders.get(0);
            userOrder.setAddress(orderDTO.getAddress());
            userOrder.setPhone(orderDTO.getPhone());
            userOrder.setLinkname(orderDTO.getLinkname());
        }
        List<Integer> userOrderIds = userOrders.stream().map(UserOrderDTO::getId).collect(Collectors.toList());
        List<Carmichae> allCardGoods = groupApiService.selectGoodsByOrderIds(userOrderIds, 1);
        Map<String, UserOrderDTO> dataMap = new LinkedHashMap<>();
        Map<String, UserOrderDTO> mallOrders = new LinkedHashMap<>();
        Set<Integer> orderIds = new HashSet<>(userOrderIds);
        boolean refuseWait = false;
        userOrder.setSendExc(true);
        long shipEndTimeStamp=0;
        for (UserOrderDTO order : userOrders) {
            order.setSortByTeam(sortByTeam);
            boolean isMallOrder = order.getGroupInfoId() == null;
            if (!isMallOrder) {
                List<Carmichae> cardGoods = allCardGoods.stream().filter(c -> c.getUserOrderId() == order.getId().intValue()).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(cardGoods)) {
                    continue;
                }
                order.setCarmichaels(cardGoods);
            }
            boolean needShipment = isMallOrder && order.getServeStatus() != null && (order.getServeStatus() == 120 || order.getServeStatus() == 130);
            boolean isOrderRefuse = order.getRefuseStatus() != null && order.getRefuseStatus() == 1;
            if (!refuseWait && (isOrderRefuse || needShipment)) {
                // 显示红点
                refuseWait = true;
                userOrder.setRefuseWait(true);
            }
            if (!order.isSendExc()) {
                userOrder.setSendExc(false);
                userOrder.setRefuseStatus(0);
            }
            if (order.isHasPickUpCode()) {
                userOrder.setHasPickUpCode(true);
            }
            if (StringUtils.isEmpty(userOrder.getPickUpType()) && StringUtils.isNotEmpty(order.getPickUpType())) {
                userOrder.setPickUpType(order.getPickUpType());
            }
            if (StringUtils.isEmpty(userOrder.getCourierNum()) && StringUtils.isNotEmpty(order.getCourierNum())) {
                userOrder.setPickUpType(order.getPickUpType());
                userOrder.setCourierNum(order.getCourierNum());
                userOrder.setCurierCompany(order.getCurierCompany());
            }

            String name;
            if (isMallOrder) {
                if (order.getShipEndTimeStamp() > 0 && order.getShipEndTimeStamp() > shipEndTimeStamp) {
                    shipEndTimeStamp = order.getShipEndTimeStamp();
                }
                name = order.getName() + "-" + order.getSpecs();
                if (mallOrders.containsKey(name)) {
                    UserOrderDTO existTypeOrder = mallOrders.get(name);
                    existTypeOrder.setPurchaseCount(existTypeOrder.getPurchaseCount() + order.getPurchaseCount());
                    List<UserOrderDTO.SimpleOrder> list = existTypeOrder.getSimpleOrders();
                    list.add(new UserOrderDTO.SimpleOrder(order.getOrderNo(), order.getPurchaseCount()));
                    existTypeOrder.setSimpleOrders(list);
                } else {
                    List<UserOrderDTO.SimpleOrder> simpleOrders = new ArrayList<>();
                    simpleOrders.add(new UserOrderDTO.SimpleOrder(order.getOrderNo(), order.getPurchaseCount()));
                    order.setSimpleOrders(simpleOrders);
                    mallOrders.put(name, order);
                }
            } else {
                name = order.getName() + "-" + order.getCode();
                if (dataMap.containsKey(name)) {
                    UserOrderDTO existTypeOrder = dataMap.get(name);
                    List<Carmichae> list = existTypeOrder.getCarmichaels();
                    list.addAll(order.getCarmichaels());
                    existTypeOrder.setCarmichaels(list);
                } else {
                    dataMap.put(name, order);
                }
            }
        }
        userOrder.setShipEndTimeStamp(shipEndTimeStamp);
        userOrder.setUserOrderIds(orderIds);
        userOrder.setOrders(dataMap);
        userOrder.setMallOrders(mallOrders);
    }

    @ApiLog(title = "累积发货的用户订单信息(包含拼豆订单)", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/waitShippingUser")
    @ApiVersion(1)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING,UserType.USER_ROLE_DELIVERY})
    @ApiOperation("累积发货的用户订单信息(包含拼豆订单)")
    public OutDTO waitShippingUserV2(@RequestBody InDto inDto) {
        UserInfo user = UserUtils.getSimpleUserInfo(true);
        AppAssert.notNull(user, MsgConstants.NEED_LOGIN);
        int offSet = (inDto.getPageNo() - 1) * inDto.getPageSize();
        String keyword = inDto.getString("keyword");
        boolean payed = inDto.getBooleanParam("payed");
        boolean sortByTeam = getMerchantDefaultSortValue(inDto.get("sortByTeam"), user.getMerchantId());
        ShippingQuery query = new ShippingQuery().setMerchantId(user.getMerchantId()).setKeyword(keyword)
                .setPageSize(inDto.getPageSize()).setOffset(offSet).setSortByTeam(sortByTeam).setPayed(payed);
        List<UserWaitOrderDTO> userList = groupApiService.getWaitShippingUser(query);
        if(!CollectionUtils.isEmpty(userList)){
            List<Long> userIds = userList.stream().map(u -> u.getId().longValue()).collect(Collectors.toList());
            List<Integer> addrIds = userList.stream().map(UserWaitOrderDTO::getShippingAddressId).collect(Collectors.toList());
            ShippingQuery orderQuery = new ShippingQuery().setMerchantId(user.getMerchantId()).setUserIds(userIds).setAddrIds(addrIds).setPayed(payed);
            List<UserOrderDTO> orders = groupApiService.getUserWaitShippingOrder(orderQuery);
            userList.forEach(order -> buildShippingUserData(order, orders, query.isSortByTeam()));
        }
        return OutDTO.ok().put("waitShippingOrders", userList).put("userInfo",user).put("sortByTeam",sortByTeam);
    }


    @ApiLog(title = "精美卡片发货", businessType = BusinessType.SEARCH)
    @ResponseBody
    @RequestMapping(value = "/nonEmptySend", method = RequestMethod.POST)
    @ApiVersion(1.0)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING, UserType.USER_ROLE_DELIVERY})
    @ApiOperation("精美卡片发货")
    public OutDTO nonEmptySend(@RequestBody InDto inDto) {
        AppUserInfoDto userInfo =  mineApiService.checkUserNew(inDto);
        String userOrderIds = inDto.getString("userOrderIds");
        if (StringUtils.isEmpty(userOrderIds)) {
            return OutDTO.error500("订单为空!");
        }
        String[] orderIds = userOrderIds.split(",");
        String courierNum = inDto.getString("courierNum");
        String courierCompany = inDto.getString("curierCompany");
        //添加顺丰一键发货逻辑
        if(StringUtils.isNotEmpty(courierCompany) && "顺丰一键发货".equals(courierCompany) ){
            inDto.put("userInfo",userInfo);
            inDto.put("orderIds",userOrderIds);
            return merchantApiService.createSfOrder(inDto);
        }
        courierCompany = StringUtils.isEmpty(courierCompany) ? ExpressUtils.getCompanyName(courierNum) : courierCompany;//快递公司
        if (!ExpressUtils.checkExpressCode(courierNum)) {
            return OutDTO.error(10059, "快递单号不符合规范[" + courierNum + "]");
        }
        CardGroupOrderInfo orderInfoCondition = new CardGroupOrderInfo();
        orderInfoCondition.setCourierNum(courierNum);
        orderInfoCondition.setCurierCompany(courierCompany);
        CardGroupOrderInfo existOrder = cardGroupOrderInfoService.selectCardGroupOrderInfoById(Long.valueOf(orderIds[0]));
        orderInfoCondition.setColumnsearch(" and cgoi.user_id != " + existOrder.getUserId());
        List<CardGroupOrderInfo> existOrders = merchantApiService.selectByCourier(orderInfoCondition);
        if (!CollectionUtils.isEmpty(existOrders)) {
            return OutDTO.error(10050, "其他订单已经使用了该物流单号！")
                    .put("orderInfo", existOrders.get(0));
        }
        List<Long> orderIdList = Arrays.stream(orderIds).map(Long::new).collect(Collectors.toList());
        CardGroupOrderInfo orderInfo = new CardGroupOrderInfo();
        orderInfo.setPickUpType("2");
        orderInfo.setCourierNum(courierNum);
        orderInfo.setCurierCompany(courierCompany);
        orderInfo.setStatus(104L);
        cardGroupOrderInfoService.updateOrderCourierByOrderIds(orderInfo,orderIdList);
        List<TzyMerchantCenter> tzyMerchantCenterList = groupApiService.checkMerchantCenterByCourier(courierNum);
        // 查询订单是否违规、如果违规更新违规状态
        if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(tzyMerchantCenterList)){
            tzyMerchantCenterList.forEach(center ->{
                String waringType = center.getWaringType();
                if ("exquisite24".equals(waringType) && 1 == center.getStatus()) { // 风险
                    groupApiService.resetGroupWaringType(center.getId(), 3);
                } else if ("exquisite72".equals(waringType) && 2 == center.getStatus()) { // 违规
                    groupApiService.resetGroupWaringType(center.getId(), 4);
                }
            });
        }
        return OutDTO.ok();
    }

    @ApiLog(title = "商家添加订单备注", businessType = BusinessType.SEARCH)
    @ResponseBody
    @RequestMapping(value = "/orderRemark", method = RequestMethod.POST)
    @ApiVersion(1.0)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    @ApiOperation("商家添加订单备注")
    public OutDTO orderRemark(@RequestBody InDto inDto) {
        com.tzy.pojo.card.CardGroupOrderInfo order = new com.tzy.pojo.card.CardGroupOrderInfo();
        Object orderId = inDto.get("orderId");
        order.setId(Long.valueOf(orderId.toString()));
        order.setRemark(inDto.getString("remark"));
        order.setUpdateTime(DateUtils.getTimestampNow());
        suidRich.update(order);
        return OutDTO.ok();
    }

    /**
     * 获取商家app用户id
     *
     * @return
     */
    @ApiLog(title = "获取商家app用户信息", businessType = BusinessType.SEARCH, indto = "{{inDto}}")
    @ResponseBody
    @PostMapping(value = "/getMerAppUserId")
    public OutDTO getMerAppUserId(@RequestBody InDto inDto) {
        Integer merchantId = inDto.getIntegerParam("merchantId");
        if (merchantId == null) {
            return OutDTO.error500("商户id为空");
        }
        SimpleUser simpleUser = mineApiService.selectAppUserByMerchantId(merchantId);
        AppAssert.notNull(simpleUser, "商家用户不存在");
        return OutDTO.ok().put("merchantUserId", simpleUser.getId()).put("merchantAppUser", simpleUser);
    }

    /**
     * 商家隐藏评论
     *
     * @return
     */
    @ApiLog(title = "商家隐藏评论", businessType = BusinessType.SEARCH, indto = "{{inDto}}")
    @ResponseBody
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    @RequestMapping(value = "/deleteEvaluation", method = RequestMethod.POST)
    public OutDTO deleteEvaluation(@RequestBody InDto inDto) {
        mineApiService.checkUserNew(inDto);
        Object id = inDto.get("id");
        if(id==null){
            return OutDTO.error500("id为空");
        }
        EvaluationRecord evaluationRecord = new EvaluationRecord();
        evaluationRecord.setId(Integer.valueOf(id.toString()));
        evaluationRecord.setStatus(0);
        suidRich.update(evaluationRecord);
        return OutDTO.ok();
    }

    /**
     * 商家开票
     */
    @ApiLog(title = "商家开票",businessType = BusinessType.SEARCH,indto = "{{inDto}}")
    @ApiOperation("商家开票,参数:invoiceId")
    @ResponseBody
    @RequestMapping(value = "/openInvoice", method = RequestMethod.POST)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    public OutDTO openInvoice(@RequestBody InDto inDto) {
        mineApiService.checkUserNew(inDto);
        Integer invoiceId = (Integer) inDto.get("invoiceId");
        if (invoiceId == null) {
            return OutDTO.error500("invoiceId为空");
        }

        AppUserInvoiceRecord condition = new AppUserInvoiceRecord();
        condition.setId(invoiceId.longValue());
        condition.setStatus(1);
        suidRich.update(condition);
        return OutDTO.ok();
    }

    /**
     * 商家详情
     */
    @ApiLog(title = "商家详情",businessType = BusinessType.SEARCH,indto = "{{inDto}}")
    @ApiOperation("商家详情,参数:id")
    @ResponseBody
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    //@RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    public OutDTO merchantDetail(@RequestBody InDto inDto) throws Exception {
        if (inDto == null || inDto.get("id") == null) {
            return OutDTO.error500("参数为空");
        }
        //mineApiService.checkUserNew(inDto);
        Long id = Long.valueOf(inDto.getString("id")) ;
        TzyMerchantArchives merchantArchives = new TzyMerchantArchives();
        merchantArchives.setMerchantId(id);
        merchantArchives.setDelFlag(0);
        merchantArchives.setStatus(3);
        Condition condition=new ConditionImpl();
        condition.orderBy("id", OrderType.ASC);
        List<TzyMerchantArchives> archivesList = suidRich.select(merchantArchives,condition);
        TzyMerchantArchives merchantArchive=null;
        if(!CollectionUtils.isEmpty(archivesList)){
            List<TzyMerchantArchives> defaltList=archivesList.stream().filter(a ->a.getDefult()!=null&&a.getDefult()).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(defaltList)){
                merchantArchive=defaltList.get(0);
            }else {
                merchantArchive=archivesList.get(0);
            }
        }

        if (merchantArchive != null && StringUtils.isNotEmpty(merchantArchive.getPicList())) {
            merchantArchive.setPicList(AESUtil.encryptData(merchantArchive.getPicList(), Constants.AES_TOKEN_PASSWORD));
        }
        //boolean delFlg = Boolean.parseBoolean(inDto.getString("delFlg")); // 删除缓存标记
        MerchantScoreDTO merchantScoreDTO = tzyMerchantAssessService.getMerchantMemberInfoV3(id);
        return OutDTO.ok()
                .put("merchantArchives",merchantArchive)
                .put("merchantBond", merchantApiService.getMerchantBond(id))
                .put("merchantScore", merchantScoreDTO);
    }

    /**
     * 修改商家组团排序
     */
    @ApiLog(title = "修改商家排序",businessType = BusinessType.SEARCH,indto = "{{inDto}}")
    @ApiOperation("修改商家排序,参数:id,sortValue")
    @ResponseBody
    @RequestMapping(value = "/editMerchantSort", method = RequestMethod.POST)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    public OutDTO editMerchantSort(@RequestBody InDto inDto) {
        if (inDto==null||inDto.get("id") == null|| inDto.get("sortValue")==null) {
            return OutDTO.error500("参数为空");
        }

        CardGroupInfo cardGroupInfo = new CardGroupInfo();
        cardGroupInfo.setId(Long.valueOf(inDto.getString("id")));
        cardGroupInfo.setMerchantSort((Integer) inDto.get("sortValue"));
        suidRich.update(cardGroupInfo);
        return  OutDTO.ok();
    }

    /**
     * 商家拉黑用户
     *
     * @param inDto
     * @return
     */
    @ApiLog(title = "商家拉黑用户", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(1.0)
    @ApiOperation("商家拉黑用户")
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    @PostMapping("/pullBackUser")
    public OutDTO pullBackUser(@RequestBody InDto inDto) {
        if(inDto.get("userId")==null){
            return OutDTO.error500("参数为空");
        }
        AppUserInfoDto appUserInfoDto = mineApiService.checkUserNew(inDto);
        MerchantInfo merchantInfo = merchantApiService.getMerchantInfoByUsername(appUserInfoDto.getAccount());
        AppMerchantFans appMerchantFans = new AppMerchantFans();
        appMerchantFans.setUserId(Long.valueOf(inDto.getString("userId")));
        appMerchantFans.setMerchantId(merchantInfo.getId().longValue());
        appMerchantFans.setType(Constants.FANS_TYPE_MERCHANT_DISLIKE);
        if(inDto.get("status")==null||Constants.STATUS_OK.equals(inDto.getString("status"))){
            if(merchantApiService.checkUserHaveSoldOrder(merchantInfo.getId(),(Integer)inDto.get("userId"))){
                return OutDTO.error500("存在订单未完成，无法屏蔽!");
            }
            List<AppMerchantFans> existFans = suidRich.select(appMerchantFans);
            if(existFans.isEmpty()){
                appMerchantFans.setCreateTime(new Date());
                suidRich.insert(appMerchantFans);
            }
        }else{
            suidRich.delete(appMerchantFans);
        }
        redisUtils.del("user_dislike_merchant:"+inDto.getString("userId"));
        return OutDTO.ok();
    }


    /**
     * 商家拉黑用户
     *
     * @param inDto
     * @return
     */
    @ApiLog(title = "商家拉黑用户[限制支付]", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(2.0)
    @ApiOperation("商家拉黑用户-v2[限制支付]")
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    @PostMapping("/v2/pullBackUser")
    public OutDTO pullBackUserV2(@RequestBody InDto inDto) {
        if(inDto.get("userId")==null){
            return OutDTO.error500("参数为空");
        }
       return merchantApiService.pullBackUserV2(inDto);
    }

    /**
     * 获取商家黑名单用户
     *
     * @param inDto
     * @return
     */
    @ApiLog(title = "获取商家黑名单用户", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(1.0)
    @ApiOperation("获取商家黑名单用户")
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    @PostMapping("/getBackUser")
    public OutDTO getBackUser(@RequestBody InDto inDto) {
        AppUserInfoDto appUserInfoDto = mineApiService.checkUserNew(inDto);
        MerchantInfo merchantInfo = merchantApiService.getMerchantInfoByUsername(appUserInfoDto.getAccount());
        List<AppUserInfoDto> users=mineApiService.getBackUserByMerchant(merchantInfo.getId(),inDto.getPageNo(),
                inDto.getPageSize(),inDto.getString("keyword"));
        return OutDTO.ok().put("users",users);
    }

    /**
     * 获取商家黑名单用户
     *
     * @param inDto
     * @return
     */
    @ApiLog(title = "获取商家黑名单用户-v2", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(2.0)
    @ApiOperation("获取商家黑名单用户-v2")
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    @PostMapping("/v2/getBackUser")
    public OutDTO getBackUserV2(@RequestBody InDto inDto) {
       return merchantApiService.getBackUserV2(inDto);
    }

    @ApiLog(title = "热门商家V2", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/hot")
    @ApiOperation("热门商家")
    @ApiVersion(1.0)
    public OutDTO hotMerchantV2(@RequestBody InDto inDto) {
        if(inDto.getString("ids")==null){
            return OutDTO.error500("参数为空");
        }
        List<Integer> ids = Arrays.stream(inDto.getString("ids").split(",")).map(Integer::valueOf).collect(Collectors.toList());
        List<SimpleMerchantInfo> merchants=merchantApiService.getHotMerchants(ids,true);
        return OutDTO.ok().put("merchants",merchants);
    }


    @ApiLog(title = "根据条件(userId)查询商家id", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/id/user")
    @ApiOperation("根据条件(userId)查询商家id")
    public OutDTO getMerchantIdByUserId(@RequestBody InDto inDto) {
        Integer userId = (Integer) inDto.get("userId");
        if(userId ==null){
            return OutDTO.error500("参数为空");
        }
        Integer merchantId=merchantApiService.getMerchantIdByUserId(userId);
        return OutDTO.ok().put("merchantId",merchantId);
    }

    @ApiLog(title = "根据条件(userId)查询商家信息", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/info/user")
    @ApiOperation("根据条件(userId)查询商家id")
    public OutDTO getMerchantByUserId(@RequestBody InDto inDto) {
        Integer userId = (Integer) inDto.get("userId");
        if(userId ==null){
            return OutDTO.error500("参数为空");
        }
        SimpleMerchantInfo merchant=merchantApiService.getMerchantByUserId(userId);
        return OutDTO.ok().put("merchant",merchant);
    }

    @ApiLog(title = "根据type查询商家信息", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/type")
    @ApiOperation("根据type查询商家信息")
    public OutDTO getMerchantByHotType(@RequestBody InDto inDto) {
        String hotType = inDto.getString("hotType");
        List<SimpleMerchantInfo> merchants=merchantApiService.getMerchantByType(hotType);
        return OutDTO.ok().put("merchants",merchants);
    }

    @ApiLog(title = "店铺综合评分（新）", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/info/assessNew")
    @ApiOperation("店铺综合评分（新）")
    public OutDTO getMerchantMemberInfoNew(@RequestBody InDto inDto) {
        Integer merchantId = inDto.getIntegerParam("merchantId");
        if(merchantId ==null){
            return OutDTO.error500("merchantId为空");
        }
        MerchantScoreDTO merchantScoreDTO = tzyMerchantAssessService.getMerchantMemberInfoNew(merchantId.longValue());
        return OutDTO.ok().put("merchantScoreDTO",merchantScoreDTO);
    }

    @ApiLog(title = "店铺综合评分", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/info/assess/v3")
    @ApiOperation("店铺综合评分")
    public OutDTO getMerchantMemberInfoV3(@RequestBody InDto inDto) {
        if(inDto == null){
            return OutDTO.error500("参数为空");
        }
        if(inDto.getIntegerParam("merchantId") == null){
            return OutDTO.error500("merchantId为空");
        }
        Long merchantId = inDto.getIntegerParam("merchantId").longValue();
        MerchantScoreDTO merchantScoreDTO = tzyMerchantAssessService.getMerchantMemberInfoV3(merchantId);
        return OutDTO.ok().put("merchantScoreDTO",merchantScoreDTO);
    }

    @ApiLog(title = "热门商家", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/hotMerchant")
    @ApiOperation("热门商家")
    public OutDTO hotMerchantV3(@RequestBody InDto inDto) {
        Integer limit = inDto.getIntegerDefault("limit", 20);
        List<SimpleMerchantInfo> merchants = merchantApiService.getHotMerchantV3(limit);
        return OutDTO.ok().put("merchants", merchants);
    }

    @ApiLog(title = "热门新商家", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(1.0)
    @PostMapping(value = "/hotNew")
    @ApiOperation("热门新商家")
    public OutDTO hotNewMerchant(@RequestBody InDto inDto) {
        Integer limit = inDto.getIntegerDefault("limit", 20);
        List<SimpleMerchantInfo> merchants = merchantApiService.getHotNewMerchants(limit);
        return OutDTO.ok().put("merchants", merchants);
    }


    @ApiLog(title = "需要发货(已发货)的精美卡片用户", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/gift/card")
    @ApiVersion(2.3)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING, UserType.USER_ROLE_DELIVERY})
    @ApiOperation("需要发货(已发货)的精美卡片用户")
    public OutDTO getGiftCardUser(@RequestBody InDto inDto) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo();
        if(userInfo ==null||userInfo.getMerchantId()==null){
            return OutDTO.error500("权限不足");
        }
        NonEmptyQuery nonEmptyQuery = inDto.buildParam(new NonEmptyQuery());
        nonEmptyQuery.setMerchantId(userInfo.getMerchantId()).setPageSize(inDto.getPageSize()).setOffset(inDto.getOffset());
        List<SimpleUserShipDTO> userShips;
        if(nonEmptyQuery.isWaitApply()){
            userShips= cardGroupOrderInfoService.getWaitApplyUserCards(nonEmptyQuery);
        }else {
            if(nonEmptyQuery.isShippedFlag()){
                userShips= cardGroupOrderInfoService.getShippedCardByUser(nonEmptyQuery);
            }else {
                userShips= cardGroupOrderInfoService.getNonEmptyCardByUserV3(nonEmptyQuery);
            }
        }
        return OutDTO.ok().put("userShips",userShips);
    }

    @ApiLog(title = "商家名下精美卡片类型", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/card/select")
    @ApiVersion(2.3)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING, UserType.USER_ROLE_DELIVERY, UserType.USER_ROLE_PUBLICITY})
    @ApiOperation("商家名下精美卡片类型")
    public OutDTO merchantSelectCard(@RequestBody InDto inDto) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo();
        if(userInfo ==null||userInfo.getMerchantId()==null){
            return OutDTO.error500("权限不足");
        }
        List<GiftCardManage> giftCards = merchantApiService.selectGiftCard(userInfo.getMerchantId(), null);
        return OutDTO.ok().put("cards",giftCards);
    }


    @ApiLog(title = "商家申请发货", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/submit/apply")
    @ApiVersion(2.3)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING, UserType.USER_ROLE_DELIVERY})
    @ApiOperation("商家申请发货")
    public OutDTO submitApplyCard(@RequestBody InDto inDto) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo();
        if(userInfo ==null||userInfo.getMerchantId()==null){
            return OutDTO.error500("权限不足");
        }
        NonEmptyQuery nonEmptyQuery = inDto.buildParam(new NonEmptyQuery());
        nonEmptyQuery.setMerchantId(userInfo.getMerchantId()).setPageSize(100).setOffset(0);
        List<SimpleUserShipDTO> userShips= cardGroupOrderInfoService.getWaitApplyUserCards(nonEmptyQuery);
        userShips.parallelStream().forEach(us -> {
            try {
                AppUserPoint shipRecord = new AppUserPoint().setUserId(us.getId()).setType(Constants.POINT_TYPE_GIFT_CARD_PRE + us.getCardId())
                        .setMerchantId(userInfo.getMerchantId()).setRefId(us.getCardId());
                cardGroupOrderInfoService.shippingPayV3(shipRecord, BigDecimal.ZERO, us.getWaitShippedNum(), null, null);
            }catch (Exception e){
                log.info("申请失败,需重试:{}",us,e);
            }
        });
        return OutDTO.ok();
    }

    @ApiLog(title = "商家标签绑定列表", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(1.0)
    @PostMapping(value = "/getByTagIds")
    @ApiOperation("商家标签绑定列表")
    public OutDTO getByTagIds(@RequestBody InDto inDto) {
        String tagIds = inDto.getString("tagIds"); // 商家标签ID 多个逗号分隔
        if(Strings.isEmpty(tagIds)){
            return OutDTO.error500("tagIds为空");
        }
        List<TzyMerchantTagDTO> merchantTagList = merchantApiService.getMerchantByTagIds(tagIds.split(","));
        return OutDTO.ok().put("merchantTagList", merchantTagList);
    }

    @ApiLog(title = "商家标签top3", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(1.0)
    @PostMapping(value = "/getMerchantTagTop3")
    @ApiOperation("商家标签top3")
    public OutDTO getMerchantTagTop3(@RequestBody InDto inDto) {
        Integer merchantId = (Integer)inDto.get("merchantId"); // 商家ID
        if(merchantId == null){
            return OutDTO.error500("tagIds为空");
        }
        List<TzyMerchantTagDTO> merchantTagList = merchantApiService.getMerchantTagTop3(merchantId);
        return OutDTO.ok().put("merchantTagList", merchantTagList);
    }

    @ApiLog(title = "新增商家拼豆名称", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(1.0)
    //@PostMapping(value = "/edit/point/msg")
    @ApiOperation("修改/新增商家拼豆名称")
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    public OutDTO editMerPointMsg(@RequestBody InDto inDto) {
        UserInfo user = UserUtils.getSimpleUserInfo();
        if (user == null) {
            return OutDTO.error500("权限不足!");
        }
        String showMsg = inDto.getString("showMsg");
        if (StringUtils.isEmpty(showMsg)) {
            return OutDTO.error500("参数为空!");
        }
        if(!StringUtils.isValidChineseEnglishOnly(showMsg)){
            return OutDTO.error500("拼豆名称不能包含特殊字符!");
        }
        if (StringUtils.isNotEmpty(showMsg) && !QiniuUtil.checkText(showMsg)) {
            return OutDTO.error500("存在不合规的文字!");
        }
        merchantApiService.updatePointMsg(user.getMerchantId(), showMsg);
        return OutDTO.ok();
    }

    @ApiLog(title = "获取商家信息", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(1.0)
    @PostMapping(value = "/info")
    @ApiOperation("获取商家信息")
    public OutDTO getMerchant(@RequestBody InDto inDto) {
        UserInfo user = UserUtils.getSimpleUserInfo();
        if (user == null || Objects.isNull(user.getMerchantId())) {
            return OutDTO.error500("权限不足!");
        }
        MerchantInfo merchantInfo = merchantApiService.getMerchantInfo(user.getMerchantId());
        return OutDTO.ok()
                .put("merchant",  DozerUtils.map(merchantInfo,SimpleMerchantInfo.class))
                .put("shopAmount", merchantApiService.sumMerchantAmount(user.getMerchantId(), "shop"))
                .put("oneKeyAmount", merchantApiService.sumMerchantAmount(user.getMerchantId(), "oneKey"))
                .put("hasCourierCompany", expressService.checkMerCourierCompany(inDto));
    }

    @ApiLog(title = "批量修改商城订单累计", businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(2.0)
    @PostMapping(value = "/order/batch/waiting")
    @ApiOperation("批量修改商城订单累计")
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    public OutDTO updateOrderWaitShipping(@RequestBody InDto inDto) {
        UserInfo user = UserUtils.getSimpleUserInfo();
        if (user == null) {
            return OutDTO.error500("权限不足!");
        }
        int num = merchantApiService.updateOrderWaitShipping(user.getMerchantId());
        return OutDTO.ok().put("num",  num);
    }

    @ApiLog(title = "批量修改商城订单累计", businessType = BusinessType.SEARCH)
    @ApiVersion(2.0)
    @ResponseBody
    @PostMapping(value = "/search")
    public OutDTO searchMerchants(@RequestBody InDto inDto){
        String keyword = inDto.getString("keyword");
        List<SimpleMerchantInfo> merchants=merchantApiService.searchMerchants(keyword);
        return OutDTO.ok().put("merchants",merchants);
    }

    @ApiLog(title = "获取生态购申请开票金额",businessType = BusinessType.SEARCH,indto = "{{inDto}}")
    @ApiOperation("获取生态购申请开票金额")
    @ApiVersion(1.0)
    @ResponseBody
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    @RequestMapping(value = "/getEcologyInvoice", method = RequestMethod.POST)
    public OutDTO getEcologyInvoice(@RequestBody InDto inDto) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo(true);
        if (userInfo == null || userInfo.getMerchantId()==null) {
            return OutDTO.error500("权限不足!");
        }
        // 生态购开票总金额
        BigDecimal invoiceAmount = cardGroupOrderInfoService.getEcologyAmount(userInfo.getId());
        // 生态购开票订单
        PageInfo<SimpleOrderDTO> orderPage = cardGroupOrderInfoService.getEcologyOrder(inDto.getPageNo(), inDto.getPageSize(), userInfo.getId());
        return OutDTO.ok()
                .put("invoiceAmount", invoiceAmount)
                .put("orderPage", orderPage);
    }

    /**
     * 生态购开票
     */
    @ApiLog(title = "生态购开票",businessType = BusinessType.SEARCH,indto = "{{inDto}}")
    @ApiOperation("生态购开票")
    @ResponseBody
    @RequestMapping(value = "/openEcologyInvoice", method = RequestMethod.POST)
    @RequireRoles(value = {UserType.USER_ROLE_SHIPPING})
    public OutDTO openEcologyInvoice(@RequestBody InDto inDto) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo(true);
        if (userInfo == null || userInfo.getMerchantId()==null) {
            return OutDTO.error500("权限不足!");
        }
        if(inDto.get("orderList") == null){
            return OutDTO.error500("开票订单为空!");
        }
        if(inDto.get("totalAmount") == null){
            return OutDTO.error500("开票总金额为空!");
        }
        if(inDto.get("invoice") == null){
            return OutDTO.error500("发票信息为空!");
        }
        //List<SysCashoutOrderList> orderList = (List<SysCashoutOrderList>) inDto.get("orderList");
        Gson gson = new Gson();
        JsonElement jsonElement = JsonParser.parseString(gson.toJson(inDto.get("orderList")));
        List<SysCashoutOrderList> orderList = null;
        if (jsonElement.isJsonArray()) {
            JsonArray jsonArray = jsonElement.getAsJsonArray();

            // 将 JsonArray 转换为 List<SysCashoutOrderList>
            orderList = gson.fromJson(jsonArray, new TypeToken<List<SysCashoutOrderList>>(){}.getType());
        }
        BigDecimal totalAmount = new BigDecimal(inDto.get("totalAmount").toString());
        String invoice = inDto.get("invoice").toString();
        // 开票订单总数、总金额、开票信息
        merchantApiService.openEcologyInvoice(userInfo.getMerchantId(), orderList, totalAmount, invoice);
        return OutDTO.ok();
    }

    @ApiLog(title = "商家详情排行榜",businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping("/rankings")
    public OutDTO getMerchantRankings(@RequestBody MerchantInfo merchantInfo){
        if(merchantInfo.getId() == null){
            return OutDTO.error500("商家id为空");
        }
        MerchantRankingsDTO rankings = merchantApiService.getDetailRank(merchantInfo.getId());
        return OutDTO.ok().put("rankings", rankings);
    }

    @ApiLog(title = "热门商家", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/hot")
    @ApiOperation("热门商家")
    @ApiVersion(3.2)
    public OutDTO hotMerchantsV4() {
        UserInfo userInfo = UserUtils.getSimpleUserInfo(false);
        Long userId = null;
        if(userInfo != null){
            userId = userInfo.getId().longValue();
        }
        List<MerchantRankDetailDTO> hotMerchants = merchantApiService.getHotMerchantV4(userId);
        return OutDTO.ok().put("hotMerchants", hotMerchants);
    }

    @ApiLog(title = "热门新商家", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/hotNew")
    @ApiOperation("热门新商家")
    @ApiVersion(3.2)
    public OutDTO hotNewMerchantsV4() {
        UserInfo userInfo = UserUtils.getSimpleUserInfo(false);
        Long userId = null;
        if(userInfo != null){
            userId = userInfo.getId().longValue();
        }
        List<MerchantRankDetailDTO> newHotMerchants = merchantApiService.getHotNewMerchantsV4(userId);
        return OutDTO.ok().put("newHotMerchants", newHotMerchants);
    }

    @ApiLog(title = "人气榜", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/popular")
    @ApiOperation("人气榜")
    @ApiVersion(3.0)
    public OutDTO getPopularMerchantV4(@RequestBody CompositeRankDTO compositeRankDTO) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo(false);
        Long userId = null;
        if(userInfo != null){
            userId = userInfo.getId().longValue();
        }
        if(compositeRankDTO == null || compositeRankDTO.getRuleId() == null){
            return OutDTO.error500("ruleId为空!");
        }
        List<MerchantRankDetailDTO> popularMerchants = merchantApiService.getPopularMerchantsV4(userId, compositeRankDTO.getRuleId());
        return OutDTO.ok().put("popularMerchants", popularMerchants);
    }

    @ApiLog(title = "人气榜", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/popular")
    @ApiOperation("人气榜")
    @ApiVersion(3.1)
    public OutDTO getPopularMerchantV5(@RequestBody CompositeRankDTO compositeRankDTO) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo(false);
        Long userId = null;
        if(userInfo != null){
            userId = userInfo.getId().longValue();
        }
        if(compositeRankDTO == null || compositeRankDTO.getRuleId() == null){
            return OutDTO.error500("ruleId为空!");
        }
        List<MerchantRankDetailDTO> popularMerchants = merchantApiService.getPopularMerchantsV5(userId, compositeRankDTO.getRuleId());
        return OutDTO.ok().put("popularMerchants", popularMerchants);
    }

    @ApiLog(title = "人气榜", businessType = BusinessType.SEARCH)
    @ResponseBody
    @PostMapping(value = "/popular")
    @ApiOperation("人气榜")
    @ApiVersion(3.2)
    public OutDTO getPopularMerchantV6(@RequestBody CompositeRankDTO compositeRankDTO) {
        UserInfo userInfo = UserUtils.getSimpleUserInfo(false);
        Long userId = null;
        if(userInfo != null){
            userId = userInfo.getId().longValue();
        }
        if(compositeRankDTO == null || compositeRankDTO.getRuleId() == null){
            return OutDTO.error500("ruleId为空!");
        }
        List<MerchantRankDetailDTO> popularMerchants = merchantApiService.getPopularMerchantsV6(userId, compositeRankDTO.getRuleId());
        return OutDTO.ok().put("popularMerchants", popularMerchants);
    }

    @ApiLog(title = "商家详情排行榜",businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(3.1)
    @PostMapping("/rankings")
    public OutDTO getMerchantRankingsV5(@RequestBody MerchantInfo merchantInfo){
        if(merchantInfo.getId() == null){
            return OutDTO.error500("商家id为空");
        }
        MerchantRankingsDTO rankings = merchantApiService.getDetailRankV5(merchantInfo.getId());
        return OutDTO.ok().put("rankings", rankings);
    }

    @ApiLog(title = "商家详情排行榜",businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(3.2)
    @PostMapping("/rankings")
    public OutDTO getMerchantRankingsV6(@RequestBody MerchantInfo merchantInfo){
        if(merchantInfo.getId() == null){
            return OutDTO.error500("商家id为空");
        }
        MerchantRankingsDTO rankings = merchantApiService.getDetailRankV6(merchantInfo.getId());
        return OutDTO.ok().put("rankings", rankings);
    }

    @ApiLog(title = "商家中心统计",businessType = BusinessType.SEARCH)
    @ResponseBody
    @ApiVersion(1.0)
    @PostMapping("/center/count")
    public OutDTO getMerchantCenterCount(){
        UserInfo userInfo = UserUtils.getSimpleUserInfo(true);
        Integer merchantId = null;
        if (userInfo != null && userInfo.getMerchantId() != null) {
            merchantId = userInfo.getMerchantId();
        }
        MerchantCenterCountDTO count = merchantApiService.getMerchantCenterCount(merchantId);
        return OutDTO.ok().put("count", count);
    }
}
