package com.liquidnet.client.admin.web.controller.zhengzai.goblin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.liquidnet.client.admin.common.annotation.Log;
import com.liquidnet.client.admin.common.core.controller.BaseController;
import com.liquidnet.client.admin.common.core.domain.AjaxResult;
import com.liquidnet.client.admin.common.core.page.TableDataInfo;
import com.liquidnet.client.admin.common.core.text.Convert;
import com.liquidnet.client.admin.common.enums.BusinessType;
import com.liquidnet.client.admin.common.utils.ShiroUtils;
import com.liquidnet.client.admin.zhengzai.goblin.service.IGoblinSelfGoodsCategoryService;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.goblin.entity.GoblinSelfGoodsCategory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Api(tags = "商品分类")
@Controller
@RequestMapping("goblin/category")
public class GoblinSelfCategoryAdminController extends BaseController {
    private final String prefix = "zhengzai/goblin/category";
    @Value("${liquidnet.client.admin.platformUrl}")
    private String platformUrl;
    @Autowired
    IGoblinSelfGoodsCategoryService goblinSelfGoodsCategoryService;

    @GetMapping()
    public String category(ModelMap mmap) {
        mmap.put("platformUrl", platformUrl);
        return prefix.concat("/category");
    }

    @RequiresPermissions("goblin:category:list")
    @RequestMapping("list")
    @ResponseBody
    public TableDataInfo list() {
//        PageHelper.startPage(0, 1000, "mid");
//        return getDataTable(goblinSelfGoodsCategoryService.listForMultiGrade());
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(goblinSelfGoodsCategoryService.listForMultiGrade());
        return rspData;
    }

