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

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.annotation.Log;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.BusinessType;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.model.entity.GoodsDonSku;
import com.cyksj.model.entity.UpgradePackage;
import com.cyksj.model.views.UpgradePackageView;
import com.cyksj.service.mange.upgrade.UpgradePackageService;
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.Map;
import java.util.stream.Collectors;


/**
 * @author zwhui
 * @date 2024/4/24 15:06
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/upgrade")
public class UpgradePackageController {

    private final UpgradePackageService upgradePackageService;

    private final HttpServletRequest request;

    private final BeanSearcher beanSearcher;

    private final GoodsDonSkuMapper goodsDonSkuMapper;

    /**
     * 新增套餐
     */
    @PostMapping
    @SaCheckPermission("upgrade:add")
    @Log(module = "套餐管理/新增套餐", businessType = BusinessType.POST, isSaveRequestData = true)
    public Result<String> post(@RequestBody UpgradePackage upgradePackage){
        log.info("新增套餐:{}", upgradePackage);
        upgradePackageService.save(upgradePackage);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 修改套餐
     */
    @PutMapping
    @SaCheckPermission("upgrade:edit")
    @Log(module = "套餐管理/修改套餐", businessType = BusinessType.PUT, isSaveRequestData = true)
    public Result<String> put(@RequestBody UpgradePackage upgradePackage){
        log.info("修改套餐:{}", upgradePackage);
        upgradePackageService.updateById(upgradePackage);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 删除套餐
     */
    @DeleteMapping("/{id}")
    @SaCheckPermission("upgrade:delete")
    @Log(module = "套餐管理/删除套餐", businessType = BusinessType.DELETE, isSaveRequestData = true)
    public Result<String> delete(@PathVariable Long id){
        log.info("删除套餐:{}", id);
        UpgradePackage byId = upgradePackageService.getById(id);
        if (byId == null){
            throw BusinessRuntimeException.getInstance("套餐不存在");
        }
        byId.setDeleted(false);
        upgradePackageService.updateById(byId);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 上下架套餐
     */
    @PutMapping("/put/status/{id}")
    @SaCheckPermission("upgrade:putStatus")
    @Log(module = "套餐管理/上下架套餐", businessType = BusinessType.PUT, isSaveRequestData = true)
    public Result<Boolean> putStatus(@PathVariable Long id){
        log.info("上下架套餐:{}", id);
        UpgradePackage byId = upgradePackageService.getById(id);
        if (byId == null){
            throw BusinessRuntimeException.getInstance("套餐不存在");
        }
        byId.setStatus(!byId.getStatus());
        upgradePackageService.updateById(byId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(byId.getStatus());
    }

    /**
     * 获取套餐
     */
    @GetMapping("/{id}")
    public Result<UpgradePackage> get(@PathVariable Long id){
        log.info("获取套餐:{}", id);
        UpgradePackage byId = upgradePackageService.getById(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult(byId);
    }

    /**
     * 获取套餐列表
     */
    @GetMapping
    public Result<SearchResult<UpgradePackageView>> list(Long skuId) {
        log.info("获取套餐列表");
        Map<String, Object> build = MapUtils.flatBuilder(request.getParameterMap()).build();
        if (skuId != null) {
            build.put("sku", String.format(" and JSON_CONTAINS(up.sku_ids,'\"%s\"')", skuId));
        }
        SearchResult<UpgradePackageView> search = beanSearcher.search(UpgradePackageView.class, build);
        search.getDataList().forEach(upgradePackageView -> {
            try {
                String specVal = goodsDonSkuMapper.selectList(Wrappers.lambdaQuery(GoodsDonSku.class).in(GoodsDonSku::getId, Jsons.parseList(upgradePackageView.getSkuIds(), Long.class))).stream().map(GoodsDonSku::getSpecVal).collect(Collectors.joining(","));
                upgradePackageView.setSpecVal(specVal);
            } catch (Exception e) {
                throw BusinessRuntimeException.getInstance("获取套餐规格失败");
            }
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }


}
