package com.heketai.website.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.heketai.website.common.result.BaseResult;
import com.heketai.website.common.result.HttpCode;
import com.heketai.website.common.utils.DateUtil;
import com.heketai.website.entity.ProductCategory;
import com.heketai.website.entity.ProductCategoryAttr;
import com.heketai.website.entity.dto.BaseVo;
import com.heketai.website.entity.dto.ProductCategoryDto;
import com.heketai.website.entity.dto.ProductCategoryVo;
import com.heketai.website.service.IProductCategoryAttrService;
import com.heketai.website.service.IProductCategoryService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 产品分类 前端控制器
 * </p>
 *
 * @author xjl
 * @since 2019-12-16
 */
@RestController
@RequestMapping("/productCategory")
public class ProductCategoryController {
    public static final Logger log = LoggerFactory.getLogger(ProductCategoryController.class);
    @Autowired
    IProductCategoryService categoryService;

    @Autowired
    IProductCategoryAttrService attrService;

    @Autowired
    private RedisTemplate redisTemplate;
    private String fKey = "43AF2D04-4B1F-1DEC-11B9-431BCC8F6E7C";

    @RequestMapping("/op/insert")
    @ApiOperation(value = "新增分类", notes = "新增分类")
    public BaseResult insert(@RequestBody ProductCategory category) {
        if (!StringUtils.isEmpty(category.getId())) {
            return BaseResult.fail(HttpCode.FAIL.getCode(), "参数错误!");
        }
        if (StringUtils.isEmpty(category.getNameCh()) || StringUtils.isEmpty(category.getNameEn())) {
            return BaseResult.fail(HttpCode.FAIL.getCode(), "分类名称不能为空!");
        }

        if (!StringUtils.isEmpty(category.getParentId())) {
            ProductCategory parent = new ProductCategory();
            parent.setId(category.getParentId());
            parent = categoryService.selectById(parent);
            if (parent == null) {
                return BaseResult.fail(HttpCode.FAIL.getCode(), "参数错误!");
            }
        }
        String datetime = DateUtil.getDateTime();
        category.setCreateTime(datetime);
        category.setUpdateTime(datetime);

        categoryService.insert(category);

        redisTemplate.delete(fKey);
        return BaseResult.success();
    }

    @RequestMapping("/op/deleteById")
    @ApiOperation(value = "删除分类", notes = "删除分类")
    public BaseResult deleteById(@RequestParam Integer id) {

        ProductCategory category = new ProductCategory();
        category.setParentId(id);
        EntityWrapper<ProductCategory> wrapper = new EntityWrapper<>();
        wrapper.setEntity(category);
        List<ProductCategory> list = categoryService.selectList(wrapper);
        if (list != null && list.size() > 0) {
            return BaseResult.fail(HttpCode.FAIL.getCode(), "该分类不可删除");
        }

        ProductCategoryAttr attr = new ProductCategoryAttr();
        attr.setCategoryId(id);
        EntityWrapper<ProductCategoryAttr> entityWrapper = new EntityWrapper<>();
        entityWrapper.setEntity(attr);
        List<ProductCategoryAttr> TempList = attrService.selectList(entityWrapper);
        if (TempList != null && TempList.size() > 0) {
            return BaseResult.fail(HttpCode.FAIL.getCode(), "该分类不可删除");
        }

        categoryService.deleteById(id);

        redisTemplate.delete(fKey);

        return BaseResult.success();
    }

    @RequestMapping("/op/update")
    @ApiOperation(value = "修改分类", notes = "修改分类")
    public BaseResult update(@RequestBody ProductCategory category) {

        if (!StringUtils.isEmpty(category.getParentId())) {
            ProductCategory parent = new ProductCategory();
            parent.setId(category.getParentId());
            parent = categoryService.selectById(parent);
            if (parent == null) {
                return BaseResult.fail(HttpCode.FAIL.getCode(), "参数错误!");
            }
        }

        categoryService.updateById(category);
        redisTemplate.delete(fKey);
        return BaseResult.success();
    }

    @GetMapping("/findList")
    @ApiOperation(value = "查询分类", notes = "查询分类")
    @Transactional(propagation = Propagation.REQUIRED)
    public BaseResult findList(@RequestParam(value = "sort", required = false) Integer sort) {
        try {
            String key = "1CFE2701-8460-8435-9D16-3F79DB8FA228" + sort;
            Object obj = redisTemplate.boundHashOps(fKey).get(key);
            if (null != obj) {
                List<ProductCategoryDto> voList = JSON.parseArray(obj.toString(), ProductCategoryDto.class);
                return BaseResult.successWithData(voList);
            }

            EntityWrapper<ProductCategory> wrapper = new EntityWrapper<>();
            ProductCategory productCategory = new ProductCategory();
            productCategory.setSort(sort);
            wrapper.setEntity(productCategory);
            List<ProductCategory> list = categoryService.selectList(wrapper);
            List<ProductCategoryDto> voList = new ArrayList<>();
            for (ProductCategory category : list) {
                if (0 != category.getParentId()) {
                    for (ProductCategoryDto dto : voList) {
                        if (category.getParentId().equals(dto.getId())) {
                            category.setParentName(dto.getNameCh());
                            dto.getSubCatgory().add(category);
                            break;
                        }
                    }
                } else {
                    ProductCategoryDto dto = new ProductCategoryDto();
                    BeanUtils.copyProperties(category, dto);
                    dto.setParentName("一级分类");
                    voList.add(dto);
                }
            }

            redisTemplate.boundHashOps(fKey).put(key, JSON.toJSONString(voList));
            return BaseResult.successWithData(voList);
        } catch (Exception e) {
            log.error("Get, /productCategory/findList, 查询分类失败：[{}]", e.getMessage(), sort, e);
            return BaseResult.fail("查询分类失败");
        }

    }


