package com.ff.weijinxiao.controller;


import com.ff.weijinxiao.domain.CUser;
import com.ff.weijinxiao.domain.GoodsCategory;
import com.ff.weijinxiao.domain.UserInfo;
import com.ff.weijinxiao.jwt.JwtHelper;
import com.ff.weijinxiao.service.CUserService;
import com.ff.weijinxiao.service.GoodsCategoryService;
import com.ff.weijinxiao.service.UserInfoService;
import com.ff.weijinxiao.util.JsonTool;
import com.ff.weijinxiao.util.RandomUtil;
import com.ff.weijinxiao.util.ResultTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

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

/**
 * 商品分类接口
 */
@RestController
@RequestMapping("api/goodscategory")
@Api(value = "商品分类controller", tags = {"商品分类接口"})
public class GoodsCategoryController {

    @Resource
    private GoodsCategoryService goodsCategoryService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CUserService cUserService;


    public UserInfo getUserInfoByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String openId = JwtHelper.parseToken(token);
        if (StringUtils.isBlank(openId)) {
            return null;
        }

        CUser cUser = cUserService.findByOpenId(openId);
        if (null == cUser) {
            return null;
        }
        return cUser.getUserInfo();
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新商品分类信息", notes = "更新商品分类信息")
    public Map<String, Object> updateGoodsCategory(@RequestBody GoodsCategory goodsCategory, HttpServletRequest request) {
        try {
            goodsCategoryService.saveGoodsCategory(goodsCategory);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建商品分类信息", notes = "创建商品分类信息")
    public Map<String, Object> saveGoodsCategory(@RequestBody GoodsCategory goodsCategory, HttpServletRequest request) {
        try {
            goodsCategory.setOnlyID(RandomUtil.genOnlyId());
            UserInfo userInfo = getUserInfoByToken(request);
            if (null != userInfo) {
                goodsCategory.setUid(userInfo.getUid());
            }
            if (null == goodsCategory.getFatherID()) {
                goodsCategory.setFatherID("0");
            }
            goodsCategoryService.saveGoodsCategory(goodsCategory);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除商品分类信息", notes = "删除商品分类信息")
    public Map<String, Object> deleteGoodsCategory(@ApiParam(required = true, value = "商品分类id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        GoodsCategory goodsCategory = goodsCategoryService.findById(id);
        if (null == goodsCategory) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "商品分类不存在");
        }
        goodsCategoryService.deleteById(id);

        return ResultTool.genSuccessResult("删除成功");
    }

    @GetMapping("/findbyid")
    @ApiOperation(value = "根据id查询商品分类信息", notes = "根据id查询商品分类信息")
    public Map<String, Object> findById(@ApiParam(required = true, value = "商品分类id") @RequestParam String id,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            GoodsCategory goodsCategory = goodsCategoryService.findById(Integer.valueOf(id));
            if (null != goodsCategory) {
                result.put("data", goodsCategory);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }


    @GetMapping("/list")
    @ApiOperation(value = "查询商品分类列表", notes = "查询商品分类列表")
    public Map<String, Object> findList(@ApiParam(required = false, value = "商品分类名字") @RequestParam(required = false) String goodsCategoryName,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        if (null != goodsCategoryName && goodsCategoryName.length() > 0) {
            param.put("LIKE_name", goodsCategoryName);
        }
        List<GoodsCategory> list = goodsCategoryService.findList(param);
        if (null != list && list.size() > 0) {
            result.put("data", list);
            result.put("total", list.size());
            result.put("message", "查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/listpage")
    @ApiOperation(value = "查询商品分类分页列表", notes = "查询商品分类分页列表")
    public Map<String, Object> findListPage(@ApiParam(required = false, value = "商品分类名字") @RequestParam(required = false) String goodsCategoryName,
                                            @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                            @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        param.put("GT_id", 0);
        if (null != goodsCategoryName && goodsCategoryName.length() > 0) {
            param.put("LIKE_name", goodsCategoryName);
        }
        Page<GoodsCategory> list = goodsCategoryService.findPage(pageNo, pageSize, param);
        if (null != list && list.getTotalElements() > 0) {
            List<GoodsCategory> data = list.getContent();
            for (GoodsCategory goodsCategory : data) {
                String fatherId = goodsCategory.getFatherID();
                if (StringUtils.isNotBlank(fatherId)) {
                    GoodsCategory category = goodsCategoryService.findByOnlyID(fatherId);
                    if (null != category) {
                        goodsCategory.setFatherName(category.getName());
                    }
                }
                UserInfo userInfo = userInfoService.findByUid(goodsCategory.getUid());
                if (null != userInfo) {
                    goodsCategory.setUserName(userInfo.getWechatName());
                }
            }
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @PostMapping("/wxapi/create")
    @ApiOperation(value = "创建商品分类信息", notes = "创建商品分类信息")
    public Map<String, Object> createCategory(@RequestBody GoodsCategory goodsCategory, HttpServletRequest request) {
        try {
            if (null == goodsCategory.getFatherID()) {
                goodsCategory.setFatherID("0");
            }
            goodsCategory.setOnlyID(RandomUtil.genOnlyId());
            UserInfo userInfo = getUserInfoByToken(request);
            if (null != userInfo) {
                goodsCategory.setUid(userInfo.getUid());
            }
            goodsCategoryService.saveGoodsCategory(goodsCategory);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/wxapi/update")
    @ApiOperation(value = "更新商品分类信息", notes = "更新商品分类信息")
    public Map<String, Object> wxupdateGoodsCategory(@RequestBody GoodsCategory goodsCategory) {
        try {
            goodsCategoryService.saveGoodsCategory(goodsCategory);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @GetMapping("/wxapi/listpage")
    @ApiOperation(value = "查询商品分类分页列表", notes = "查询商品分类分页列表")
    public Map<String, Object> wxfindListPage(@ApiParam(required = false, value = "商品分类名字") @RequestParam(required = false) String goodsCategoryName,
                                              @ApiParam(required = false, value = "分类级别 1=1级分类 2=2级分类") @RequestParam(required = false) Integer categoryLevel,
                                              @ApiParam(required = false, value = "上级分类id") @RequestParam(required = false) String fatherId,
                                              @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                              @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize,
                                              HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        Map<String, Object> param = new HashMap<>();
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        param.put("GT_id", 0);
        if (StringUtils.isNotBlank(goodsCategoryName)) {
            param.put("LIKE_name", goodsCategoryName);
        }
        if (null != categoryLevel && categoryLevel == 1) {
            param.put("EQ_fatherID", "0");
        }
        if (null != categoryLevel && categoryLevel == 2) {
            param.put("NEQ_fatherID", "0");
        }
        if (StringUtils.isNotBlank(fatherId)) {
            param.put("EQ_fatherID", fatherId);
        }
        param.put("EQ_uid", userInfo.getUid());
        Page<GoodsCategory> list = goodsCategoryService.findPage(pageNo, pageSize, param);
        if (null != list && list.getTotalElements() > 0) {
            List<GoodsCategory> data = list.getContent();
            for (GoodsCategory goodsCategory : data) {
                String fId = goodsCategory.getFatherID();
                if (StringUtils.isNotBlank(fId)) {
                    GoodsCategory category = goodsCategoryService.findByOnlyID(fId);
                    if (null != category) {
                        goodsCategory.setFatherName(category.getName());
                    }
                }
                goodsCategory.setUserName(userInfo.getWechatName());
            }
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/wxapi/listall")
    @ApiOperation(value = "查询商品分类分页列表", notes = "查询商品分类分页列表")
    public Map<String, Object> listall(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_uid", userInfo.getUid());
        List<GoodsCategory> list = goodsCategoryService.findList(param);
        if (null != list && list.size() > 0) {
            for (GoodsCategory goodsCategory : list) {
                goodsCategory.setUserName(userInfo.getWechatName());
            }
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @PostMapping("/wxapi/delete")
    @ApiOperation(value = "删除商品分类信息", notes = "删除商品分类信息")
    public Map<String, Object> wxdeleteGoodsCategory(@ApiParam(required = true, value = "商品分类id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        GoodsCategory goodsCategory = goodsCategoryService.findById(id);
        if (null == goodsCategory) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "商品分类不存在");
        }
        goodsCategoryService.deleteById(id);

        return ResultTool.genSuccessResult("删除成功");
    }
}