    @ApiOperation(value = "筛选")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "grade", value = "分类层级[1-一级|2-二级|3-三级]", allowableValues = "1,2,3"),
            @ApiImplicitParam(type = "form", required = false, dataType = "String", name = "cateId", value = "分类父ID[30]"),
    })
    @RequiresPermissions("goblin:category:filter")
    @PostMapping("filter")
    @ResponseBody
    public AjaxResult filter(@RequestParam String grade, @RequestParam String cateId) {
        LambdaQueryWrapper<GoblinSelfGoodsCategory> queryWrapper = Wrappers.lambdaQuery(GoblinSelfGoodsCategory.class);
        switch (grade) {
            case "1":
                break;
            case "2":
            case "3":
                if (StringUtils.isBlank(cateId)) {
                    return AjaxResult.warn("请指定商品分类");
                }
                queryWrapper.eq(GoblinSelfGoodsCategory::getCatePid, cateId);
                break;
            default:
                logger.warn("店铺管理:商品分类:筛选:无效参数[grade={},cateId={}]", grade, cateId);
                return AjaxResult.warn("无效参数");
        }
        queryWrapper.eq(GoblinSelfGoodsCategory::getGrade, grade);
        queryWrapper.eq(GoblinSelfGoodsCategory::getDelFlg, "0");

        queryWrapper.select(GoblinSelfGoodsCategory::getCateId, GoblinSelfGoodsCategory::getName, GoblinSelfGoodsCategory::getIcon, GoblinSelfGoodsCategory::getNeIsbn);
        queryWrapper.orderByAsc(GoblinSelfGoodsCategory::getCateId);
        return AjaxResult.success(goblinSelfGoodsCategoryService.list(queryWrapper));
    }

    @ApiOperation(value = "新建")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "grade", value = "分类层级[1-一级|2-二级|3-三级]", allowableValues = "1,2,3"),
            @ApiImplicitParam(type = "form", required = false, dataType = "String", name = "catePid", value = "分类父ID[30]"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "name", value = "分类名称[50]"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "icon", value = "分类图标[256]"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "neIsbn", value = "是否需要填写ISBN[0-否|1-是]", allowableValues = "0,1"),
            @ApiImplicitParam(type = "form", required = false, dataType = "Integer", name = "sort", value = "排序[数值越小,排序越前]", example = "1"),
    })
    @Log(title = "店铺管理:商品分类:新建", businessType = BusinessType.INSERT)
    @RequiresPermissions("goblin:category:add")
    @PostMapping("addSave")
    @ResponseBody
    public AjaxResult addSave(GoblinSelfGoodsCategory selfGoodsCategory) {
        String name = selfGoodsCategory.getName();
        if (StringUtils.isBlank(name)) {
            return AjaxResult.warn("分类名称不能为空");
        }
        String grade = selfGoodsCategory.getGrade();
        if (StringUtils.isBlank(grade)) {
            return AjaxResult.warn("分类层级不能为空");
        }
        String catePid = selfGoodsCategory.getCatePid();
        if (!grade.equals("1") && StringUtils.isBlank(catePid)) {
            return AjaxResult.warn("父级分类未指定");
        }
        GoblinSelfGoodsCategory catePidObj;
        LambdaQueryWrapper<GoblinSelfGoodsCategory> queryWrapper = Wrappers.lambdaQuery(GoblinSelfGoodsCategory.class);
        queryWrapper.eq(GoblinSelfGoodsCategory::getDelFlg, "0");
        switch (grade) {
            case "1":
                selfGoodsCategory.setCatePid(null);
                queryWrapper.eq(GoblinSelfGoodsCategory::getGrade, "1");
                queryWrapper.eq(GoblinSelfGoodsCategory::getName, name.trim());
                if (goblinSelfGoodsCategoryService.count(queryWrapper) > 0) {
                    return AjaxResult.warn("分类名称重复，请核实");
                }
                break;
            case "2":
                queryWrapper.eq(GoblinSelfGoodsCategory::getCateId, catePid).eq(GoblinSelfGoodsCategory::getGrade, "1");
                catePidObj = goblinSelfGoodsCategoryService.getOne(queryWrapper);
                if (null == catePidObj) {
                    return AjaxResult.warn("父级分类无效");
                }
                if (catePidObj.getName().equals(name.trim())) {
                    return AjaxResult.warn("分类名称与父级分类重复，请核实");
                }
//                if (goblinSelfGoodsCategoryService.countForMatchName(catePid, name.trim()) > 0) {
//                    return AjaxResult.warn("分类名称重复，请核实");
//                }
                break;
            case "3":
                queryWrapper.eq(GoblinSelfGoodsCategory::getCateId, catePid).eq(GoblinSelfGoodsCategory::getGrade, "2");
                catePidObj = goblinSelfGoodsCategoryService.getOne(queryWrapper);
                if (null == catePidObj) {
                    return AjaxResult.warn("父级分类无效");
                }
//                if (catePidObj.getName().equals(name.trim())) {
//                    return AjaxResult.warn("分类名称与父级分类重复，请核实");
//                }
//                if (goblinSelfGoodsCategoryService.countForMatchName(catePidObj.getCatePid(), name.trim()) > 0) {
//                    return AjaxResult.warn("分类名称重复，请核实");
//                }
                break;
            default:
                return AjaxResult.warn("分类层级无效");
        }

        selfGoodsCategory.setCateId(IDGenerator.nextMilliId2());
        selfGoodsCategory.setDelFlg("0");
        if (null == selfGoodsCategory.getSort()) {
            selfGoodsCategory.setSort(1);
        }
        selfGoodsCategory.setDelFlg("0");
        selfGoodsCategory.setCounts(0);
        selfGoodsCategory.setCreatedBy(ShiroUtils.getLoginName());
        selfGoodsCategory.setCreatedAt(LocalDateTime.now());

        return toAjax(goblinSelfGoodsCategoryService.addSave(selfGoodsCategory));
    }

    @Log(title = "店铺管理:商品分类:删除", businessType = BusinessType.DELETE)
    @RequiresPermissions("goblin:category:rmv")
    @PostMapping("rmv/{cateId}")
    @ResponseBody
    public AjaxResult rmv(@PathVariable("cateId") String cateId) {
        if (StringUtils.isBlank(cateId)) {
            return AjaxResult.warn("请选择至少一条数据操作");
        }
        return toAjax(goblinSelfGoodsCategoryService.remove(Convert.toStrArray(cateId)));
    }
}