    @PostMapping("/findList")
    @ApiOperation(value = "门户分类", notes = "门户分类")
    @Transactional(propagation = Propagation.REQUIRED)
    public BaseResult findList1(@RequestBody ProductCategory productCategory) {
        try {
            String key = "781F8BF873C2E69168D4" + JSON.toJSONString(productCategory);
            Object obj = redisTemplate.boundHashOps(fKey).get(key);
            if (null != obj) {
                List<BaseVo> voList = JSON.parseArray(obj.toString(), BaseVo.class);
                return BaseResult.successWithData(voList);
            }

            List<ProductCategory> list = categoryService.selectList(new EntityWrapper<>());
            List<BaseVo> voList = new ArrayList<>();
            for (ProductCategory category : list) {
                if (0 != category.getParentId()) {
                    for (BaseVo dto : voList) {
                        if (category.getParentId().equals(dto.getId())) {
                            Map<String, String> map = new HashMap<>();
                            if (productCategory.getLanguage() == 1) {
                                map.put("name", category.getNameCh());
                            } else {
                                map.put("name", category.getNameEn());
                            }
                            map.put("id", category.getId() + "");
                            dto.getSubCatgory().add(map);
                            break;
                        }
                    }
                } else {
                    BaseVo baseVo = new BaseVo();
                    baseVo.setId(category.getId());
                    if (productCategory.getLanguage() == 1) {
                        baseVo.setName(category.getNameCh());
                    } else {
                        baseVo.setName(category.getNameEn());
                    }
                    voList.add(baseVo);
                }
            }
            redisTemplate.boundHashOps(fKey).put(key, JSON.toJSONString(voList));
            return BaseResult.successWithData(voList);
        } catch (Exception e){
            log.error("post, /productCategory/findList, 门户分类失败：[{}]", e.getMessage(), productCategory, e);
            return BaseResult.fail("查询 门户分类失败");
        }

    }

    @PostMapping("/findListNew")
    @ApiOperation(value = "门户分类", notes = "门户分类")
    @Transactional(propagation = Propagation.REQUIRED)
    public BaseResult findListNew(@RequestBody ProductCategory productCategory) {
        try {

            List<ProductCategory> list = categoryService.selectList(new EntityWrapper<>());
            List<ProductCategoryVo> voList = new ArrayList<>();
            for (ProductCategory category : list) {
                if (0 != category.getParentId()) {
                    for (ProductCategoryVo dto : voList) {
                        if (category.getParentId().equals(dto.getId())) {

                            ProductCategoryVo baseVo = new ProductCategoryVo();
                            if (productCategory.getLanguage() == 1) {
                                baseVo.setName(category.getNameCh());
                            } else {
                                baseVo.setName(category.getNameCh());
                            }
                            dto.getChildren().add(baseVo);
                            break;
                        }
                    }
                } else {
                    ProductCategoryVo baseVo = new ProductCategoryVo();
                    baseVo.setId(category.getId());
                    if (productCategory.getLanguage() == 1) {
                        baseVo.setName(category.getNameCh());
                    } else {
                        baseVo.setName(category.getNameEn());
                    }
                    voList.add(baseVo);
                }
            }

            return BaseResult.successWithData(voList);
        } catch (Exception e){
            log.error("post, /productCategory/findList, 门户分类失败：[{}]", e.getMessage(), productCategory, e);
            return BaseResult.fail("查询 门户分类失败");
        }

    }

    @GetMapping("/findListNew")
    @ApiOperation(value = "查询分类", notes = "查询分类")
    @Transactional(propagation = Propagation.REQUIRED)
    public BaseResult findListNew(@RequestParam(value = "sort", required = false) Integer sort) {
        try {

            EntityWrapper<ProductCategory> wrapper = new EntityWrapper<>();
            ProductCategory productCategory = new ProductCategory();
            productCategory.setSort(sort);
            wrapper.setEntity(productCategory);
            List<ProductCategory> list = categoryService.selectList(wrapper);
            List<ProductCategoryVo> voList = new ArrayList<>();
            for (ProductCategory category : list) {
                if (0 != category.getParentId()) {
                    for (ProductCategoryVo dto : voList) {
                        List<ProductCategoryVo> productCategoryVos = new ArrayList<>();
                        if (category.getParentId().equals(dto.getId())) {
                            if(dto.getChildren() == null ) {
                                dto.setChildren(productCategoryVos);
                            }

                            ProductCategoryVo productCategoryVo = new ProductCategoryVo();
                            productCategoryVo.setId(category.getId());
                            productCategoryVo.setName(category.getNameCh());
                            productCategoryVo.setLevel(3);
                            dto.getChildren().add(productCategoryVo);
                            break;
                        }
                    }
                } else {
                    ProductCategoryVo dto = new ProductCategoryVo();
                    dto.setId(category.getId());
                    dto.setName(category.getNameCh());
                    dto.setLevel(2);
                    voList.add(dto);
                }
            }

            return BaseResult.successWithData(voList);
        } catch (Exception e) {
            log.error("Get, /productCategory/findList, 查询分类失败：[{}]", e.getMessage(), sort, e);
            return BaseResult.fail("查询分类失败");
        }

    }


}
