package com.cyksj.web.controller.manage.shop;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.ZfbShopOrderDayLimitMapper;
import com.cyksj.model.entity.Channel;
import com.cyksj.model.entity.ShopConfig;
import com.cyksj.model.entity.ZfbShopOrderDayLimit;
import com.cyksj.model.request.ChannelPayReq;
import com.cyksj.service.mange.channel.ChannelService;
import com.cyksj.service.mange.shop.ShopConfigService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * @author chan
 * @date 2022/12/13 4:53 PM
 */
@RestController
@RequestMapping("/manage/shop")
@RequiredArgsConstructor
@Slf4j
public class ShopConfigController {

    private final BeanSearcher beanSearcher;

    private final ShopConfigService shopConfigService;

    private final HttpServletRequest request;

    private final ChannelService channelService;

    private final ZfbShopOrderDayLimitMapper zfbShopOrderDayLimitMapper;

    @GetMapping
    public Result<SearchResult<ShopConfig>> get() {
	    SearchResult<ShopConfig> searchResult = beanSearcher.search(ShopConfig.class, MapUtils.flatBuilder(request.getParameterMap()).build());
	    searchResult.getDataList().forEach((shopConfig) -> {
		    shopConfig.setChannelCount(channelService.count(Wrappers.lambdaQuery(Channel.class).eq(Channel::getWxShopId, shopConfig.getAppId()).or().eq(Channel::getZfbShopId, shopConfig.getAppId())));

		    Optional.ofNullable(zfbShopOrderDayLimitMapper.selectOne(Wrappers.lambdaQuery(ZfbShopOrderDayLimit.class)
				    .eq(ZfbShopOrderDayLimit::getAppId, shopConfig.getAppId())
				    .last("limit 1"))).ifPresent(limit -> {
			    shopConfig.setDayLimitOrders(limit.getDayLimitOrders());
			    shopConfig.setDayLimitStatus(limit.getStatus());
		    });
	    });
	    return GatewayResponse.SUCCESS.newBuilder().toResult(searchResult);
    }

    @PostMapping
    public Result<String> post(@RequestBody ShopConfig shopConfig){
        shopConfigService.save(shopConfig);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    @PutMapping
    public Result<String> put(@RequestBody ShopConfig shopConfig){
        shopConfigService.updateById(shopConfig);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    @DeleteMapping("/{id}")
    public Result<String> del(@PathVariable Long id){
        shopConfigService.removeById(id);
       return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 更换渠道支付方式
     */
    @PutMapping("/update/channel/pay")
    @SaCheckPermission("merchant:updateChannelShop")
    public Result<String> updateChannelPay(@RequestBody ChannelPayReq req) {
        String wxShopId = req.getWxShopId();
        String zfbShopId = req.getZfbShopId();
        if (StrUtil.isAllEmpty(wxShopId, zfbShopId)) {
            return GatewayResponse.SUCCESS.newBuilder().toResult();
        }
        channelService.update(Wrappers.lambdaUpdate(Channel.class)
                .eq(StrUtil.isNotBlank(wxShopId), Channel::getWxShopId, wxShopId)
                .eq(StrUtil.isNotBlank(zfbShopId), Channel::getZfbShopId, zfbShopId));
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 支付宝每日限单数 配置列表
     */
    @GetMapping("/get/zfb/limit")
    public Result<List<ZfbShopOrderDayLimit>> getZfbShopOrderDayLimit() {
        List<ZfbShopOrderDayLimit> orderDayLimits = beanSearcher.searchAll(ZfbShopOrderDayLimit.class, MapUtils.flatBuilder(request.getParameterMap()).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(orderDayLimits);
    }

    /**
     * 编辑支付宝限制单数配置
     */
    @PutMapping("/update/zfb/limit")
    public Result<String> updateZfbShopOrderDayLimit(ZfbShopOrderDayLimit zfbShopOrderDayLimit) {
        zfbShopOrderDayLimitMapper.updateById(zfbShopOrderDayLimit);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 新增支付宝限制单数配置
     */
    @PostMapping("/save/zfb/limit")
    public Result<String> saveZfbShopOrderDayLimit(@RequestBody ZfbShopOrderDayLimit zfbShopOrderDayLimit) {
        zfbShopOrderDayLimit.setHourLimitOrders(RandomUtil.randomInt(zfbShopOrderDayLimit.getHourRandOrdersSt(), zfbShopOrderDayLimit.getHourRandOrdersEnd()));
        zfbShopOrderDayLimit.setHourRemainOrders(zfbShopOrderDayLimit.getHourLimitOrders());
        zfbShopOrderDayLimit.setDayRemainOrders(zfbShopOrderDayLimit.getDayLimitOrders());
        zfbShopOrderDayLimitMapper.insert(zfbShopOrderDayLimit);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    /**
     * 新增支付宝限制单数配置
     */
    @DeleteMapping("/delete/zfb/limit/{id}")
    public Result<String> saveZfbShopOrderDayLimit(@PathVariable Long id) {
        zfbShopOrderDayLimitMapper.deleteById(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }
}
