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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.GoodsDon;
import com.cyksj.model.entity.GoodsDonSpec;
import com.cyksj.model.manage.request.ReqGoodsSkuSpec;
import com.cyksj.model.manage.request.ReqGoodsSpecSingle;
import com.cyksj.service.mange.CmsGoodsDonService;
import com.cyksj.service.mange.CmsGoodsDonSpecService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.util.MapUtils;
import com.fasterxml.jackson.databind.JavaType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chan
 * @date 2022/9/27 4:48 PM
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/goods/spec")
public class CmsGoodsDonSpecController {

    private final HttpServletRequest request;

    private final BeanSearcher beanSearcher;

    private final CmsGoodsDonSpecService goodsDonSpecService;

    private final CmsGoodsDonService goodsDonService;

    @PostMapping("/post")
    public Result<String> specAppend(@RequestBody ReqGoodsSpecSingle specSingle) throws Exception {

        GoodsDon goodsDon = beanSearcher.searchFirst(GoodsDon.class, MapUtils.builder().field(GoodsDon::getId, specSingle.getGoodsId()).build());

        if (null == goodsDon) {
            throw new BusinessRuntimeException("","找不到商品spu.");
        }

        GoodsDonSpec v2spec = beanSearcher.searchFirst(GoodsDonSpec.class,MapUtils.builder().field(GoodsDonSpec::getGoodsId,goodsDon.getId()).build());
        if (null == v2spec) {
            throw new BusinessRuntimeException("","该商品未设置总规格, 请设置总规格.");
        }

        List<ReqGoodsSkuSpec> specs = Jsons.parseList(v2spec.getSpecsJson(), ReqGoodsSkuSpec.class);
        for (ReqGoodsSkuSpec e : specs) {
            if (StringUtils.equals(e.getKey(), specSingle.getKey())) {
                List<ReqGoodsSkuSpec.Node> values = e.getValues();

                ReqGoodsSkuSpec.Node node = new ReqGoodsSkuSpec.Node();
                node.setId(specSingle.getId());
                node.setValue(specSingle.getName());
                values.add(node);

                break;
            }
        }
        String specsJson = Jsons.toJson(specs);

        JavaType type = Jsons.javaType().constructMapType(HashMap.class, Integer.class, ReqGoodsSpecSingle.class);
        Map<Integer, ReqGoodsSpecSingle> map = Jsons.parseObject(v2spec.getSpecMapping(), type);
        map.put(specSingle.getId(), specSingle);
        String specMapping = Jsons.toJson(map);

        v2spec.setMaxId(specSingle.getMaxId());
        v2spec.setSpecsJson(specsJson);
        v2spec.setSpecMapping(specMapping);

        goodsDonSpecService.saveOrUpdate(v2spec);

        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 删除 商品spec
     */
    @DeleteMapping(value = "/delete")
    public Result<String> delete(Integer specId, Long goodsId) throws Exception {
        //TODO
        GoodsDonSpec loveSpec = goodsDonSpecService.getOne(Wrappers.lambdaQuery(GoodsDonSpec.class).eq(GoodsDonSpec::getGoodsId,goodsId).last(" limit 1"));
        if (null == loveSpec) {
            throw new RuntimeException("该商品未设置总规格, 请设置总规格.");
        }
        if (specId > loveSpec.getMaxId()) {
            throw new RuntimeException("错误规格属性id.");
        }

        JavaType type = Jsons.javaType().constructMapType(HashMap.class, Integer.class, ReqGoodsSpecSingle.class);
        Map<Long, ReqGoodsSpecSingle> map = Jsons.parseObject(loveSpec.getSpecMapping(), type);
        if (!map.containsKey(specId)) {
            throw new RuntimeException("该id指向的规格属性 不存在.");
        }
        ReqGoodsSpecSingle spec = map.remove(specId);
        String specMapping = Jsons.toJson(map);

        List<ReqGoodsSkuSpec> specs = Jsons.parseList(loveSpec.getSpecsJson(), ReqGoodsSkuSpec.class);
        for (ReqGoodsSkuSpec e : specs) {
            if (StringUtils.equals(e.getKey(), spec.getKey())) {
                e.getValues().removeIf(node -> node.getId().equals(specId));
                break;
            }
        }
        String specsJson = Jsons.toJson(specs);

        loveSpec.setSpecsJson(specsJson);
        loveSpec.setSpecMapping(specMapping);
        goodsDonSpecService.saveOrUpdate(loveSpec);

        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }



}
