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

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.Channel;
import com.cyksj.model.entity.ShopConfig;
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;

/**
 * @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;

    @GetMapping
    @SaCheckPermission("merchant:view")
    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())));
        });
        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();
    }
}
